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;
163 * The PFlush algorithm makes use of the fact that Fid.Unique is not used in
164 * below hash algorithms. Change it if need be so that flushing algorithm
165 * doesn't move things from one hash chain to another.
167 /*Vnode, Chunk -> Hash table index */
168 int DCHash(struct VenusFid *fid, afs_int32 chunk)
172 buf[0] = fid->Fid.Volume;
173 buf[1] = fid->Fid.Vnode;
175 return opr_jhash(buf, 3, 0) & (afs_dhashsize - 1);
177 /*Vnode -> Other hash table index */
178 int DVHash(struct VenusFid *fid)
180 return opr_jhash_int2(fid->Fid.Volume, fid->Fid.Vnode, 0) &
185 * Where is this vcache's entry associated dcache located/
186 * \param avc The vcache entry.
187 * \return Bucket index:
192 afs_DCGetBucket(struct vcache *avc)
197 /* This should be replaced with some sort of user configurable function */
198 if (avc->f.states & CRO) {
200 } else if (avc->f.states & CBackup) {
210 * Readjust a dcache's size.
212 * \param adc The dcache to be adjusted.
213 * \param oldSize Old size for the dcache.
214 * \param newSize The new size to be adjusted to.
218 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
220 afs_int32 adjustSize = newSize - oldSize;
228 afs_blocksUsed_0 += adjustSize;
229 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
232 afs_blocksUsed_1 += adjustSize;
233 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
236 afs_blocksUsed_2 += adjustSize;
237 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
245 * Move a dcache from one bucket to another.
247 * \param adc Operate on this dcache.
248 * \param size Size in bucket (?).
249 * \param newBucket Destination bucket.
253 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
258 /* Substract size from old bucket. */
262 afs_blocksUsed_0 -= size;
265 afs_blocksUsed_1 -= size;
268 afs_blocksUsed_2 -= size;
272 /* Set new bucket and increase destination bucket size. */
273 adc->bucket = newBucket;
278 afs_blocksUsed_0 += size;
281 afs_blocksUsed_1 += size;
284 afs_blocksUsed_2 += size;
292 * Init split caches size.
297 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
306 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
311 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
312 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
314 /* Short cut: if we don't know about it, try to kill it */
315 if (phase < 2 && afs_blocksUsed_0)
318 if (afs_pct1 > afs_tpct1)
320 if (afs_pct2 > afs_tpct2)
322 return 0; /* unlikely */
327 * Warn about failing to store a file.
329 * \param acode Associated error code.
330 * \param avolume Volume involved.
331 * \param aflags How to handle the output:
332 * aflags & 1: Print out on console
333 * aflags & 2: Print out on controlling tty
335 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
339 afs_StoreWarn(afs_int32 acode, afs_int32 avolume,
342 static char problem_fmt[] =
343 "afs: failed to store file in volume %d (%s)\n";
344 static char problem_fmt_w_error[] =
345 "afs: failed to store file in volume %d (error %d)\n";
346 static char netproblems[] = "network problems";
347 static char partfull[] = "partition full";
348 static char overquota[] = "over quota";
350 AFS_STATCNT(afs_StoreWarn);
356 afs_warn(problem_fmt, avolume, netproblems);
358 afs_warnuser(problem_fmt, avolume, netproblems);
359 } else if (acode == ENOSPC) {
364 afs_warn(problem_fmt, avolume, partfull);
366 afs_warnuser(problem_fmt, avolume, partfull);
369 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
370 * Instead ENOSPC will be sent...
372 if (acode == EDQUOT) {
377 afs_warn(problem_fmt, avolume, overquota);
379 afs_warnuser(problem_fmt, avolume, overquota);
387 afs_warn(problem_fmt_w_error, avolume, acode);
389 afs_warnuser(problem_fmt_w_error, avolume, acode);
394 * Try waking up truncation daemon, if it's worth it.
397 afs_MaybeWakeupTruncateDaemon(void)
399 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
400 afs_CacheTooFullCount++;
401 afs_CacheTooFull = 1;
402 if (!afs_TruncateDaemonRunning)
403 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
404 } else if (!afs_TruncateDaemonRunning
405 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
406 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
413 * Keep statistics on run time for afs_CacheTruncateDaemon. This is a
414 * struct so we need only export one symbol for AIX.
416 static struct CTD_stats {
417 osi_timeval32_t CTD_beforeSleep;
418 osi_timeval32_t CTD_afterSleep;
419 osi_timeval32_t CTD_sleepTime;
420 osi_timeval32_t CTD_runTime;
424 u_int afs_min_cache = 0;
427 * If there are waiters for the cache to drain, wake them if
428 * the number of free or discarded cache blocks reaches the
429 * CM_CACHESIZEDDRAINEDPCT limit.
432 * This routine must be called with the afs_xdcache lock held
436 afs_WakeCacheWaitersIfDrained(void)
438 if (afs_WaitForCacheDrain) {
439 if ((afs_blocksUsed - afs_blocksDiscarded) <=
440 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
441 afs_WaitForCacheDrain = 0;
442 afs_osi_Wakeup(&afs_WaitForCacheDrain);
448 * Keeps the cache clean and free by truncating uneeded files, when used.
453 afs_CacheTruncateDaemon(void)
455 osi_timeval32_t CTD_tmpTime;
459 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
461 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
463 osi_GetTime(&CTD_stats.CTD_afterSleep);
464 afs_TruncateDaemonRunning = 1;
466 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
467 ObtainWriteLock(&afs_xdcache, 266);
468 if (afs_CacheTooFull || afs_WaitForCacheDrain) {
469 int space_needed, slots_needed;
470 /* if we get woken up, we should try to clean something out */
471 for (counter = 0; counter < 10; counter++) {
473 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
474 if (space_needed < 0)
477 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
478 if (slots_needed < 0)
480 if (slots_needed || space_needed)
481 afs_GetDownD(slots_needed, &space_needed, 0);
482 if ((space_needed <= 0) && (slots_needed <= 0)) {
485 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
488 if (!afs_CacheIsTooFull()) {
489 afs_CacheTooFull = 0;
490 afs_WakeCacheWaitersIfDrained();
492 } /* end of cache cleanup */
493 ReleaseWriteLock(&afs_xdcache);
496 * This is a defensive check to try to avoid starving threads
497 * that may need the global lock so thay can help free some
498 * cache space. If this thread won't be sleeping or truncating
499 * any cache files then give up the global lock so other
500 * threads get a chance to run.
502 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
503 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
504 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
508 * This is where we free the discarded cache elements.
510 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
511 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
512 int code = afs_FreeDiscardedDCache();
514 /* If we can't free any discarded dcache entries, that's okay.
515 * We're just doing this in the background; if someone needs
516 * discarded entries freed, they will try it themselves and/or
517 * signal us that the cache is too full. In any case, we'll
518 * try doing this again the next time we run through the loop.
524 /* See if we need to continue to run. Someone may have
525 * signalled us while we were executing.
527 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
528 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
529 /* Collect statistics on truncate daemon. */
530 CTD_stats.CTD_nSleeps++;
531 osi_GetTime(&CTD_stats.CTD_beforeSleep);
532 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
533 CTD_stats.CTD_beforeSleep);
534 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
536 afs_TruncateDaemonRunning = 0;
537 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
538 afs_TruncateDaemonRunning = 1;
540 osi_GetTime(&CTD_stats.CTD_afterSleep);
541 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
542 CTD_stats.CTD_afterSleep);
543 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
545 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
546 afs_termState = AFSOP_STOP_AFSDB;
547 afs_osi_Wakeup(&afs_termState);
555 * Make adjustment for the new size in the disk cache entry
557 * \note Major Assumptions Here:
558 * Assumes that frag size is an integral power of two, less one,
559 * and that this is a two's complement machine. I don't
560 * know of any filesystems which violate this assumption...
562 * \param adc Ptr to dcache entry.
563 * \param anewsize New size desired.
568 afs_AdjustSize(struct dcache *adc, afs_int32 newSize)
572 AFS_STATCNT(afs_AdjustSize);
574 if (newSize > afs_OtherCSize && !(adc->f.fid.Fid.Vnode & 1)) {
575 /* No non-dir cache files should be larger than the chunk size.
576 * (Directory blobs are fetched in a single chunk file, so directories
577 * can be larger.) If someone is requesting that a chunk is larger than
578 * the chunk size, something strange is happening. Log a message about
579 * it, to give a hint to subsequent strange behavior, if any occurs. */
583 afs_warn("afs: Warning: dcache %d is very large (%d > %d). This "
584 "should not happen, but trying to continue regardless. If "
585 "AFS starts hanging or behaving strangely, this might be "
587 adc->index, newSize, afs_OtherCSize);
591 adc->dflags |= DFEntryMod;
592 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
593 adc->f.chunkBytes = newSize;
596 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
597 afs_DCAdjustSize(adc, oldSize, newSize);
598 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
600 /* We're growing the file, wakeup the daemon */
601 afs_MaybeWakeupTruncateDaemon();
603 afs_blocksUsed += (newSize - oldSize);
604 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
609 * This routine is responsible for moving at least one entry (but up
610 * to some number of them) from the LRU queue to the free queue.
612 * \param anumber Number of entries that should ideally be moved.
613 * \param aneedSpace How much space we need (1K blocks);
616 * The anumber parameter is just a hint; at least one entry MUST be
617 * moved, or we'll panic. We must be called with afs_xdcache
618 * write-locked. We should try to satisfy both anumber and aneedspace,
619 * whichever is more demanding - need to do several things:
620 * 1. only grab up to anumber victims if aneedSpace <= 0, not
621 * the whole set of MAXATONCE.
622 * 2. dynamically choose MAXATONCE to reflect severity of
623 * demand: something like (*aneedSpace >> (logChunk - 9))
625 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
626 * indicates that the cache is not properly configured/tuned or
627 * something. We should be able to automatically correct that problem.
630 #define MAXATONCE 16 /* max we can obtain at once */
632 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
636 struct VenusFid *afid;
641 afs_uint32 victims[MAXATONCE];
642 struct dcache *victimDCs[MAXATONCE];
643 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
644 afs_uint32 victimPtr; /* next free item in victim arrays */
645 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
646 afs_uint32 maxVictimPtr; /* where it is */
650 AFS_STATCNT(afs_GetDownD);
652 if (CheckLock(&afs_xdcache) != -1)
653 osi_Panic("getdownd nolock");
654 /* decrement anumber first for all dudes in free list */
655 /* SHOULD always decrement anumber first, even if aneedSpace >0,
656 * because we should try to free space even if anumber <=0 */
657 if (!aneedSpace || *aneedSpace <= 0) {
658 anumber -= afs_freeDCCount;
660 return; /* enough already free */
664 /* bounds check parameter */
665 if (anumber > MAXATONCE)
666 anumber = MAXATONCE; /* all we can do */
668 /* rewrite so phases include a better eligiblity for gc test*/
670 * The phase variable manages reclaims. Set to 0, the first pass,
671 * we don't reclaim active entries, or other than target bucket.
672 * Set to 1, we reclaim even active ones in target bucket.
673 * Set to 2, we reclaim any inactive one.
674 * Set to 3, we reclaim even active ones. On Solaris, we also reclaim
675 * entries whose corresponding vcache has a nonempty multiPage list, when
684 for (i = 0; i < afs_cacheFiles; i++)
685 /* turn off all flags */
686 afs_indexFlags[i] &= ~IFFlag;
688 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
689 /* find oldest entries for reclamation */
690 maxVictimPtr = victimPtr = 0;
691 hzero(maxVictimTime);
692 curbucket = afs_DCWhichBucket(phase, buckethint);
693 /* select victims from access time array */
694 for (i = 0; i < afs_cacheFiles; i++) {
695 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
696 /* skip if dirty or already free */
699 tdc = afs_indexTable[i];
700 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
702 /* Wrong bucket; can't use it! */
705 if (tdc && (tdc->refCount != 0)) {
706 /* Referenced; can't use it! */
709 hset(vtime, afs_indexTimes[i]);
711 /* if we've already looked at this one, skip it */
712 if (afs_indexFlags[i] & IFFlag)
715 if (victimPtr < MAXATONCE) {
716 /* if there's at least one free victim slot left */
717 victims[victimPtr] = i;
718 hset(victimTimes[victimPtr], vtime);
719 if (hcmp(vtime, maxVictimTime) > 0) {
720 hset(maxVictimTime, vtime);
721 maxVictimPtr = victimPtr;
724 } else if (hcmp(vtime, maxVictimTime) < 0) {
726 * We're older than youngest victim, so we replace at
729 /* find youngest (largest LRU) victim */
732 osi_Panic("getdownd local");
734 hset(victimTimes[j], vtime);
735 /* recompute maxVictimTime */
736 hset(maxVictimTime, vtime);
737 for (j = 0; j < victimPtr; j++)
738 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
739 hset(maxVictimTime, victimTimes[j]);
745 /* now really reclaim the victims */
746 j = 0; /* flag to track if we actually got any of the victims */
747 /* first, hold all the victims, since we're going to release the lock
748 * during the truncate operation.
750 for (i = 0; i < victimPtr; i++) {
751 tdc = afs_GetValidDSlot(victims[i]);
752 /* We got tdc->tlock(R) here */
753 if (tdc && tdc->refCount == 1)
758 ReleaseReadLock(&tdc->tlock);
763 for (i = 0; i < victimPtr; i++) {
764 /* q is first elt in dcache entry */
766 /* now, since we're dropping the afs_xdcache lock below, we
767 * have to verify, before proceeding, that there are no other
768 * references to this dcache entry, even now. Note that we
769 * compare with 1, since we bumped it above when we called
770 * afs_GetValidDSlot to preserve the entry's identity.
772 if (tdc && tdc->refCount == 1) {
773 unsigned char chunkFlags;
774 afs_size_t tchunkoffset = 0;
776 /* xdcache is lower than the xvcache lock */
777 ReleaseWriteLock(&afs_xdcache);
778 ObtainReadLock(&afs_xvcache);
779 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
780 ReleaseReadLock(&afs_xvcache);
781 ObtainWriteLock(&afs_xdcache, 527);
783 if (tdc->refCount > 1)
786 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
787 chunkFlags = afs_indexFlags[tdc->index];
788 if (((phase & 1) == 0) && osi_Active(tvc))
790 if (((phase & 1) == 1) && osi_Active(tvc)
791 && (tvc->f.states & CDCLock)
792 && (chunkFlags & IFAnyPages))
794 if (chunkFlags & IFDataMod)
796 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
797 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
798 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
799 ICL_HANDLE_OFFSET(tchunkoffset));
801 #if defined(AFS_SUN5_ENV)
803 * Now we try to invalidate pages. We do this only for
804 * Solaris. For other platforms, it's OK to recycle a
805 * dcache entry out from under a page, because the strategy
806 * function can call afs_GetDCache().
808 if (!skip && (chunkFlags & IFAnyPages)) {
811 ReleaseWriteLock(&afs_xdcache);
812 ObtainWriteLock(&tvc->vlock, 543);
813 if (!QEmpty(&tvc->multiPage)) {
814 if (phase < 3 || osi_VM_MultiPageConflict(tvc, tdc)) {
819 /* block locking pages */
820 tvc->vstates |= VPageCleaning;
821 /* block getting new pages */
823 ReleaseWriteLock(&tvc->vlock);
824 /* One last recheck */
825 ObtainWriteLock(&afs_xdcache, 333);
826 chunkFlags = afs_indexFlags[tdc->index];
827 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
828 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
829 && (chunkFlags & IFAnyPages))) {
831 ReleaseWriteLock(&afs_xdcache);
834 ReleaseWriteLock(&afs_xdcache);
836 code = osi_VM_GetDownD(tvc, tdc);
838 ObtainWriteLock(&afs_xdcache, 269);
839 /* we actually removed all pages, clean and dirty */
841 afs_indexFlags[tdc->index] &=
842 ~(IFDirtyPages | IFAnyPages);
845 ReleaseWriteLock(&afs_xdcache);
847 ObtainWriteLock(&tvc->vlock, 544);
848 if (--tvc->activeV == 0
849 && (tvc->vstates & VRevokeWait)) {
850 tvc->vstates &= ~VRevokeWait;
851 afs_osi_Wakeup((char *)&tvc->vstates);
854 if (tvc->vstates & VPageCleaning) {
855 tvc->vstates &= ~VPageCleaning;
856 afs_osi_Wakeup((char *)&tvc->vstates);
859 ReleaseWriteLock(&tvc->vlock);
861 #endif /* AFS_SUN5_ENV */
863 ReleaseWriteLock(&afs_xdcache);
866 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
867 ObtainWriteLock(&afs_xdcache, 528);
868 if (afs_indexFlags[tdc->index] &
869 (IFDataMod | IFDirtyPages | IFAnyPages))
871 if (tdc->refCount > 1)
874 #if defined(AFS_SUN5_ENV)
876 /* no vnode, so IFDirtyPages is spurious (we don't
877 * sweep dcaches on vnode recycling, so we can have
878 * DIRTYPAGES set even when all pages are gone). Just
880 * Hold vcache lock to prevent vnode from being
881 * created while we're clearing IFDirtyPages.
883 afs_indexFlags[tdc->index] &=
884 ~(IFDirtyPages | IFAnyPages);
888 /* skip this guy and mark him as recently used */
889 afs_indexFlags[tdc->index] |= IFFlag;
890 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
891 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
892 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
893 ICL_HANDLE_OFFSET(tchunkoffset));
895 /* flush this dude from the data cache and reclaim;
896 * first, make sure no one will care that we damage
897 * it, by removing it from all hash tables. Then,
898 * melt it down for parts. Note that any concurrent
899 * (new possibility!) calls to GetDownD won't touch
900 * this guy because his reference count is > 0. */
901 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
902 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
903 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
904 ICL_HANDLE_OFFSET(tchunkoffset));
905 AFS_STATCNT(afs_gget);
906 afs_HashOutDCache(tdc, 1);
907 if (tdc->f.chunkBytes != 0) {
911 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
916 afs_DiscardDCache(tdc);
921 j = 1; /* we reclaimed at least one victim */
926 } /* end of for victims loop */
929 /* Phase is 0 and no one was found, so try phase 1 (ignore
930 * osi_Active flag) */
933 for (i = 0; i < afs_cacheFiles; i++)
934 /* turn off all flags */
935 afs_indexFlags[i] &= ~IFFlag;
938 /* found no one in phases 0-5, we're hosed */
942 } /* big while loop */
950 * Remove adc from any hash tables that would allow it to be located
951 * again by afs_FindDCache or afs_GetDCache.
953 * \param adc Pointer to dcache entry to remove from hash tables.
955 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
959 afs_HashOutDCache(struct dcache *adc, int zap)
963 AFS_STATCNT(afs_glink);
965 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
967 /* if this guy is in the hash table, pull him out */
968 if (adc->f.fid.Fid.Volume != 0) {
969 /* remove entry from first hash chains */
970 i = DCHash(&adc->f.fid, adc->f.chunk);
971 us = afs_dchashTbl[i];
972 if (us == adc->index) {
973 /* first dude in the list */
974 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
976 /* somewhere on the chain */
977 while (us != NULLIDX) {
978 if (afs_dcnextTbl[us] == adc->index) {
979 /* found item pointing at the one to delete */
980 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
983 us = afs_dcnextTbl[us];
986 osi_Panic("dcache hc");
988 /* remove entry from *other* hash chain */
989 i = DVHash(&adc->f.fid);
990 us = afs_dvhashTbl[i];
991 if (us == adc->index) {
992 /* first dude in the list */
993 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
995 /* somewhere on the chain */
996 while (us != NULLIDX) {
997 if (afs_dvnextTbl[us] == adc->index) {
998 /* found item pointing at the one to delete */
999 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
1002 us = afs_dvnextTbl[us];
1005 osi_Panic("dcache hv");
1010 /* prevent entry from being found on a reboot (it is already out of
1011 * the hash table, but after a crash, we just look at fid fields of
1012 * stable (old) entries).
1014 adc->f.fid.Fid.Volume = 0; /* invalid */
1016 /* mark entry as modified */
1017 adc->dflags |= DFEntryMod;
1022 } /*afs_HashOutDCache */
1025 * Flush the given dcache entry, pulling it from hash chains
1026 * and truncating the associated cache file.
1028 * \param adc Ptr to dcache entry to flush.
1030 * \note Environment:
1031 * This routine must be called with the afs_xdcache lock held
1035 afs_FlushDCache(struct dcache *adc)
1037 AFS_STATCNT(afs_FlushDCache);
1039 * Bump the number of cache files flushed.
1041 afs_stats_cmperf.cacheFlushes++;
1043 /* remove from all hash tables */
1044 afs_HashOutDCache(adc, 1);
1046 /* Free its space; special case null operation, since truncate operation
1047 * in UFS is slow even in this case, and this allows us to pre-truncate
1048 * these files at more convenient times with fewer locks set
1049 * (see afs_GetDownD).
1051 if (adc->f.chunkBytes != 0) {
1052 afs_DiscardDCache(adc);
1053 afs_MaybeWakeupTruncateDaemon();
1055 afs_FreeDCache(adc);
1057 } /*afs_FlushDCache */
1061 * Put a dcache entry on the free dcache entry list.
1063 * \param adc dcache entry to free.
1065 * \note Environment: called with afs_xdcache lock write-locked.
1068 afs_FreeDCache(struct dcache *adc)
1070 /* Thread on free list, update free list count and mark entry as
1071 * freed in its indexFlags element. Also, ensure DCache entry gets
1072 * written out (set DFEntryMod).
1075 afs_dvnextTbl[adc->index] = afs_freeDCList;
1076 afs_freeDCList = adc->index;
1078 afs_indexFlags[adc->index] |= IFFree;
1079 adc->dflags |= DFEntryMod;
1081 afs_WakeCacheWaitersIfDrained();
1082 } /* afs_FreeDCache */
1085 * Discard the cache element by moving it to the discardDCList.
1086 * This puts the cache element into a quasi-freed state, where
1087 * the space may be reused, but the file has not been truncated.
1089 * \note Major Assumptions Here:
1090 * Assumes that frag size is an integral power of two, less one,
1091 * and that this is a two's complement machine. I don't
1092 * know of any filesystems which violate this assumption...
1094 * \param adr Ptr to dcache entry.
1096 * \note Environment:
1097 * Must be called with afs_xdcache write-locked.
1101 afs_DiscardDCache(struct dcache *adc)
1105 AFS_STATCNT(afs_DiscardDCache);
1107 osi_Assert(adc->refCount == 1);
1109 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1110 afs_blocksDiscarded += size;
1111 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1113 afs_dvnextTbl[adc->index] = afs_discardDCList;
1114 afs_discardDCList = adc->index;
1115 afs_discardDCCount++;
1117 adc->f.fid.Fid.Volume = 0;
1118 adc->dflags |= DFEntryMod;
1119 afs_indexFlags[adc->index] |= IFDiscarded;
1121 afs_WakeCacheWaitersIfDrained();
1122 } /*afs_DiscardDCache */
1125 * Get a dcache entry from the discard or free list
1127 * @param[out] adc On success, a dcache from the given list. Otherwise, NULL.
1128 * @param[in] indexp A pointer to the head of the dcache free list or discard
1129 * list (afs_freeDCList, or afs_discardDCList)
1131 * @return 0 on success. If there are no dcache slots available, return ENOSPC.
1132 * If we encountered an error in disk i/o while trying to find a
1133 * dcache, return EIO.
1135 * @pre afs_xdcache is write-locked
1138 afs_GetDSlotFromList(struct dcache **adc, afs_int32 *indexp)
1144 if (*indexp == NULLIDX) {
1148 tdc = afs_GetUnusedDSlot(*indexp);
1153 osi_Assert(tdc->refCount == 1);
1154 ReleaseReadLock(&tdc->tlock);
1155 *indexp = afs_dvnextTbl[tdc->index];
1156 afs_dvnextTbl[tdc->index] = NULLIDX;
1163 * Free the next element on the list of discarded cache elements.
1165 * Returns -1 if we encountered an error preventing us from freeing a
1166 * discarded dcache, or 0 on success.
1169 afs_FreeDiscardedDCache(void)
1172 struct osi_file *tfile;
1175 AFS_STATCNT(afs_FreeDiscardedDCache);
1177 ObtainWriteLock(&afs_xdcache, 510);
1178 if (!afs_blocksDiscarded) {
1179 ReleaseWriteLock(&afs_xdcache);
1184 * Get an entry from the list of discarded cache elements
1186 (void)afs_GetDSlotFromList(&tdc, &afs_discardDCList);
1188 ReleaseWriteLock(&afs_xdcache);
1192 afs_discardDCCount--;
1193 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1194 afs_blocksDiscarded -= size;
1195 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1196 /* We can lock because we just took it off the free list */
1197 ObtainWriteLock(&tdc->lock, 626);
1198 ReleaseWriteLock(&afs_xdcache);
1201 * Truncate the element to reclaim its space
1203 tfile = afs_CFileOpen(&tdc->f.inode);
1205 afs_CFileTruncate(tfile, 0);
1206 afs_CFileClose(tfile);
1207 afs_AdjustSize(tdc, 0);
1208 afs_DCMoveBucket(tdc, 0, 0);
1211 * Free the element we just truncated
1213 ObtainWriteLock(&afs_xdcache, 511);
1214 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1215 afs_FreeDCache(tdc);
1216 tdc->f.states &= ~(DRO|DBackup|DRW);
1217 ReleaseWriteLock(&tdc->lock);
1219 ReleaseWriteLock(&afs_xdcache);
1225 * Free as many entries from the list of discarded cache elements
1226 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1231 afs_MaybeFreeDiscardedDCache(void)
1234 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1236 while (afs_blocksDiscarded
1237 && (afs_blocksUsed >
1238 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1239 int code = afs_FreeDiscardedDCache();
1241 /* Callers depend on us to get the afs_blocksDiscarded count down.
1242 * If we cannot do that, the callers can spin by calling us over
1243 * and over. Panic for now until we can figure out something
1245 osi_Panic("Error freeing discarded dcache");
1252 * Try to free up a certain number of disk slots.
1254 * \param anumber Targeted number of disk slots to free up.
1256 * \note Environment:
1257 * Must be called with afs_xdcache write-locked.
1261 afs_GetDownDSlot(int anumber)
1263 struct afs_q *tq, *nq;
1268 AFS_STATCNT(afs_GetDownDSlot);
1269 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1270 osi_Panic("diskless getdowndslot");
1272 if (CheckLock(&afs_xdcache) != -1)
1273 osi_Panic("getdowndslot nolock");
1275 /* decrement anumber first for all dudes in free list */
1276 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1279 return; /* enough already free */
1281 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1283 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1284 nq = QPrev(tq); /* in case we remove it */
1285 if (tdc->refCount == 0) {
1286 if ((ix = tdc->index) == NULLIDX)
1287 osi_Panic("getdowndslot");
1289 /* write-through if modified */
1290 if (tdc->dflags & DFEntryMod) {
1291 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1293 * ask proxy to do this for us - we don't have the stack space
1295 while (tdc->dflags & DFEntryMod) {
1298 s = SPLOCK(afs_sgibklock);
1299 if (afs_sgibklist == NULL) {
1300 /* if slot is free, grab it. */
1301 afs_sgibklist = tdc;
1302 SV_SIGNAL(&afs_sgibksync);
1304 /* wait for daemon to (start, then) finish. */
1305 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1311 code = afs_WriteDCache(tdc, 1);
1314 * We couldn't flush it at this time; return early because
1315 * if afs_WriteDCache() failed once it is likely to
1316 * continue failing for subsequent dcaches.
1320 tdc->dflags &= ~DFEntryMod;
1324 /* pull the entry out of the lruq and put it on the free list */
1325 QRemove(&tdc->lruq);
1326 afs_indexTable[ix] = NULL;
1327 afs_indexFlags[ix] &= ~IFEverUsed;
1328 tdc->index = NULLIDX;
1329 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1330 afs_freeDSList = tdc;
1334 } /*afs_GetDownDSlot */
1341 * Increment the reference count on a disk cache entry,
1342 * which already has a non-zero refcount. In order to
1343 * increment the refcount of a zero-reference entry, you
1344 * have to hold afs_xdcache.
1347 * adc : Pointer to the dcache entry to increment.
1350 * Nothing interesting.
1353 afs_RefDCache(struct dcache *adc)
1355 ObtainWriteLock(&adc->tlock, 627);
1356 if (adc->refCount < 0)
1357 osi_Panic("RefDCache: negative refcount");
1359 ReleaseWriteLock(&adc->tlock);
1368 * Decrement the reference count on a disk cache entry.
1371 * ad : Ptr to the dcache entry to decrement.
1374 * Nothing interesting.
1377 afs_PutDCache(struct dcache *adc)
1379 AFS_STATCNT(afs_PutDCache);
1380 ObtainWriteLock(&adc->tlock, 276);
1381 if (adc->refCount <= 0)
1382 osi_Panic("putdcache");
1384 ReleaseWriteLock(&adc->tlock);
1393 * Try to discard all data associated with this file from the
1397 * avc : Pointer to the cache info for the file.
1400 * Both pvnLock and lock are write held.
1403 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1408 AFS_STATCNT(afs_TryToSmush);
1409 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1410 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1411 sync = 1; /* XX Temp testing XX */
1413 #if defined(AFS_SUN5_ENV)
1414 ObtainWriteLock(&avc->vlock, 573);
1415 avc->activeV++; /* block new getpages */
1416 ReleaseWriteLock(&avc->vlock);
1419 /* Flush VM pages */
1420 osi_VM_TryToSmush(avc, acred, sync);
1423 * Get the hash chain containing all dce's for this fid
1425 i = DVHash(&avc->f.fid);
1426 ObtainWriteLock(&afs_xdcache, 277);
1427 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1428 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1429 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1430 int releaseTlock = 1;
1431 tdc = afs_GetValidDSlot(index);
1433 /* afs_TryToSmush is best-effort; we may not actually discard
1434 * everything, so failure to discard dcaches due to an i/o
1438 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1440 if ((afs_indexFlags[index] & IFDataMod) == 0
1441 && tdc->refCount == 1) {
1442 ReleaseReadLock(&tdc->tlock);
1444 afs_FlushDCache(tdc);
1447 afs_indexTable[index] = 0;
1450 ReleaseReadLock(&tdc->tlock);
1454 #if defined(AFS_SUN5_ENV)
1455 ObtainWriteLock(&avc->vlock, 545);
1456 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1457 avc->vstates &= ~VRevokeWait;
1458 afs_osi_Wakeup((char *)&avc->vstates);
1460 ReleaseWriteLock(&avc->vlock);
1462 ReleaseWriteLock(&afs_xdcache);
1464 * It's treated like a callback so that when we do lookups we'll
1465 * invalidate the unique bit if any
1466 * trytoSmush occured during the lookup call
1472 * afs_DCacheMissingChunks
1475 * Given the cached info for a file, return the number of chunks that
1476 * are not available from the dcache.
1479 * avc: Pointer to the (held) vcache entry to look in.
1482 * The number of chunks which are not currently cached.
1485 * The vcache entry is held upon entry.
1489 afs_DCacheMissingChunks(struct vcache *avc)
1492 afs_size_t totalLength = 0;
1493 afs_uint32 totalChunks = 0;
1496 totalLength = avc->f.m.Length;
1497 if (avc->f.truncPos < totalLength)
1498 totalLength = avc->f.truncPos;
1500 /* Length is 0, no chunk missing. */
1501 if (totalLength == 0)
1504 /* If totalLength is a multiple of chunksize, the last byte appears
1505 * as being part of the next chunk, which does not exist.
1506 * Decrementing totalLength by one fixes that.
1509 totalChunks = (AFS_CHUNK(totalLength) + 1);
1511 /* If we're a directory, we only ever have one chunk, regardless of
1512 * the size of the dir.
1514 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1518 printf("Should have %d chunks for %u bytes\n",
1519 totalChunks, (totalLength + 1));
1521 i = DVHash(&avc->f.fid);
1522 ObtainWriteLock(&afs_xdcache, 1001);
1523 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1524 i = afs_dvnextTbl[index];
1525 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1526 tdc = afs_GetValidDSlot(index);
1530 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1533 ReleaseReadLock(&tdc->tlock);
1537 ReleaseWriteLock(&afs_xdcache);
1539 /*printf("Missing %d chunks\n", totalChunks);*/
1541 return (totalChunks);
1548 * Given the cached info for a file and a byte offset into the
1549 * file, make sure the dcache entry for that file and containing
1550 * the given byte is available, returning it to our caller.
1553 * avc : Pointer to the (held) vcache entry to look in.
1554 * abyte : Which byte we want to get to.
1557 * Pointer to the dcache entry covering the file & desired byte,
1558 * or NULL if not found.
1561 * The vcache entry is held upon entry.
1565 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1569 struct dcache *tdc = NULL;
1571 AFS_STATCNT(afs_FindDCache);
1572 chunk = AFS_CHUNK(abyte);
1575 * Hash on the [fid, chunk] and get the corresponding dcache index
1576 * after write-locking the dcache.
1578 i = DCHash(&avc->f.fid, chunk);
1579 ObtainWriteLock(&afs_xdcache, 278);
1580 for (index = afs_dchashTbl[i]; index != NULLIDX; index = afs_dcnextTbl[index]) {
1581 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1582 tdc = afs_GetValidDSlot(index);
1584 /* afs_FindDCache is best-effort; we may not find the given
1585 * file/offset, so if we cannot find the given dcache due to
1586 * i/o errors, that is okay. */
1590 ReleaseReadLock(&tdc->tlock);
1591 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1592 break; /* leaving refCount high for caller */
1597 if (index != NULLIDX) {
1598 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1599 hadd32(afs_indexCounter, 1);
1600 ReleaseWriteLock(&afs_xdcache);
1603 ReleaseWriteLock(&afs_xdcache);
1605 } /*afs_FindDCache */
1607 /* only call these from afs_AllocDCache() */
1609 afs_AllocFreeDSlot(struct dcache **adc)
1614 code = afs_GetDSlotFromList(&tdc, &afs_freeDCList);
1618 afs_indexFlags[tdc->index] &= ~IFFree;
1619 ObtainWriteLock(&tdc->lock, 604);
1626 afs_AllocDiscardDSlot(struct dcache **adc, afs_int32 lock)
1630 afs_uint32 size = 0;
1631 struct osi_file *file;
1633 code = afs_GetDSlotFromList(&tdc, &afs_discardDCList);
1637 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1638 ObtainWriteLock(&tdc->lock, 605);
1639 afs_discardDCCount--;
1641 ((tdc->f.chunkBytes +
1642 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1643 tdc->f.states &= ~(DRO|DBackup|DRW);
1644 afs_DCMoveBucket(tdc, size, 0);
1645 afs_blocksDiscarded -= size;
1646 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1648 /* Truncate the chunk so zeroes get filled properly */
1649 file = afs_CFileOpen(&tdc->f.inode);
1651 afs_CFileTruncate(file, 0);
1652 afs_CFileClose(file);
1653 afs_AdjustSize(tdc, 0);
1661 * Get a fresh dcache from the free or discarded list.
1663 * \param adc Set to the new dcache on success, and NULL on error.
1664 * \param avc Who's dcache is this going to be?
1665 * \param chunk The position where it will be placed in.
1666 * \param lock How are locks held.
1667 * \param ashFid If this dcache going to be used for a shadow dir,
1670 * \note Required locks:
1672 * - avc (R if (lock & 1) set and W otherwise)
1673 * \note It write locks the new dcache. The caller must unlock it.
1675 * \return If we're out of dslots, ENOSPC. If we encountered disk errors, EIO.
1676 * On success, return 0.
1679 afs_AllocDCache(struct dcache **adc, struct vcache *avc, afs_int32 chunk,
1680 afs_int32 lock, struct VenusFid *ashFid)
1683 struct dcache *tdc = NULL;
1687 /* if (lock & 2), prefer 'free' dcaches; otherwise, prefer 'discard'
1688 * dcaches. In either case, try both if our first choice doesn't work due
1691 code = afs_AllocFreeDSlot(&tdc);
1692 if (code == ENOSPC) {
1693 code = afs_AllocDiscardDSlot(&tdc, lock);
1696 code = afs_AllocDiscardDSlot(&tdc, lock);
1697 if (code == ENOSPC) {
1698 code = afs_AllocFreeDSlot(&tdc);
1707 * avc->lock(R) if setLocks
1708 * avc->lock(W) if !setLocks
1714 * Fill in the newly-allocated dcache record.
1716 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1718 /* Use shadow fid if provided. */
1719 tdc->f.fid = *ashFid;
1721 /* Use normal vcache's fid otherwise. */
1722 tdc->f.fid = avc->f.fid;
1723 if (avc->f.states & CRO)
1724 tdc->f.states = DRO;
1725 else if (avc->f.states & CBackup)
1726 tdc->f.states = DBackup;
1728 tdc->f.states = DRW;
1729 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1730 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1732 hones(tdc->f.versionNo); /* invalid value */
1733 tdc->f.chunk = chunk;
1734 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1736 if (tdc->lruq.prev == &tdc->lruq)
1737 osi_Panic("lruq 1");
1744 IsDCacheSizeOK(struct dcache *adc, struct vcache *avc, afs_int32 chunk_bytes,
1745 afs_size_t file_length, afs_uint32 versionNo, int from_net)
1747 afs_size_t expected_bytes;
1748 afs_size_t chunk_start = AFS_CHUNKTOBASE(adc->f.chunk);
1750 if (vType(avc) == VDIR) {
1752 * Directory blobs may be constructed locally (see afs_LocalHero), and
1753 * the size of the blob may differ slightly compared to what's on the
1754 * fileserver. So, skip size checks for directories.
1759 if ((avc->f.states & CDirty)) {
1761 * Our vcache may have writes that are local to our cache, but not yet
1762 * written to the fileserver. In such a situation, we may have dcaches
1763 * for that file that are "short". For example:
1765 * Say we have a file that is 0 bytes long. A process opens that file,
1766 * and writes some data to offset 5M (keeping the file open). Another
1767 * process comes along and reads data from offset 1M. We'll try to
1768 * fetch data at offset 1M, and the fileserver will respond with 0
1769 * bytes, since our locally-written data hasn't been written to the
1770 * fileserver yet (on the fileserver, the file is still 0-bytes long).
1771 * So our dcache at offset 1M will have 0 bytes.
1773 * So if CDirty is set, don't do any size/length checks at all, since
1774 * we have no idea if the avc length is valid.
1779 if (!from_net && (adc->f.states & DRW)) {
1781 * The dcache data we're looking at is from our local cache (not from a
1782 * fileserver), and it's for data in an RW volume. For cached RW data,
1783 * there are some edge cases that can cause the below length checks to
1784 * trigger false positives.
1786 * For example: if the local client writes 4 bytes to a new file at
1787 * offset 0, and then 4 bytes at offset 0x400000, the file will be
1788 * 0x400004 bytes long, but the first dcache chunk will only contain 4
1789 * bytes. If such a file is fetched from a fileserver, the first chunk
1790 * will have a full chunk of data (most of it zeroes), but on the
1791 * client that did the write, the sparse data will not appear in the
1794 * Such false positives should only be possible with RW data, since
1795 * non-RW data is never generated locally. So to avoid the false
1796 * positives, assume the dcache length is OK for RW data if the dcache
1797 * came from our local cache (and not directly from a fileserver).
1802 if (file_length < chunk_start) {
1806 expected_bytes = file_length - chunk_start;
1808 if (vType(avc) != VDIR && expected_bytes > AFS_CHUNKTOSIZE(adc->f.chunk)) {
1809 /* A non-dir chunk cannot have more bytes than the chunksize. */
1810 expected_bytes = AFS_CHUNKTOSIZE(adc->f.chunk);
1814 if (chunk_bytes != expected_bytes) {
1815 static const afs_uint32 one_hour = 60 * 60;
1816 static afs_uint32 last_warn;
1817 afs_uint32 now = osi_Time();
1819 if (now < last_warn) {
1820 /* clock went backwards */
1824 if (now - last_warn > one_hour) {
1825 unsigned int mtime = adc->f.modTime;
1831 * The dcache we're looking at didn't come from the cache, but is
1832 * being populated from the net. Don't print out its mtime in that
1833 * case; that would be misleading since that's the mtime from the
1834 * last time this dcache slot was written to.
1839 afs_warn("afs: Detected corrupt dcache for file %d.%u.%u.%u: chunk %d "
1840 "(offset %lu) has %d bytes, but it should have %lu bytes\n",
1842 adc->f.fid.Fid.Volume,
1843 adc->f.fid.Fid.Vnode,
1844 adc->f.fid.Fid.Unique,
1846 (unsigned long)chunk_start,
1848 (unsigned long)expected_bytes);
1849 afs_warn("afs: (dcache %p, file length %lu, DV %u, dcache mtime %u, "
1850 "index %d, dflags 0x%x, mflags 0x%x, states 0x%x, vcache "
1853 (unsigned long)file_length,
1857 (unsigned)adc->dflags,
1858 (unsigned)adc->mflags,
1859 (unsigned)adc->f.states,
1861 afs_warn("afs: Ignoring the dcache for now, but this may indicate "
1862 "corruption in the AFS cache, or a bug.\n");
1870 * Check if a dcache is "fresh". That is, if the dcache's DV matches the DV of
1871 * the vcache for that file, and the dcache looks "sane" (its length makes
1872 * sense, when considering the length of the given avc).
1874 * \param adc The dcache to check
1875 * \param avc The vcache for adc
1877 * \return 1 if the dcache is "fresh". 0 otherwise.
1880 afs_IsDCacheFresh(struct dcache *adc, struct vcache *avc)
1882 if (!hsame(adc->f.versionNo, avc->f.m.DataVersion)) {
1887 * If we've reached here, the DV in adc matches the DV of our avc. Check if
1888 * the number of bytes in adc agrees with the avc file length, as a sanity
1889 * check. If they don't match, we'll pretend the DVs don't match, so the
1890 * bad dcache data will not be used, and we'll probably re-fetch the chunk
1891 * data, replacing the bad chunk.
1894 if (!IsDCacheSizeOK(adc, avc, adc->f.chunkBytes, avc->f.m.Length,
1895 hgetlo(adc->f.versionNo), 0)) {
1906 * This function is called to obtain a reference to data stored in
1907 * the disk cache, locating a chunk of data containing the desired
1908 * byte and returning a reference to the disk cache entry, with its
1909 * reference count incremented.
1913 * avc : Ptr to a vcache entry (unlocked)
1914 * abyte : Byte position in the file desired
1915 * areq : Request structure identifying the requesting user.
1916 * aflags : Settings as follows:
1918 * 2 : Return after creating entry.
1919 * 4 : called from afs_vnop_write.c
1920 * *alen contains length of data to be written.
1922 * aoffset : Set to the offset within the chunk where the resident
1924 * alen : Set to the number of bytes of data after the desired
1925 * byte (including the byte itself) which can be read
1929 * The vcache entry pointed to by avc is unlocked upon entry.
1933 * Update the vnode-to-dcache hint if we can get the vnode lock
1934 * right away. Assumes dcache entry is at least read-locked.
1937 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1939 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1940 if (afs_IsDCacheFresh(d, v) && v->callback)
1943 ReleaseWriteLock(&v->lock);
1947 /* avc - Write-locked unless aflags & 1 */
1949 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1950 struct vrequest *areq, afs_size_t * aoffset,
1951 afs_size_t * alen, int aflags)
1953 afs_int32 i, code, shortcut;
1954 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1955 afs_int32 adjustsize = 0;
1961 afs_size_t Position = 0;
1962 afs_int32 size, tlen; /* size of segment to transfer */
1963 struct afs_FetchOutput *tsmall = 0;
1965 struct osi_file *file;
1966 struct afs_conn *tc;
1968 struct server *newCallback = NULL;
1969 char setNewCallback;
1970 char setVcacheStatus;
1971 char doVcacheUpdate;
1973 int doAdjustSize = 0;
1974 int doReallyAdjustSize = 0;
1975 int overWriteWholeChunk = 0;
1976 struct rx_connection *rxconn;
1979 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1980 int fromReplica; /*Are we reading from a replica? */
1981 int numFetchLoops; /*# times around the fetch/analyze loop */
1982 #endif /* AFS_NOSTATS */
1984 AFS_STATCNT(afs_GetDCache);
1988 setLocks = aflags & 1;
1991 * Determine the chunk number and offset within the chunk corresponding
1992 * to the desired byte.
1994 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1997 chunk = AFS_CHUNK(abyte);
2000 /* come back to here if we waited for the cache to drain. */
2003 setNewCallback = setVcacheStatus = 0;
2007 ObtainWriteLock(&avc->lock, 616);
2009 ObtainReadLock(&avc->lock);
2014 * avc->lock(R) if setLocks && !slowPass
2015 * avc->lock(W) if !setLocks || slowPass
2020 /* check hints first! (might could use bcmp or some such...) */
2021 if ((tdc = avc->dchint)) {
2025 * The locking order between afs_xdcache and dcache lock matters.
2026 * The hint dcache entry could be anywhere, even on the free list.
2027 * Locking afs_xdcache ensures that noone is trying to pull dcache
2028 * entries from the free list, and thereby assuming them to be not
2029 * referenced and not locked.
2031 ObtainReadLock(&afs_xdcache);
2032 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
2034 if (dcLocked && (tdc->index != NULLIDX)
2035 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
2036 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
2037 /* got the right one. It might not be the right version, and it
2038 * might be fetching, but it's the right dcache entry.
2040 /* All this code should be integrated better with what follows:
2041 * I can save a good bit more time under a write lock if I do..
2043 ObtainWriteLock(&tdc->tlock, 603);
2045 ReleaseWriteLock(&tdc->tlock);
2047 ReleaseReadLock(&afs_xdcache);
2050 if (afs_IsDCacheFresh(tdc, avc)
2051 && !(tdc->dflags & DFFetching)) {
2053 afs_stats_cmperf.dcacheHits++;
2054 ObtainWriteLock(&afs_xdcache, 559);
2055 QRemove(&tdc->lruq);
2056 QAdd(&afs_DLRU, &tdc->lruq);
2057 ReleaseWriteLock(&afs_xdcache);
2060 * avc->lock(R) if setLocks && !slowPass
2061 * avc->lock(W) if !setLocks || slowPass
2068 ReleaseSharedLock(&tdc->lock);
2069 ReleaseReadLock(&afs_xdcache);
2077 * avc->lock(R) if setLocks && !slowPass
2078 * avc->lock(W) if !setLocks || slowPass
2079 * tdc->lock(S) if tdc
2082 if (!tdc) { /* If the hint wasn't the right dcache entry */
2083 int dslot_error = 0;
2085 * Hash on the [fid, chunk] and get the corresponding dcache index
2086 * after write-locking the dcache.
2091 * avc->lock(R) if setLocks && !slowPass
2092 * avc->lock(W) if !setLocks || slowPass
2095 i = DCHash(&avc->f.fid, chunk);
2096 /* check to make sure our space is fine */
2097 afs_MaybeWakeupTruncateDaemon();
2099 ObtainWriteLock(&afs_xdcache, 280);
2101 for (index = afs_dchashTbl[i]; index != NULLIDX; us = index, index = afs_dcnextTbl[index]) {
2102 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
2103 tdc = afs_GetValidDSlot(index);
2105 /* we got an i/o error when trying to get the given dslot.
2106 * it's possible the dslot we're looking for is elsewhere,
2107 * but most likely the disk cache is currently unusable, so
2108 * all afs_GetValidDSlot calls will fail, so just bail out. */
2113 ReleaseReadLock(&tdc->tlock);
2116 * avc->lock(R) if setLocks && !slowPass
2117 * avc->lock(W) if !setLocks || slowPass
2120 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
2121 /* Move it up in the beginning of the list */
2122 if (afs_dchashTbl[i] != index) {
2123 afs_dcnextTbl[us] = afs_dcnextTbl[index];
2124 afs_dcnextTbl[index] = afs_dchashTbl[i];
2125 afs_dchashTbl[i] = index;
2127 ReleaseWriteLock(&afs_xdcache);
2128 ObtainSharedLock(&tdc->lock, 606);
2129 break; /* leaving refCount high for caller */
2137 * If we didn't find the entry, we'll create one.
2139 if (index == NULLIDX) {
2142 * avc->lock(R) if setLocks
2143 * avc->lock(W) if !setLocks
2146 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
2147 avc, ICL_TYPE_INT32, chunk);
2150 /* We couldn't find the dcache we want, but we hit some i/o
2151 * errors when trying to find it, so we're not sure if the
2152 * dcache we want is in the cache or not. Error out, so we
2153 * don't try to possibly create 2 separate dcaches for the
2154 * same exact data. */
2155 ReleaseWriteLock(&afs_xdcache);
2159 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
2161 avc->f.states |= CDCLock;
2162 /* just need slots */
2163 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
2165 avc->f.states &= ~CDCLock;
2167 code = afs_AllocDCache(&tdc, avc, chunk, aflags, NULL);
2169 ReleaseWriteLock(&afs_xdcache);
2170 if (code == ENOSPC) {
2171 /* It looks like afs_AllocDCache failed because we don't
2172 * have any free dslots to use. Maybe if we wait a little
2173 * while, we'll be able to free up some slots, so try for 5
2174 * minutes, then bail out. */
2175 if (++downDCount > 300) {
2176 afs_warn("afs: Unable to get free cache space for file "
2177 "%u:%u.%u.%u for 5 minutes; failing with an i/o error\n",
2179 avc->f.fid.Fid.Volume,
2180 avc->f.fid.Fid.Vnode,
2181 avc->f.fid.Fid.Unique);
2184 afs_osi_Wait(1000, 0, 0);
2188 /* afs_AllocDCache failed, but not because we're out of free
2189 * dslots. Something must be screwy with the cache, so bail out
2190 * immediately without waiting. */
2191 afs_warn("afs: Error while alloc'ing cache slot for file "
2192 "%u:%u.%u.%u; failing with an i/o error\n",
2194 avc->f.fid.Fid.Volume,
2195 avc->f.fid.Fid.Vnode,
2196 avc->f.fid.Fid.Unique);
2202 * avc->lock(R) if setLocks
2203 * avc->lock(W) if !setLocks
2209 * Now add to the two hash chains - note that i is still set
2210 * from the above DCHash call.
2212 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
2213 afs_dchashTbl[i] = tdc->index;
2214 i = DVHash(&avc->f.fid);
2215 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
2216 afs_dvhashTbl[i] = tdc->index;
2217 tdc->dflags = DFEntryMod;
2219 afs_MaybeWakeupTruncateDaemon();
2220 ReleaseWriteLock(&afs_xdcache);
2221 ConvertWToSLock(&tdc->lock);
2226 /* vcache->dcache hint failed */
2229 * avc->lock(R) if setLocks && !slowPass
2230 * avc->lock(W) if !setLocks || slowPass
2233 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
2234 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2235 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
2236 hgetlo(avc->f.m.DataVersion));
2238 * Here we have the entry in tdc, with its refCount incremented.
2239 * Note: we don't use the S-lock on avc; it costs concurrency when
2240 * storing a file back to the server.
2244 * Not a newly created file so we need to check the file's length and
2245 * compare data versions since someone could have changed the data or we're
2246 * reading a file written elsewhere. We only want to bypass doing no-op
2247 * read rpcs on newly created files (dv of 0) since only then we guarantee
2248 * that this chunk's data hasn't been filled by another client.
2250 size = AFS_CHUNKSIZE(abyte);
2251 if (aflags & 4) /* called from write */
2253 else /* called from read */
2254 tlen = tdc->validPos - abyte;
2255 Position = AFS_CHUNKTOBASE(chunk);
2256 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
2257 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2258 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2259 ICL_HANDLE_OFFSET(Position));
2260 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
2262 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
2263 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2264 overWriteWholeChunk = 1;
2265 if (doAdjustSize || overWriteWholeChunk) {
2266 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2268 #ifdef AFS_SGI64_ENV
2271 #else /* AFS_SGI64_ENV */
2274 #endif /* AFS_SGI64_ENV */
2275 #else /* AFS_SGI_ENV */
2278 #endif /* AFS_SGI_ENV */
2279 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
2280 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2281 #if defined(AFS_SUN5_ENV)
2282 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
2284 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
2286 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2287 !afs_IsDCacheFresh(tdc, avc))
2288 doReallyAdjustSize = 1;
2290 if (doReallyAdjustSize || overWriteWholeChunk) {
2291 /* no data in file to read at this position */
2292 UpgradeSToWLock(&tdc->lock, 607);
2293 file = afs_CFileOpen(&tdc->f.inode);
2295 afs_CFileTruncate(file, 0);
2296 afs_CFileClose(file);
2297 afs_AdjustSize(tdc, 0);
2298 hset(tdc->f.versionNo, avc->f.m.DataVersion);
2299 tdc->dflags |= DFEntryMod;
2301 ConvertWToSLock(&tdc->lock);
2306 * We must read in the whole chunk if the version number doesn't
2310 /* don't need data, just a unique dcache entry */
2311 ObtainWriteLock(&afs_xdcache, 608);
2312 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2313 hadd32(afs_indexCounter, 1);
2314 ReleaseWriteLock(&afs_xdcache);
2316 updateV2DC(setLocks, avc, tdc, 553);
2317 if (vType(avc) == VDIR)
2320 *aoffset = AFS_CHUNKOFFSET(abyte);
2321 if (tdc->validPos < abyte)
2322 *alen = (afs_size_t) 0;
2324 *alen = tdc->validPos - abyte;
2325 ReleaseSharedLock(&tdc->lock);
2328 ReleaseWriteLock(&avc->lock);
2330 ReleaseReadLock(&avc->lock);
2332 return tdc; /* check if we're done */
2337 * avc->lock(R) if setLocks && !slowPass
2338 * avc->lock(W) if !setLocks || slowPass
2341 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2343 setNewCallback = setVcacheStatus = 0;
2347 * avc->lock(R) if setLocks && !slowPass
2348 * avc->lock(W) if !setLocks || slowPass
2351 if (!afs_IsDCacheFresh(tdc, avc) && !overWriteWholeChunk) {
2353 * Version number mismatch.
2356 * If we are disconnected, then we can't do much of anything
2357 * because the data doesn't match the file.
2359 if (AFS_IS_DISCONNECTED) {
2360 ReleaseSharedLock(&tdc->lock);
2363 ReleaseWriteLock(&avc->lock);
2365 ReleaseReadLock(&avc->lock);
2367 /* Flush the Dcache */
2372 UpgradeSToWLock(&tdc->lock, 609);
2375 * If data ever existed for this vnode, and this is a text object,
2376 * do some clearing. Now, you'd think you need only do the flush
2377 * when VTEXT is on, but VTEXT is turned off when the text object
2378 * is freed, while pages are left lying around in memory marked
2379 * with this vnode. If we would reactivate (create a new text
2380 * object from) this vnode, we could easily stumble upon some of
2381 * these old pages in pagein. So, we always flush these guys.
2382 * Sun has a wonderful lack of useful invariants in this system.
2384 * avc->flushDV is the data version # of the file at the last text
2385 * flush. Clearly, at least, we don't have to flush the file more
2386 * often than it changes
2388 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2390 * By here, the cache entry is always write-locked. We can
2391 * deadlock if we call osi_Flush with the cache entry locked...
2392 * Unlock the dcache too.
2394 ReleaseWriteLock(&tdc->lock);
2395 if (setLocks && !slowPass)
2396 ReleaseReadLock(&avc->lock);
2398 ReleaseWriteLock(&avc->lock);
2402 * Call osi_FlushPages in open, read/write, and map, since it
2403 * is too hard here to figure out if we should lock the
2406 if (setLocks && !slowPass)
2407 ObtainReadLock(&avc->lock);
2409 ObtainWriteLock(&avc->lock, 66);
2410 ObtainWriteLock(&tdc->lock, 610);
2415 * avc->lock(R) if setLocks && !slowPass
2416 * avc->lock(W) if !setLocks || slowPass
2420 /* Watch for standard race condition around osi_FlushText */
2421 if (afs_IsDCacheFresh(tdc, avc)) {
2422 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2423 afs_stats_cmperf.dcacheHits++;
2424 ConvertWToSLock(&tdc->lock);
2428 /* Sleep here when cache needs to be drained. */
2429 if (setLocks && !slowPass
2430 && (afs_blocksUsed >
2431 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2432 /* Make sure truncate daemon is running */
2433 afs_MaybeWakeupTruncateDaemon();
2434 ObtainWriteLock(&tdc->tlock, 614);
2435 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2436 ReleaseWriteLock(&tdc->tlock);
2437 ReleaseWriteLock(&tdc->lock);
2438 ReleaseReadLock(&avc->lock);
2439 while ((afs_blocksUsed - afs_blocksDiscarded) >
2440 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2441 if (afs_WaitForCacheDrain == 0)
2442 afs_WaitForCacheDrainCount++;
2443 afs_WaitForCacheDrain = 1;
2444 afs_osi_Sleep(&afs_WaitForCacheDrain);
2446 afs_MaybeFreeDiscardedDCache();
2447 /* need to check if someone else got the chunk first. */
2448 goto RetryGetDCache;
2451 Position = AFS_CHUNKBASE(abyte);
2452 if (vType(avc) == VDIR) {
2453 size = avc->f.m.Length;
2454 if (size > tdc->f.chunkBytes) {
2455 /* pre-reserve space for file */
2456 afs_AdjustSize(tdc, size);
2458 size = 999999999; /* max size for transfer */
2460 afs_size_t maxGoodLength;
2462 /* estimate how much data we're expecting back from the server,
2463 * and reserve space in the dcache entry for it */
2465 maxGoodLength = avc->f.m.Length;
2466 if (avc->f.truncPos < maxGoodLength)
2467 maxGoodLength = avc->f.truncPos;
2469 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2470 if (Position > maxGoodLength) { /* If we're beyond EOF */
2472 } else if (Position + size > maxGoodLength) {
2473 size = maxGoodLength - Position;
2475 osi_Assert(size >= 0);
2477 if (size > tdc->f.chunkBytes) {
2478 /* pre-reserve estimated space for file */
2479 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2483 /* For the actual fetch, do not limit the request to the
2484 * length of the file. If this results in a read past EOF on
2485 * the server, the server will just reply with less data than
2486 * requested. If we limit ourselves to only requesting data up
2487 * to the avc file length, we open ourselves up to races if the
2488 * file is extended on the server at about the same time.
2490 * However, we must restrict ourselves to the avc->f.truncPos
2491 * length, since this represents an outstanding local
2492 * truncation of the file that will be committed to the
2493 * fileserver when we actually write the fileserver contents.
2494 * If we do not restrict the fetch length based on
2495 * avc->f.truncPos, a different truncate operation extending
2496 * the file length could cause the old data after
2497 * avc->f.truncPos to reappear, instead of extending the file
2498 * with NUL bytes. */
2499 size = AFS_CHUNKSIZE(abyte);
2500 if (Position > avc->f.truncPos) {
2502 } else if (Position + size > avc->f.truncPos) {
2503 size = avc->f.truncPos - Position;
2505 osi_Assert(size >= 0);
2508 if (afs_mariner && !tdc->f.chunk)
2509 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2511 * Right now, we only have one tool, and it's a hammer. So, we
2512 * fetch the whole file.
2514 DZap(tdc); /* pages in cache may be old */
2515 file = afs_CFileOpen(&tdc->f.inode);
2517 /* We can't access the file in the disk cache backing this dcache;
2519 ReleaseWriteLock(&tdc->lock);
2524 afs_RemoveVCB(&avc->f.fid);
2525 tdc->f.states |= DWriting;
2526 tdc->dflags |= DFFetching;
2527 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2528 if (tdc->mflags & DFFetchReq) {
2529 tdc->mflags &= ~DFFetchReq;
2530 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2531 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2532 __FILE__, ICL_TYPE_INT32, __LINE__,
2533 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2536 tsmall = osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2537 setVcacheStatus = 0;
2540 * Remember if we are doing the reading from a replicated volume,
2541 * and how many times we've zipped around the fetch/analyze loop.
2543 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2545 accP = &(afs_stats_cmfullperf.accessinf);
2547 (accP->replicatedRefs)++;
2549 (accP->unreplicatedRefs)++;
2550 #endif /* AFS_NOSTATS */
2551 /* this is a cache miss */
2552 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2553 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2554 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2557 afs_stats_cmperf.dcacheMisses++;
2560 * Dynamic root support: fetch data from local memory.
2562 if (afs_IsDynroot(avc)) {
2566 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2568 dynrootDir += Position;
2569 dynrootLen -= Position;
2570 if (size > dynrootLen)
2574 code = afs_CFileWrite(file, 0, dynrootDir, size);
2582 tdc->validPos = Position + size;
2583 afs_CFileTruncate(file, size); /* prune it */
2584 } else if (afs_IsDynrootMount(avc)) {
2588 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2590 dynrootDir += Position;
2591 dynrootLen -= Position;
2592 if (size > dynrootLen)
2596 code = afs_CFileWrite(file, 0, dynrootDir, size);
2604 tdc->validPos = Position + size;
2605 afs_CFileTruncate(file, size); /* prune it */
2608 * Not a dynamic vnode: do the real fetch.
2613 * avc->lock(R) if setLocks && !slowPass
2614 * avc->lock(W) if !setLocks || slowPass
2618 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2623 (accP->numReplicasAccessed)++;
2625 #endif /* AFS_NOSTATS */
2626 if (!setLocks || slowPass) {
2627 avc->callback = tc->parent->srvr->server;
2629 newCallback = tc->parent->srvr->server;
2633 code = afs_CacheFetchProc(tc, rxconn, file, Position, tdc,
2639 /* callback could have been broken (or expired) in a race here,
2640 * but we return the data anyway. It's as good as we knew about
2641 * when we started. */
2643 * validPos is updated by CacheFetchProc, and can only be
2644 * modifed under a dcache write lock, which we've blocked out
2648 size = tdc->validPos - Position; /* actual segment size */
2651 afs_CFileTruncate(file, size); /* prune it */
2653 /* Check that the amount of data that we fetched for the
2654 * dcache makes sense. */
2655 FillInt64(length, tsmall->OutStatus.Length_hi, tsmall->OutStatus.Length);
2656 if (!IsDCacheSizeOK(tdc, avc, size,
2658 tsmall->OutStatus.DataVersion, 1)) {
2663 if (!setLocks || slowPass) {
2664 afs_StaleVCacheFlags(avc, AFS_STALEVC_CLEARCB, CUnique);
2666 /* Something lost. Forget about performance, and go
2667 * back with a vcache write lock.
2669 afs_CFileTruncate(file, 0);
2670 afs_AdjustSize(tdc, 0);
2671 afs_CFileClose(file);
2672 osi_FreeLargeSpace(tsmall);
2674 ReleaseWriteLock(&tdc->lock);
2679 * Call afs_Analyze to manage the connection references
2680 * and handle the error code (possibly mark servers
2681 * down, etc). We are going to retry getting the
2682 * dcache regardless, so we just ignore the retry hint
2683 * returned by afs_Analyze on this call.
2685 (void)afs_Analyze(tc, rxconn, code, &avc->f.fid, areq,
2686 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL);
2688 ReleaseReadLock(&avc->lock);
2691 goto RetryGetDCache;
2695 } while (afs_Analyze
2696 (tc, rxconn, code, &avc->f.fid, areq,
2697 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2701 * avc->lock(R) if setLocks && !slowPass
2702 * avc->lock(W) if !setLocks || slowPass
2708 * In the case of replicated access, jot down info on the number of
2709 * attempts it took before we got through or gave up.
2712 if (numFetchLoops <= 1)
2713 (accP->refFirstReplicaOK)++;
2714 if (numFetchLoops > accP->maxReplicasPerRef)
2715 accP->maxReplicasPerRef = numFetchLoops;
2717 #endif /* AFS_NOSTATS */
2719 tdc->dflags &= ~DFFetching;
2720 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2721 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2722 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2723 tdc, ICL_TYPE_INT32, tdc->dflags);
2724 if (avc->execsOrWriters == 0)
2725 tdc->f.states &= ~DWriting;
2727 /* now, if code != 0, we have an error and should punt.
2728 * note that we have the vcache write lock, either because
2729 * !setLocks or slowPass.
2732 afs_CFileTruncate(file, 0);
2733 afs_AdjustSize(tdc, 0);
2734 afs_CFileClose(file);
2735 ZapDCE(tdc); /* sets DFEntryMod */
2736 if (vType(avc) == VDIR) {
2739 tdc->f.states &= ~(DRO|DBackup|DRW);
2740 afs_DCMoveBucket(tdc, 0, 0);
2741 ReleaseWriteLock(&tdc->lock);
2743 if (!afs_IsDynroot(avc)) {
2744 afs_StaleVCacheFlags(avc, 0, CUnique);
2747 * avc->lock(W); assert(!setLocks || slowPass)
2749 osi_Assert(!setLocks || slowPass);
2755 /* otherwise we copy in the just-fetched info */
2756 afs_CFileClose(file);
2757 afs_AdjustSize(tdc, size); /* new size */
2759 * Copy appropriate fields into vcache. Status is
2760 * copied later where we selectively acquire the
2761 * vcache write lock.
2764 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2766 setVcacheStatus = 1;
2767 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2768 tsmall->OutStatus.DataVersion);
2769 tdc->dflags |= DFEntryMod;
2770 afs_indexFlags[tdc->index] |= IFEverUsed;
2771 ConvertWToSLock(&tdc->lock);
2772 } /*Data version numbers don't match */
2775 * Data version numbers match.
2777 afs_stats_cmperf.dcacheHits++;
2778 } /*Data version numbers match */
2780 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2784 * avc->lock(R) if setLocks && !slowPass
2785 * avc->lock(W) if !setLocks || slowPass
2786 * tdc->lock(S) if tdc
2790 * See if this was a reference to a file in the local cell.
2792 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2793 afs_stats_cmperf.dlocalAccesses++;
2795 afs_stats_cmperf.dremoteAccesses++;
2797 /* Fix up LRU info */
2800 ObtainWriteLock(&afs_xdcache, 602);
2801 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2802 hadd32(afs_indexCounter, 1);
2803 ReleaseWriteLock(&afs_xdcache);
2805 /* return the data */
2806 if (vType(avc) == VDIR)
2809 *aoffset = AFS_CHUNKOFFSET(abyte);
2810 *alen = (tdc->f.chunkBytes - *aoffset);
2811 ReleaseSharedLock(&tdc->lock);
2816 * avc->lock(R) if setLocks && !slowPass
2817 * avc->lock(W) if !setLocks || slowPass
2820 /* Fix up the callback and status values in the vcache */
2822 if (setLocks && !slowPass) {
2825 * This is our dirty little secret to parallel fetches.
2826 * We don't write-lock the vcache while doing the fetch,
2827 * but potentially we'll need to update the vcache after
2828 * the fetch is done.
2830 * Drop the read lock and try to re-obtain the write
2831 * lock. If the vcache still has the same DV, it's
2832 * ok to go ahead and install the new data.
2834 afs_hyper_t currentDV, statusDV;
2836 hset(currentDV, avc->f.m.DataVersion);
2838 if (setNewCallback && avc->callback != newCallback)
2842 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2843 tsmall->OutStatus.DataVersion);
2845 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2847 if (setVcacheStatus && !hsame(currentDV, statusDV))
2851 ReleaseReadLock(&avc->lock);
2853 if (doVcacheUpdate) {
2854 ObtainWriteLock(&avc->lock, 615);
2855 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2856 /* We lose. Someone will beat us to it. */
2858 ReleaseWriteLock(&avc->lock);
2863 /* With slow pass, we've already done all the updates */
2865 ReleaseWriteLock(&avc->lock);
2868 /* Check if we need to perform any last-minute fixes with a write-lock */
2869 if (!setLocks || doVcacheUpdate) {
2871 avc->callback = newCallback;
2872 if (tsmall && setVcacheStatus)
2873 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2875 ReleaseWriteLock(&avc->lock);
2879 osi_FreeLargeSpace(tsmall);
2882 } /*afs_GetDCache */
2886 * afs_WriteThroughDSlots
2889 * Sweep through the dcache slots and write out any modified
2890 * in-memory data back on to our caching store.
2896 * The afs_xdcache is write-locked through this whole affair.
2899 afs_WriteThroughDSlots(void)
2902 afs_int32 i, touchedit = 0;
2905 struct afs_q DirtyQ, *tq;
2907 AFS_STATCNT(afs_WriteThroughDSlots);
2910 * Because of lock ordering, we can't grab dcache locks while
2911 * holding afs_xdcache. So we enter xdcache, get a reference
2912 * for every dcache entry, and exit xdcache.
2914 ObtainWriteLock(&afs_xdcache, 283);
2916 for (i = 0; i < afs_cacheFiles; i++) {
2917 tdc = afs_indexTable[i];
2919 /* Grab tlock in case the existing refcount isn't zero */
2920 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2921 ObtainWriteLock(&tdc->tlock, 623);
2923 ReleaseWriteLock(&tdc->tlock);
2925 QAdd(&DirtyQ, &tdc->dirty);
2928 ReleaseWriteLock(&afs_xdcache);
2931 * Now, for each dcache entry we found, check if it's dirty.
2932 * If so, get write-lock, get afs_xdcache, which protects
2933 * afs_cacheInodep, and flush it. Don't forget to put back
2937 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2939 for (tq = DirtyQ.prev; tq != &DirtyQ && code == 0; tq = QPrev(tq)) {
2941 if (tdc->dflags & DFEntryMod) {
2944 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2946 /* Now that we have the write lock, double-check */
2947 if (wrLock && (tdc->dflags & DFEntryMod)) {
2948 tdc->dflags &= ~DFEntryMod;
2949 ObtainWriteLock(&afs_xdcache, 620);
2950 code = afs_WriteDCache(tdc, 1);
2951 ReleaseWriteLock(&afs_xdcache);
2953 /* We didn't successfully write out the dslot; make sure we
2954 * try again later */
2955 tdc->dflags |= DFEntryMod;
2961 ReleaseWriteLock(&tdc->lock);
2971 ObtainWriteLock(&afs_xdcache, 617);
2972 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2973 /* Touch the file to make sure that the mtime on the file is kept
2974 * up-to-date to avoid losing cached files on cold starts because
2975 * their mtime seems old...
2977 struct afs_fheader theader;
2979 afs_InitFHeader(&theader);
2980 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2982 ReleaseWriteLock(&afs_xdcache);
2990 * Return a pointer to an freshly initialized dcache entry using
2991 * a memory-based cache. The tlock will be read-locked.
2994 * aslot : Dcache slot to look at.
2995 * type : What 'type' of dslot to get; see the dslot_state enum
2998 * Must be called with afs_xdcache write-locked.
3002 afs_MemGetDSlot(afs_int32 aslot, dslot_state type)
3007 AFS_STATCNT(afs_MemGetDSlot);
3008 if (CheckLock(&afs_xdcache) != -1)
3009 osi_Panic("getdslot nolock");
3010 if (aslot < 0 || aslot >= afs_cacheFiles)
3011 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3012 tdc = afs_indexTable[aslot];
3014 QRemove(&tdc->lruq); /* move to queue head */
3015 QAdd(&afs_DLRU, &tdc->lruq);
3016 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
3017 ObtainWriteLock(&tdc->tlock, 624);
3019 ConvertWToRLock(&tdc->tlock);
3023 /* if we got here, the given slot is not in memory in our list of known
3024 * slots. for memcache, the only place a dslot can exist is in memory, so
3025 * if the caller is expecting to get back a known dslot, and we've reached
3026 * here, something is very wrong. DSLOT_NEW is the only type of dslot that
3027 * may not exist; for all others, the caller assumes the given dslot
3028 * already exists. so, 'type' had better be DSLOT_NEW here, or something is
3030 osi_Assert(type == DSLOT_NEW);
3032 if (!afs_freeDSList)
3033 afs_GetDownDSlot(4);
3034 if (!afs_freeDSList) {
3035 /* none free, making one is better than a panic */
3036 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3037 tdc = afs_osi_Alloc(sizeof(struct dcache));
3038 osi_Assert(tdc != NULL);
3039 #ifdef KERNEL_HAVE_PIN
3040 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3043 tdc = afs_freeDSList;
3044 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3047 tdc->dflags = 0; /* up-to-date, not in free q */
3049 QAdd(&afs_DLRU, &tdc->lruq);
3050 if (tdc->lruq.prev == &tdc->lruq)
3051 osi_Panic("lruq 3");
3053 /* initialize entry */
3054 tdc->f.fid.Cell = 0;
3055 tdc->f.fid.Fid.Volume = 0;
3057 hones(tdc->f.versionNo);
3058 tdc->f.inode.mem = aslot;
3059 tdc->dflags |= DFEntryMod;
3062 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3065 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3066 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3067 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3070 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
3071 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3072 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
3073 ObtainReadLock(&tdc->tlock);
3075 afs_indexTable[aslot] = tdc;
3078 } /*afs_MemGetDSlot */
3081 LogCacheError(int aslot, int off, int code, int target_size)
3083 struct osi_stat tstat;
3086 if (afs_osi_Stat(afs_cacheInodep, &tstat)) {
3090 procname = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
3091 if (procname != NULL) {
3092 osi_procname(procname, AFS_SMALLOCSIZ);
3093 procname[AFS_SMALLOCSIZ-1] = '\0';
3096 afs_warn("afs: disk cache read error in CacheItems slot %d "
3097 "off %d/%d code %d/%d pid %d (%s)\n",
3098 aslot, off, (int)tstat.size, code, target_size,
3099 (int)MyPidxx2Pid(MyPidxx),
3100 procname ? procname : "");
3102 if (procname != NULL) {
3103 osi_FreeSmallSpace(procname);
3108 unsigned int last_error = 0, lasterrtime = 0;
3114 * Return a pointer to an freshly initialized dcache entry using
3115 * a UFS-based disk cache. The dcache tlock will be read-locked.
3118 * aslot : Dcache slot to look at.
3119 * type : What 'type' of dslot to get; see the dslot_state enum
3122 * afs_xdcache lock write-locked.
3125 afs_UFSGetDSlot(afs_int32 aslot, dslot_state type)
3133 AFS_STATCNT(afs_UFSGetDSlot);
3134 if (CheckLock(&afs_xdcache) != -1)
3135 osi_Panic("getdslot nolock");
3136 if (aslot < 0 || aslot >= afs_cacheFiles)
3137 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3138 tdc = afs_indexTable[aslot];
3140 QRemove(&tdc->lruq); /* move to queue head */
3141 QAdd(&afs_DLRU, &tdc->lruq);
3142 /* Grab tlock in case refCount != 0 */
3143 ObtainWriteLock(&tdc->tlock, 625);
3145 ConvertWToRLock(&tdc->tlock);
3149 /* otherwise we should read it in from the cache file */
3150 if (!afs_freeDSList)
3151 afs_GetDownDSlot(4);
3152 if (!afs_freeDSList) {
3153 /* none free, making one is better than a panic */
3154 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3155 tdc = afs_osi_Alloc(sizeof(struct dcache));
3156 osi_Assert(tdc != NULL);
3157 #ifdef KERNEL_HAVE_PIN
3158 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3161 tdc = afs_freeDSList;
3162 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3165 tdc->dflags = 0; /* up-to-date, not in free q */
3167 QAdd(&afs_DLRU, &tdc->lruq);
3168 if (tdc->lruq.prev == &tdc->lruq)
3169 osi_Panic("lruq 3");
3172 * Seek to the aslot'th entry and read it in.
3174 off = sizeof(struct fcache)*aslot + sizeof(struct afs_fheader);
3176 afs_osi_Read(afs_cacheInodep,
3177 off, (char *)(&tdc->f),
3178 sizeof(struct fcache));
3180 if (code != sizeof(struct fcache)) {
3182 #if defined(KERNEL_HAVE_UERROR)
3183 last_error = getuerror();
3187 lasterrtime = osi_Time();
3188 if (type != DSLOT_NEW) {
3189 /* If we are requesting a non-DSLOT_NEW slot, this is an error.
3190 * non-DSLOT_NEW slots are supposed to already exist, so if we
3191 * failed to read in the slot, something is wrong. */
3192 LogCacheError(aslot, off, code, sizeof(struct fcache));
3194 /* put tdc back on the free dslot list */
3195 QRemove(&tdc->lruq);
3196 tdc->index = NULLIDX;
3197 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
3198 afs_freeDSList = tdc;
3202 if (!afs_CellNumValid(tdc->f.fid.Cell)) {
3204 if (type == DSLOT_VALID) {
3205 osi_Panic("afs: needed valid dcache but index %d off %d has "
3206 "invalid cell num %d\n",
3207 (int)aslot, off, (int)tdc->f.fid.Cell);
3211 if (type == DSLOT_VALID && tdc->f.fid.Fid.Volume == 0) {
3212 osi_Panic("afs: invalid zero-volume dcache entry at slot %d off %d",
3216 if (type == DSLOT_UNUSED) {
3217 /* the requested dslot is known to exist, but contain invalid data
3218 * (this happens when we're using a dslot from the free or discard
3219 * list). be sure not to re-use the data in it, so force invalidation.
3225 tdc->f.fid.Cell = 0;
3226 tdc->f.fid.Fid.Volume = 0;
3228 hones(tdc->f.versionNo);
3229 tdc->dflags |= DFEntryMod;
3230 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3231 tdc->f.states &= ~(DRO|DBackup|DRW);
3232 afs_DCMoveBucket(tdc, 0, 0);
3234 if (tdc->f.states & DRO) {
3235 afs_DCMoveBucket(tdc, 0, 2);
3236 } else if (tdc->f.states & DBackup) {
3237 afs_DCMoveBucket(tdc, 0, 1);
3239 afs_DCMoveBucket(tdc, 0, 1);
3244 if (tdc->f.chunk >= 0)
3245 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
3250 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3251 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3252 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3255 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
3256 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3257 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
3258 ObtainReadLock(&tdc->tlock);
3261 * If we didn't read into a temporary dcache region, update the
3262 * slot pointer table.
3264 afs_indexTable[aslot] = tdc;
3267 } /*afs_UFSGetDSlot */
3272 * Write a particular dcache entry back to its home in the
3275 * \param adc Pointer to the dcache entry to write.
3276 * \param atime If true, set the modtime on the file to the current time.
3278 * \note Environment:
3279 * Must be called with the afs_xdcache lock at least read-locked,
3280 * and dcache entry at least read-locked.
3281 * The reference count is not changed.
3285 afs_WriteDCache(struct dcache *adc, int atime)
3289 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3291 AFS_STATCNT(afs_WriteDCache);
3292 osi_Assert(WriteLocked(&afs_xdcache));
3294 adc->f.modTime = osi_Time();
3296 if ((afs_indexFlags[adc->index] & (IFFree | IFDiscarded)) == 0 &&
3297 adc->f.fid.Fid.Volume == 0) {
3298 /* If a dcache slot is not on the free or discard list, it must be
3299 * in the hash table. Thus, the volume must be non-zero, since that
3300 * is how we determine whether or not to unhash the entry when kicking
3301 * it out of the cache. Do this check now, since otherwise this can
3302 * cause hash table corruption and a panic later on after we read the
3304 osi_Panic("afs_WriteDCache zero volume index %d flags 0x%x\n",
3305 adc->index, (unsigned)afs_indexFlags[adc->index]);
3309 * Seek to the right dcache slot and write the in-memory image out to disk.
3311 afs_cellname_write();
3313 afs_osi_Write(afs_cacheInodep,
3314 sizeof(struct fcache) * adc->index +
3315 sizeof(struct afs_fheader), (char *)(&adc->f),
3316 sizeof(struct fcache));
3317 if (code != sizeof(struct fcache)) {
3318 afs_warn("afs: failed to write to CacheItems off %ld code %d/%d\n",
3319 (long)(sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader)),
3320 (int)code, (int)sizeof(struct fcache));
3329 * Wake up users of a particular file waiting for stores to take
3332 * \param avc Ptr to related vcache entry.
3334 * \note Environment:
3335 * Nothing interesting.
3338 afs_wakeup(struct vcache *avc)
3341 struct brequest *tb;
3343 AFS_STATCNT(afs_wakeup);
3344 for (i = 0; i < NBRS; i++, tb++) {
3345 /* if request is valid and for this file, we've found it */
3346 if (tb->refCount > 0 && avc == tb->vc) {
3349 * If CSafeStore is on, then we don't awaken the guy
3350 * waiting for the store until the whole store has finished.
3351 * Otherwise, we do it now. Note that if CSafeStore is on,
3352 * the BStore routine actually wakes up the user, instead
3354 * I think this is redundant now because this sort of thing
3355 * is already being handled by the higher-level code.
3357 if ((avc->f.states & CSafeStore) == 0) {
3358 tb->code_raw = tb->code_checkcode = 0;
3359 tb->flags |= BUVALID;
3360 if (tb->flags & BUWAIT) {
3361 tb->flags &= ~BUWAIT;
3372 * Given a file name and inode, set up that file to be an
3373 * active member in the AFS cache. This also involves checking
3374 * the usability of its data.
3376 * \param afile Name of the cache file to initialize.
3377 * \param ainode Inode of the file.
3379 * \note Environment:
3380 * This function is called only during initialization.
3383 afs_InitCacheFile(char *afile, ino_t ainode)
3388 struct osi_file *tfile;
3389 struct osi_stat tstat;
3392 AFS_STATCNT(afs_InitCacheFile);
3393 index = afs_stats_cmperf.cacheNumEntries;
3394 if (index >= afs_cacheFiles)
3397 ObtainWriteLock(&afs_xdcache, 282);
3398 tdc = afs_GetNewDSlot(index);
3399 ReleaseReadLock(&tdc->tlock);
3400 ReleaseWriteLock(&afs_xdcache);
3402 ObtainWriteLock(&tdc->lock, 621);
3403 ObtainWriteLock(&afs_xdcache, 622);
3404 if (!afile && !ainode) {
3409 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
3411 ReleaseWriteLock(&afs_xdcache);
3412 ReleaseWriteLock(&tdc->lock);
3417 /* Add any other 'complex' inode types here ... */
3418 #if !defined(AFS_LINUX26_ENV) && !defined(AFS_CACHE_VNODE_PATH)
3419 tdc->f.inode.ufs = ainode;
3421 osi_Panic("Can't init cache with inode numbers when complex inodes are "
3426 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3428 tfile = osi_UFSOpen(&tdc->f.inode);
3430 ReleaseWriteLock(&afs_xdcache);
3431 ReleaseWriteLock(&tdc->lock);
3436 code = afs_osi_Stat(tfile, &tstat);
3438 osi_Panic("initcachefile stat");
3441 * If file size doesn't match the cache info file, it's probably bad.
3443 if (tdc->f.chunkBytes != tstat.size)
3446 * If file changed within T (120?) seconds of cache info file, it's
3447 * probably bad. In addition, if slot changed within last T seconds,
3448 * the cache info file may be incorrectly identified, and so slot
3451 if (cacheInfoModTime < tstat.mtime + 120)
3453 if (cacheInfoModTime < tdc->f.modTime + 120)
3455 /* In case write through is behind, make sure cache items entry is
3456 * at least as new as the chunk.
3458 if (tdc->f.modTime < tstat.mtime)
3461 tdc->f.chunkBytes = 0;
3464 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3465 if (tfile && tstat.size != 0)
3466 osi_UFSTruncate(tfile, 0);
3467 tdc->f.states &= ~(DRO|DBackup|DRW);
3468 afs_DCMoveBucket(tdc, 0, 0);
3469 /* put entry in free cache slot list */
3470 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3471 afs_freeDCList = index;
3473 afs_indexFlags[index] |= IFFree;
3474 afs_indexUnique[index] = 0;
3477 * We must put this entry in the appropriate hash tables.
3478 * Note that i is still set from the above DCHash call
3480 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3481 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3482 afs_dchashTbl[code] = tdc->index;
3483 code = DVHash(&tdc->f.fid);
3484 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3485 afs_dvhashTbl[code] = tdc->index;
3486 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3488 /* has nontrivial amt of data */
3489 afs_indexFlags[index] |= IFEverUsed;
3490 afs_stats_cmperf.cacheFilesReused++;
3492 * Initialize index times to file's mod times; init indexCounter
3495 hset32(afs_indexTimes[index], tstat.atime);
3496 if (hgetlo(afs_indexCounter) < tstat.atime) {
3497 hset32(afs_indexCounter, tstat.atime);
3499 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3500 } /*File is not bad */
3503 osi_UFSClose(tfile);
3504 tdc->f.states &= ~DWriting;
3505 tdc->dflags &= ~DFEntryMod;
3506 /* don't set f.modTime; we're just cleaning up */
3507 osi_Assert(afs_WriteDCache(tdc, 0) == 0);
3508 ReleaseWriteLock(&afs_xdcache);
3509 ReleaseWriteLock(&tdc->lock);
3511 afs_stats_cmperf.cacheNumEntries++;
3516 /*Max # of struct dcache's resident at any time*/
3518 * If 'dchint' is enabled then in-memory dcache min is increased because of
3524 * Initialize dcache related variables.
3534 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3541 afs_freeDCList = NULLIDX;
3542 afs_discardDCList = NULLIDX;
3543 afs_freeDCCount = 0;
3544 afs_freeDSList = NULL;
3545 hzero(afs_indexCounter);
3547 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3553 if (achunk < 0 || achunk > 30)
3554 achunk = 13; /* Use default */
3555 AFS_SETCHUNKSIZE(achunk);
3561 /* afs_dhashsize defaults to 1024 */
3562 if (aDentries > 512)
3563 afs_dhashsize = 2048;
3564 /* Try to keep the average chain length around two unless the table
3565 * would be ridiculously big. */
3566 if (aDentries > 4096) {
3567 afs_dhashbits = opr_fls(aDentries) - 3;
3568 /* Cap the hash tables to 32k entries. */
3569 if (afs_dhashbits > 15)
3571 afs_dhashsize = opr_jhash_size(afs_dhashbits);
3573 /* initialize hash tables */
3574 afs_dvhashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3575 osi_Assert(afs_dvhashTbl != NULL);
3576 afs_dchashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3577 osi_Assert(afs_dchashTbl != NULL);
3578 for (i = 0; i < afs_dhashsize; i++) {
3579 afs_dvhashTbl[i] = NULLIDX;
3580 afs_dchashTbl[i] = NULLIDX;
3582 afs_dvnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3583 osi_Assert(afs_dvnextTbl != NULL);
3584 afs_dcnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3585 osi_Assert(afs_dcnextTbl != NULL);
3586 for (i = 0; i < afiles; i++) {
3587 afs_dvnextTbl[i] = NULLIDX;
3588 afs_dcnextTbl[i] = NULLIDX;
3591 /* Allocate and zero the pointer array to the dcache entries */
3592 afs_indexTable = afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3593 osi_Assert(afs_indexTable != NULL);
3594 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3595 afs_indexTimes = afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3596 osi_Assert(afs_indexTimes != NULL);
3597 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3598 afs_indexUnique = afs_osi_Alloc(afiles * sizeof(afs_uint32));
3599 osi_Assert(afs_indexUnique != NULL);
3600 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3601 afs_indexFlags = afs_osi_Alloc(afiles * sizeof(u_char));
3602 osi_Assert(afs_indexFlags != NULL);
3603 memset(afs_indexFlags, 0, afiles * sizeof(char));
3605 /* Allocate and thread the struct dcache entries themselves */
3606 tdp = afs_Initial_freeDSList =
3607 afs_osi_Alloc(aDentries * sizeof(struct dcache));
3608 osi_Assert(tdp != NULL);
3609 memset(tdp, 0, aDentries * sizeof(struct dcache));
3610 #ifdef KERNEL_HAVE_PIN
3611 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3612 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3613 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3614 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3615 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3616 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3617 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3618 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3619 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3622 afs_freeDSList = &tdp[0];
3623 for (i = 0; i < aDentries - 1; i++) {
3624 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3625 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3626 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3627 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3629 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3630 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3631 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3632 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3634 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3635 afs_cacheBlocks = ablocks;
3636 afs_ComputeCacheParms(); /* compute parms based on cache size */
3638 afs_dcentries = aDentries;
3640 afs_stats_cmperf.cacheBucket0_Discarded =
3641 afs_stats_cmperf.cacheBucket1_Discarded =
3642 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3646 if (aflags & AFSCALL_INIT_MEMCACHE) {
3648 * Use a memory cache instead of a disk cache
3650 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3651 afs_cacheType = &afs_MemCacheOps;
3652 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3653 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3654 /* ablocks is reported in 1K blocks */
3655 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3657 afs_warn("afsd: memory cache too large for available memory.\n");
3658 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3662 afs_warn("Memory cache: Allocating %d dcache entries...",
3665 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3666 afs_cacheType = &afs_UfsCacheOps;
3672 * Shuts down the cache.
3676 shutdown_dcache(void)
3680 #ifdef AFS_CACHE_VNODE_PATH
3681 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3683 for (i = 0; i < afs_cacheFiles; i++) {
3684 tdc = afs_indexTable[i];
3686 afs_osi_FreeStr(tdc->f.inode.ufs);
3692 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3693 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3694 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3695 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3696 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3697 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3698 afs_osi_Free(afs_Initial_freeDSList,
3699 afs_dcentries * sizeof(struct dcache));
3700 #ifdef KERNEL_HAVE_PIN
3701 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3702 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3703 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3704 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3705 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3706 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3707 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3711 for (i = 0; i < afs_dhashsize; i++) {
3712 afs_dvhashTbl[i] = NULLIDX;
3713 afs_dchashTbl[i] = NULLIDX;
3716 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3717 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3719 afs_blocksUsed = afs_dcentries = 0;
3720 afs_stats_cmperf.cacheBucket0_Discarded =
3721 afs_stats_cmperf.cacheBucket1_Discarded =
3722 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3723 hzero(afs_indexCounter);
3725 afs_freeDCCount = 0;
3726 afs_freeDCList = NULLIDX;
3727 afs_discardDCList = NULLIDX;
3728 afs_freeDSList = afs_Initial_freeDSList = 0;
3730 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3736 * Get a dcache ready for writing, respecting the current cache size limits
3738 * len is required because afs_GetDCache with flag == 4 expects the length
3739 * field to be filled. It decides from this whether it's necessary to fetch
3740 * data into the chunk before writing or not (when the whole chunk is
3743 * \param avc The vcache to fetch a dcache for
3744 * \param filePos The start of the section to be written
3745 * \param len The length of the section to be written
3749 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3750 * must be released and afs_PutDCache() called to free dcache.
3753 * \note avc->lock must be held on entry. Function may release and reobtain
3754 * avc->lock and GLOCK.
3758 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3759 afs_size_t len, struct vrequest *areq,
3762 struct dcache *tdc = NULL;
3765 /* read the cached info */
3767 tdc = afs_FindDCache(avc, filePos);
3769 ObtainWriteLock(&tdc->lock, 657);
3770 } else if (afs_blocksUsed >
3771 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3772 tdc = afs_FindDCache(avc, filePos);
3774 ObtainWriteLock(&tdc->lock, 658);
3775 if (!afs_IsDCacheFresh(tdc, avc)
3776 || (tdc->dflags & DFFetching)) {
3777 ReleaseWriteLock(&tdc->lock);
3783 afs_MaybeWakeupTruncateDaemon();
3784 while (afs_blocksUsed >
3785 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3786 ReleaseWriteLock(&avc->lock);
3787 if (afs_blocksUsed - afs_blocksDiscarded >
3788 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3789 if (afs_WaitForCacheDrain == 0)
3790 afs_WaitForCacheDrainCount++;
3791 afs_WaitForCacheDrain = 1;
3792 afs_osi_Sleep(&afs_WaitForCacheDrain);
3794 afs_MaybeFreeDiscardedDCache();
3795 afs_MaybeWakeupTruncateDaemon();
3796 ObtainWriteLock(&avc->lock, 509);
3798 avc->f.states |= CDirty;
3799 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3801 ObtainWriteLock(&tdc->lock, 659);
3804 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3806 ObtainWriteLock(&tdc->lock, 660);
3809 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3810 afs_stats_cmperf.cacheCurrDirtyChunks++;
3811 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3813 if (!(tdc->f.states & DWriting)) {
3814 /* don't mark entry as mod if we don't have to */
3815 tdc->f.states |= DWriting;
3816 tdc->dflags |= DFEntryMod;
3823 * Make a shadow copy of a dir's dcache. It's used for disconnected
3824 * operations like remove/create/rename to keep the original directory data.
3825 * On reconnection, we can diff the original data with the server and get the
3826 * server changes and with the local data to get the local changes.
3828 * \param avc The dir vnode.
3829 * \param adc The dir dcache.
3831 * \return 0 for success.
3833 * \note The vcache entry must be write locked.
3834 * \note The dcache entry must be read locked.
3837 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3839 int i, code, ret_code = 0, written, trans_size;
3840 struct dcache *new_dc = NULL;
3841 struct osi_file *tfile_src = NULL, *tfile_dst = NULL;
3842 struct VenusFid shadow_fid;
3845 /* Is this a dir? */
3846 if (vType(avc) != VDIR)
3849 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3852 /* Generate a fid for the shadow dir. */
3853 shadow_fid.Cell = avc->f.fid.Cell;
3854 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3855 afs_GenShadowFid(&shadow_fid);
3857 ObtainWriteLock(&afs_xdcache, 716);
3859 /* Get a fresh dcache. */
3860 (void)afs_AllocDCache(&new_dc, avc, 0, 0, &shadow_fid);
3863 ObtainReadLock(&adc->mflock);
3865 /* Set up the new fid. */
3866 /* Copy interesting data from original dir dcache. */
3867 new_dc->mflags = adc->mflags;
3868 new_dc->dflags = adc->dflags;
3869 new_dc->f.modTime = adc->f.modTime;
3870 new_dc->f.versionNo = adc->f.versionNo;
3871 new_dc->f.states = adc->f.states;
3872 new_dc->f.chunk= adc->f.chunk;
3873 new_dc->f.chunkBytes = adc->f.chunkBytes;
3875 ReleaseReadLock(&adc->mflock);
3877 /* Now add to the two hash chains */
3878 i = DCHash(&shadow_fid, 0);
3879 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3880 afs_dchashTbl[i] = new_dc->index;
3882 i = DVHash(&shadow_fid);
3883 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3884 afs_dvhashTbl[i] = new_dc->index;
3886 ReleaseWriteLock(&afs_xdcache);
3888 /* Alloc a 4k block. */
3889 data = afs_osi_Alloc(4096);
3891 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3896 /* Open the files. */
3897 tfile_src = afs_CFileOpen(&adc->f.inode);
3903 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3909 /* And now copy dir dcache data into this dcache,
3913 while (written < adc->f.chunkBytes) {
3914 trans_size = adc->f.chunkBytes - written;
3915 if (trans_size > 4096)
3918 /* Read a chunk from the dcache. */
3919 code = afs_CFileRead(tfile_src, written, data, trans_size);
3920 if (code < trans_size) {
3925 /* Write it to the new dcache. */
3926 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3927 if (code < trans_size) {
3932 written+=trans_size;
3937 afs_CFileClose(tfile_dst);
3939 afs_CFileClose(tfile_src);
3942 afs_osi_Free(data, 4096);
3944 ReleaseWriteLock(&new_dc->lock);
3945 afs_PutDCache(new_dc);
3948 ObtainWriteLock(&afs_xvcache, 763);
3949 ObtainWriteLock(&afs_disconDirtyLock, 765);
3950 QAdd(&afs_disconShadow, &avc->shadowq);
3951 osi_Assert((afs_RefVCache(avc) == 0));
3952 ReleaseWriteLock(&afs_disconDirtyLock);
3953 ReleaseWriteLock(&afs_xvcache);
3955 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3956 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3963 * Delete the dcaches of a shadow dir.
3965 * \param avc The vcache containing the shadow fid.
3967 * \note avc must be write locked.
3970 afs_DeleteShadowDir(struct vcache *avc)
3973 struct VenusFid shadow_fid;
3975 shadow_fid.Cell = avc->f.fid.Cell;
3976 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3977 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3978 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3980 tdc = afs_FindDCacheByFid(&shadow_fid);
3982 afs_HashOutDCache(tdc, 1);
3983 afs_DiscardDCache(tdc);
3986 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3987 ObtainWriteLock(&afs_disconDirtyLock, 708);
3988 QRemove(&avc->shadowq);
3989 ReleaseWriteLock(&afs_disconDirtyLock);
3990 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3994 * Populate a dcache with empty chunks up to a given file size,
3995 * used before extending a file in order to avoid 'holes' which
3996 * we can't access in disconnected mode.
3998 * \param avc The vcache which is being extended (locked)
3999 * \param alen The new length of the file
4003 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
4006 afs_size_t len, offset;
4007 afs_int32 start, end;
4009 /* We're doing this to deal with the situation where we extend
4010 * by writing after lseek()ing past the end of the file . If that
4011 * extension skips chunks, then those chunks won't be created, and
4012 * GetDCache will assume that they have to be fetched from the server.
4013 * So, for each chunk between the current file position, and the new
4014 * length we GetDCache for that chunk.
4017 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
4020 if (avc->f.m.Length == 0)
4023 start = AFS_CHUNK(avc->f.m.Length)+1;
4025 end = AFS_CHUNK(apos);
4028 len = AFS_CHUNKTOSIZE(start);
4029 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);