2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
13 #include <afsconfig.h>
14 #include "afs/param.h"
17 #include "afs/sysincludes.h" /*Standard vendor system headers */
18 #include "afsincludes.h" /*AFS-based standard headers */
19 #include "afs/afs_stats.h" /* statistics */
20 #include "afs/afs_cbqueue.h"
21 #include "afs/afs_osidnlc.h"
23 /* Forward declarations. */
24 static void afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint);
25 static void afs_FreeDiscardedDCache(void);
26 static void afs_DiscardDCache(struct dcache *);
27 static void afs_FreeDCache(struct dcache *);
29 static afs_int32 afs_DCGetBucket(struct vcache *);
30 static void afs_DCAdjustSize(struct dcache *, afs_int32, afs_int32);
31 static void afs_DCMoveBucket(struct dcache *, afs_int32, afs_int32);
32 static void afs_DCSizeInit(void);
33 static afs_int32 afs_DCWhichBucket(afs_int32, afs_int32);
36 * --------------------- Exported definitions ---------------------
39 afs_int32 afs_blocksUsed_0; /*!< 1K blocks in cache - in theory is zero */
40 afs_int32 afs_blocksUsed_1; /*!< 1K blocks in cache */
41 afs_int32 afs_blocksUsed_2; /*!< 1K blocks in cache */
42 afs_int32 afs_pct1 = -1;
43 afs_int32 afs_pct2 = -1;
44 afs_uint32 afs_tpct1 = 0;
45 afs_uint32 afs_tpct2 = 0;
46 afs_uint32 splitdcache = 0;
48 afs_lock_t afs_xdcache; /*!< Lock: alloc new disk cache entries */
49 afs_int32 afs_freeDCList; /*!< Free list for disk cache entries */
50 afs_int32 afs_freeDCCount; /*!< Count of elts in freeDCList */
51 afs_int32 afs_discardDCList; /*!< Discarded disk cache entries */
52 afs_int32 afs_discardDCCount; /*!< Count of elts in discardDCList */
53 struct dcache *afs_freeDSList; /*!< Free list for disk slots */
54 struct dcache *afs_Initial_freeDSList; /*!< Initial list for above */
55 afs_dcache_id_t cacheInode; /*!< Inode for CacheItems file */
56 struct osi_file *afs_cacheInodep = 0; /*!< file for CacheItems inode */
57 struct afs_q afs_DLRU; /*!< dcache LRU */
58 afs_int32 afs_dhashsize = 1024;
59 afs_int32 *afs_dvhashTbl; /*!< Data cache hash table: hashed by FID + chunk number. */
60 afs_int32 *afs_dchashTbl; /*!< Data cache hash table: hashed by FID. */
61 afs_int32 *afs_dvnextTbl; /*!< Dcache hash table links */
62 afs_int32 *afs_dcnextTbl; /*!< Dcache hash table links */
63 struct dcache **afs_indexTable; /*!< Pointers to dcache entries */
64 afs_hyper_t *afs_indexTimes; /*!< Dcache entry Access times */
65 afs_int32 *afs_indexUnique; /*!< dcache entry Fid.Unique */
66 unsigned char *afs_indexFlags; /*!< (only one) Is there data there? */
67 afs_hyper_t afs_indexCounter; /*!< Fake time for marking index
69 afs_int32 afs_cacheFiles = 0; /*!< Size of afs_indexTable */
70 afs_int32 afs_cacheBlocks; /*!< 1K blocks in cache */
71 afs_int32 afs_cacheStats; /*!< Stat entries in cache */
72 afs_int32 afs_blocksUsed; /*!< Number of blocks in use */
73 afs_int32 afs_blocksDiscarded; /*!<Blocks freed but not truncated */
74 afs_int32 afs_fsfragsize = 1023; /*!< Underlying Filesystem minimum unit
75 *of disk allocation usually 1K
76 *this value is (truefrag -1 ) to
77 *save a bunch of subtracts... */
78 #ifdef AFS_64BIT_CLIENT
79 #ifdef AFS_VM_RDWR_ENV
80 afs_size_t afs_vmMappingEnd; /* !< For large files (>= 2GB) the VM
81 * mapping an 32bit addressing machines
82 * can only be used below the 2 GB
83 * line. From this point upwards we
84 * must do direct I/O into the cache
85 * files. The value should be on a
87 #endif /* AFS_VM_RDWR_ENV */
88 #endif /* AFS_64BIT_CLIENT */
90 /* The following is used to ensure that new dcache's aren't obtained when
91 * the cache is nearly full.
93 int afs_WaitForCacheDrain = 0;
94 int afs_TruncateDaemonRunning = 0;
95 int afs_CacheTooFull = 0;
97 afs_int32 afs_dcentries; /*!< In-memory dcache entries */
100 int dcacheDisabled = 0;
102 static int afs_UFSCacheFetchProc(struct rx_call *, struct osi_file *,
103 afs_size_t, struct dcache *,
104 struct vcache *, afs_size_t *,
105 afs_size_t *, afs_int32);
107 static int afs_UFSCacheStoreProc(struct rx_call *, struct osi_file *,
108 afs_int32, struct vcache *,
112 struct afs_cacheOps afs_UfsCacheOps = {
120 afs_UFSCacheFetchProc,
121 afs_UFSCacheStoreProc,
127 struct afs_cacheOps afs_MemCacheOps = {
129 afs_MemCacheTruncate,
135 afs_MemCacheFetchProc,
136 afs_MemCacheStoreProc,
142 int cacheDiskType; /*Type of backing disk for cache */
143 struct afs_cacheOps *afs_cacheType;
146 * Where is this vcache's entry associated dcache located/
147 * \param avc The vcache entry.
148 * \return Bucket index:
153 afs_DCGetBucket(struct vcache *avc)
158 /* This should be replaced with some sort of user configurable function */
159 if (avc->f.states & CRO) {
161 } else if (avc->f.states & CBackup) {
171 * Readjust a dcache's size.
173 * \param adc The dcache to be adjusted.
174 * \param oldSize Old size for the dcache.
175 * \param newSize The new size to be adjusted to.
179 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
181 afs_int32 adjustSize = newSize - oldSize;
189 afs_blocksUsed_0 += adjustSize;
190 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
193 afs_blocksUsed_1 += adjustSize;
194 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
197 afs_blocksUsed_2 += adjustSize;
198 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
206 * Move a dcache from one bucket to another.
208 * \param adc Operate on this dcache.
209 * \param size Size in bucket (?).
210 * \param newBucket Destination bucket.
214 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
219 /* Substract size from old bucket. */
223 afs_blocksUsed_0 -= size;
226 afs_blocksUsed_1 -= size;
229 afs_blocksUsed_2 -= size;
233 /* Set new bucket and increase destination bucket size. */
234 adc->bucket = newBucket;
239 afs_blocksUsed_0 += size;
242 afs_blocksUsed_1 += size;
245 afs_blocksUsed_2 += size;
253 * Init split caches size.
258 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
267 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
272 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
273 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
275 /* Short cut: if we don't know about it, try to kill it */
276 if (phase < 2 && afs_blocksUsed_0)
279 if (afs_pct1 > afs_tpct1)
281 if (afs_pct2 > afs_tpct2)
283 return 0; /* unlikely */
288 * Warn about failing to store a file.
290 * \param acode Associated error code.
291 * \param avolume Volume involved.
292 * \param aflags How to handle the output:
293 * aflags & 1: Print out on console
294 * aflags & 2: Print out on controlling tty
296 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
300 afs_StoreWarn(register afs_int32 acode, afs_int32 avolume,
301 register afs_int32 aflags)
303 static char problem_fmt[] =
304 "afs: failed to store file in volume %d (%s)\n";
305 static char problem_fmt_w_error[] =
306 "afs: failed to store file in volume %d (error %d)\n";
307 static char netproblems[] = "network problems";
308 static char partfull[] = "partition full";
309 static char overquota[] = "over quota";
311 AFS_STATCNT(afs_StoreWarn);
317 afs_warn(problem_fmt, avolume, netproblems);
319 afs_warnuser(problem_fmt, avolume, netproblems);
320 } else if (acode == ENOSPC) {
325 afs_warn(problem_fmt, avolume, partfull);
327 afs_warnuser(problem_fmt, avolume, partfull);
330 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
331 * Instead ENOSPC will be sent...
333 if (acode == EDQUOT) {
338 afs_warn(problem_fmt, avolume, overquota);
340 afs_warnuser(problem_fmt, avolume, overquota);
348 afs_warn(problem_fmt_w_error, avolume, acode);
350 afs_warnuser(problem_fmt_w_error, avolume, acode);
355 * Try waking up truncation daemon, if it's worth it.
358 afs_MaybeWakeupTruncateDaemon(void)
360 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
361 afs_CacheTooFull = 1;
362 if (!afs_TruncateDaemonRunning)
363 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
364 } else if (!afs_TruncateDaemonRunning
365 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
366 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
373 * Keep statistics on run time for afs_CacheTruncateDaemon. This is a
374 * struct so we need only export one symbol for AIX.
376 static struct CTD_stats {
377 osi_timeval_t CTD_beforeSleep;
378 osi_timeval_t CTD_afterSleep;
379 osi_timeval_t CTD_sleepTime;
380 osi_timeval_t CTD_runTime;
384 u_int afs_min_cache = 0;
387 * Keeps the cache clean and free by truncating uneeded files, when used.
392 afs_CacheTruncateDaemon(void)
394 osi_timeval_t CTD_tmpTime;
398 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
400 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
402 osi_GetuTime(&CTD_stats.CTD_afterSleep);
403 afs_TruncateDaemonRunning = 1;
405 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
406 MObtainWriteLock(&afs_xdcache, 266);
407 if (afs_CacheTooFull) {
408 int space_needed, slots_needed;
409 /* if we get woken up, we should try to clean something out */
410 for (counter = 0; counter < 10; counter++) {
412 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
414 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
415 afs_GetDownD(slots_needed, &space_needed, 0);
416 if ((space_needed <= 0) && (slots_needed <= 0)) {
419 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
422 if (!afs_CacheIsTooFull())
423 afs_CacheTooFull = 0;
424 } /* end of cache cleanup */
425 MReleaseWriteLock(&afs_xdcache);
428 * This is a defensive check to try to avoid starving threads
429 * that may need the global lock so thay can help free some
430 * cache space. If this thread won't be sleeping or truncating
431 * any cache files then give up the global lock so other
432 * threads get a chance to run.
434 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
435 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
436 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
440 * This is where we free the discarded cache elements.
442 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
443 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
444 afs_FreeDiscardedDCache();
447 /* See if we need to continue to run. Someone may have
448 * signalled us while we were executing.
450 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
451 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
452 /* Collect statistics on truncate daemon. */
453 CTD_stats.CTD_nSleeps++;
454 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
455 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
456 CTD_stats.CTD_beforeSleep);
457 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
459 afs_TruncateDaemonRunning = 0;
460 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
461 afs_TruncateDaemonRunning = 1;
463 osi_GetuTime(&CTD_stats.CTD_afterSleep);
464 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
465 CTD_stats.CTD_afterSleep);
466 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
468 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
470 afs_termState = AFSOP_STOP_AFSDB;
472 afs_termState = AFSOP_STOP_RXEVENT;
474 afs_osi_Wakeup(&afs_termState);
482 * Make adjustment for the new size in the disk cache entry
484 * \note Major Assumptions Here:
485 * Assumes that frag size is an integral power of two, less one,
486 * and that this is a two's complement machine. I don't
487 * know of any filesystems which violate this assumption...
489 * \param adc Ptr to dcache entry.
490 * \param anewsize New size desired.
495 afs_AdjustSize(register struct dcache *adc, register afs_int32 newSize)
497 register afs_int32 oldSize;
499 AFS_STATCNT(afs_AdjustSize);
501 adc->dflags |= DFEntryMod;
502 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
503 adc->f.chunkBytes = newSize;
506 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
507 afs_DCAdjustSize(adc, oldSize, newSize);
508 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
510 /* We're growing the file, wakeup the daemon */
511 afs_MaybeWakeupTruncateDaemon();
513 afs_blocksUsed += (newSize - oldSize);
514 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
519 * This routine is responsible for moving at least one entry (but up
520 * to some number of them) from the LRU queue to the free queue.
522 * \param anumber Number of entries that should ideally be moved.
523 * \param aneedSpace How much space we need (1K blocks);
526 * The anumber parameter is just a hint; at least one entry MUST be
527 * moved, or we'll panic. We must be called with afs_xdcache
528 * write-locked. We should try to satisfy both anumber and aneedspace,
529 * whichever is more demanding - need to do several things:
530 * 1. only grab up to anumber victims if aneedSpace <= 0, not
531 * the whole set of MAXATONCE.
532 * 2. dynamically choose MAXATONCE to reflect severity of
533 * demand: something like (*aneedSpace >> (logChunk - 9))
535 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
536 * indicates that the cache is not properly configured/tuned or
537 * something. We should be able to automatically correct that problem.
540 #define MAXATONCE 16 /* max we can obtain at once */
542 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
546 struct VenusFid *afid;
550 register struct vcache *tvc;
551 afs_uint32 victims[MAXATONCE];
552 struct dcache *victimDCs[MAXATONCE];
553 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
554 afs_uint32 victimPtr; /* next free item in victim arrays */
555 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
556 afs_uint32 maxVictimPtr; /* where it is */
559 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
563 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
564 vfslocked = VFS_LOCK_GIANT(afs_globalVFS);
567 AFS_STATCNT(afs_GetDownD);
569 if (CheckLock(&afs_xdcache) != -1)
570 osi_Panic("getdownd nolock");
571 /* decrement anumber first for all dudes in free list */
572 /* SHOULD always decrement anumber first, even if aneedSpace >0,
573 * because we should try to free space even if anumber <=0 */
574 if (!aneedSpace || *aneedSpace <= 0) {
575 anumber -= afs_freeDCCount;
577 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
578 VFS_UNLOCK_GIANT(vfslocked);
580 return; /* enough already free */
584 /* bounds check parameter */
585 if (anumber > MAXATONCE)
586 anumber = MAXATONCE; /* all we can do */
588 /* rewrite so phases include a better eligiblity for gc test*/
590 * The phase variable manages reclaims. Set to 0, the first pass,
591 * we don't reclaim active entries, or other than target bucket.
592 * Set to 1, we reclaim even active ones in target bucket.
593 * Set to 2, we reclaim any inactive one.
594 * Set to 3, we reclaim even active ones.
602 for (i = 0; i < afs_cacheFiles; i++)
603 /* turn off all flags */
604 afs_indexFlags[i] &= ~IFFlag;
606 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
607 /* find oldest entries for reclamation */
608 maxVictimPtr = victimPtr = 0;
609 hzero(maxVictimTime);
610 curbucket = afs_DCWhichBucket(phase, buckethint);
611 /* select victims from access time array */
612 for (i = 0; i < afs_cacheFiles; i++) {
613 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
614 /* skip if dirty or already free */
617 tdc = afs_indexTable[i];
618 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
620 /* Wrong bucket; can't use it! */
623 if (tdc && (tdc->refCount != 0)) {
624 /* Referenced; can't use it! */
627 hset(vtime, afs_indexTimes[i]);
629 /* if we've already looked at this one, skip it */
630 if (afs_indexFlags[i] & IFFlag)
633 if (victimPtr < MAXATONCE) {
634 /* if there's at least one free victim slot left */
635 victims[victimPtr] = i;
636 hset(victimTimes[victimPtr], vtime);
637 if (hcmp(vtime, maxVictimTime) > 0) {
638 hset(maxVictimTime, vtime);
639 maxVictimPtr = victimPtr;
642 } else if (hcmp(vtime, maxVictimTime) < 0) {
644 * We're older than youngest victim, so we replace at
647 /* find youngest (largest LRU) victim */
650 osi_Panic("getdownd local");
652 hset(victimTimes[j], vtime);
653 /* recompute maxVictimTime */
654 hset(maxVictimTime, vtime);
655 for (j = 0; j < victimPtr; j++)
656 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
657 hset(maxVictimTime, victimTimes[j]);
663 /* now really reclaim the victims */
664 j = 0; /* flag to track if we actually got any of the victims */
665 /* first, hold all the victims, since we're going to release the lock
666 * during the truncate operation.
668 for (i = 0; i < victimPtr; i++) {
669 tdc = afs_GetDSlot(victims[i], 0);
670 /* We got tdc->tlock(R) here */
671 if (tdc->refCount == 1)
675 ReleaseReadLock(&tdc->tlock);
679 for (i = 0; i < victimPtr; i++) {
680 /* q is first elt in dcache entry */
682 /* now, since we're dropping the afs_xdcache lock below, we
683 * have to verify, before proceeding, that there are no other
684 * references to this dcache entry, even now. Note that we
685 * compare with 1, since we bumped it above when we called
686 * afs_GetDSlot to preserve the entry's identity.
688 if (tdc && tdc->refCount == 1) {
689 unsigned char chunkFlags;
690 afs_size_t tchunkoffset = 0;
692 /* xdcache is lower than the xvcache lock */
693 MReleaseWriteLock(&afs_xdcache);
694 MObtainReadLock(&afs_xvcache);
695 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
696 MReleaseReadLock(&afs_xvcache);
697 MObtainWriteLock(&afs_xdcache, 527);
699 if (tdc->refCount > 1)
702 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
703 chunkFlags = afs_indexFlags[tdc->index];
704 if (((phase & 1) == 0) && osi_Active(tvc))
706 if (((phase & 1) == 1) && osi_Active(tvc)
707 && (tvc->f.states & CDCLock)
708 && (chunkFlags & IFAnyPages))
710 if (chunkFlags & IFDataMod)
712 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
713 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
714 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
715 ICL_HANDLE_OFFSET(tchunkoffset));
717 #if defined(AFS_SUN5_ENV)
719 * Now we try to invalidate pages. We do this only for
720 * Solaris. For other platforms, it's OK to recycle a
721 * dcache entry out from under a page, because the strategy
722 * function can call afs_GetDCache().
724 if (!skip && (chunkFlags & IFAnyPages)) {
727 MReleaseWriteLock(&afs_xdcache);
728 MObtainWriteLock(&tvc->vlock, 543);
729 if (tvc->multiPage) {
733 /* block locking pages */
734 tvc->vstates |= VPageCleaning;
735 /* block getting new pages */
737 MReleaseWriteLock(&tvc->vlock);
738 /* One last recheck */
739 MObtainWriteLock(&afs_xdcache, 333);
740 chunkFlags = afs_indexFlags[tdc->index];
741 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
742 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
743 && (chunkFlags & IFAnyPages))) {
745 MReleaseWriteLock(&afs_xdcache);
748 MReleaseWriteLock(&afs_xdcache);
750 code = osi_VM_GetDownD(tvc, tdc);
752 MObtainWriteLock(&afs_xdcache, 269);
753 /* we actually removed all pages, clean and dirty */
755 afs_indexFlags[tdc->index] &=
756 ~(IFDirtyPages | IFAnyPages);
759 MReleaseWriteLock(&afs_xdcache);
761 MObtainWriteLock(&tvc->vlock, 544);
762 if (--tvc->activeV == 0
763 && (tvc->vstates & VRevokeWait)) {
764 tvc->vstates &= ~VRevokeWait;
765 afs_osi_Wakeup((char *)&tvc->vstates);
768 if (tvc->vstates & VPageCleaning) {
769 tvc->vstates &= ~VPageCleaning;
770 afs_osi_Wakeup((char *)&tvc->vstates);
773 MReleaseWriteLock(&tvc->vlock);
775 #endif /* AFS_SUN5_ENV */
777 MReleaseWriteLock(&afs_xdcache);
780 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
781 MObtainWriteLock(&afs_xdcache, 528);
782 if (afs_indexFlags[tdc->index] &
783 (IFDataMod | IFDirtyPages | IFAnyPages))
785 if (tdc->refCount > 1)
788 #if defined(AFS_SUN5_ENV)
790 /* no vnode, so IFDirtyPages is spurious (we don't
791 * sweep dcaches on vnode recycling, so we can have
792 * DIRTYPAGES set even when all pages are gone). Just
794 * Hold vcache lock to prevent vnode from being
795 * created while we're clearing IFDirtyPages.
797 afs_indexFlags[tdc->index] &=
798 ~(IFDirtyPages | IFAnyPages);
802 /* skip this guy and mark him as recently used */
803 afs_indexFlags[tdc->index] |= IFFlag;
804 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
805 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
806 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
807 ICL_HANDLE_OFFSET(tchunkoffset));
809 /* flush this dude from the data cache and reclaim;
810 * first, make sure no one will care that we damage
811 * it, by removing it from all hash tables. Then,
812 * melt it down for parts. Note that any concurrent
813 * (new possibility!) calls to GetDownD won't touch
814 * this guy because his reference count is > 0. */
815 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
816 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
817 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
818 ICL_HANDLE_OFFSET(tchunkoffset));
819 AFS_STATCNT(afs_gget);
820 afs_HashOutDCache(tdc, 1);
821 if (tdc->f.chunkBytes != 0) {
825 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
830 afs_DiscardDCache(tdc);
835 j = 1; /* we reclaimed at least one victim */
839 } /* end of for victims loop */
842 /* Phase is 0 and no one was found, so try phase 1 (ignore
843 * osi_Active flag) */
846 for (i = 0; i < afs_cacheFiles; i++)
847 /* turn off all flags */
848 afs_indexFlags[i] &= ~IFFlag;
851 /* found no one in phases 0-5, we're hosed */
855 } /* big while loop */
857 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
858 VFS_UNLOCK_GIANT(vfslocked);
867 * Remove adc from any hash tables that would allow it to be located
868 * again by afs_FindDCache or afs_GetDCache.
870 * \param adc Pointer to dcache entry to remove from hash tables.
872 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
876 afs_HashOutDCache(struct dcache *adc, int zap)
880 AFS_STATCNT(afs_glink);
882 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
884 /* if this guy is in the hash table, pull him out */
885 if (adc->f.fid.Fid.Volume != 0) {
886 /* remove entry from first hash chains */
887 i = DCHash(&adc->f.fid, adc->f.chunk);
888 us = afs_dchashTbl[i];
889 if (us == adc->index) {
890 /* first dude in the list */
891 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
893 /* somewhere on the chain */
894 while (us != NULLIDX) {
895 if (afs_dcnextTbl[us] == adc->index) {
896 /* found item pointing at the one to delete */
897 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
900 us = afs_dcnextTbl[us];
903 osi_Panic("dcache hc");
905 /* remove entry from *other* hash chain */
906 i = DVHash(&adc->f.fid);
907 us = afs_dvhashTbl[i];
908 if (us == adc->index) {
909 /* first dude in the list */
910 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
912 /* somewhere on the chain */
913 while (us != NULLIDX) {
914 if (afs_dvnextTbl[us] == adc->index) {
915 /* found item pointing at the one to delete */
916 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
919 us = afs_dvnextTbl[us];
922 osi_Panic("dcache hv");
927 /* prevent entry from being found on a reboot (it is already out of
928 * the hash table, but after a crash, we just look at fid fields of
929 * stable (old) entries).
931 adc->f.fid.Fid.Volume = 0; /* invalid */
933 /* mark entry as modified */
934 adc->dflags |= DFEntryMod;
939 } /*afs_HashOutDCache */
942 * Flush the given dcache entry, pulling it from hash chains
943 * and truncating the associated cache file.
945 * \param adc Ptr to dcache entry to flush.
948 * This routine must be called with the afs_xdcache lock held
952 afs_FlushDCache(register struct dcache *adc)
954 AFS_STATCNT(afs_FlushDCache);
956 * Bump the number of cache files flushed.
958 afs_stats_cmperf.cacheFlushes++;
960 /* remove from all hash tables */
961 afs_HashOutDCache(adc, 1);
963 /* Free its space; special case null operation, since truncate operation
964 * in UFS is slow even in this case, and this allows us to pre-truncate
965 * these files at more convenient times with fewer locks set
966 * (see afs_GetDownD).
968 if (adc->f.chunkBytes != 0) {
969 afs_DiscardDCache(adc);
970 afs_MaybeWakeupTruncateDaemon();
975 if (afs_WaitForCacheDrain) {
976 if (afs_blocksUsed <=
977 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
978 afs_WaitForCacheDrain = 0;
979 afs_osi_Wakeup(&afs_WaitForCacheDrain);
982 } /*afs_FlushDCache */
986 * Put a dcache entry on the free dcache entry list.
988 * \param adc dcache entry to free.
990 * \note Environment: called with afs_xdcache lock write-locked.
993 afs_FreeDCache(register struct dcache *adc)
995 /* Thread on free list, update free list count and mark entry as
996 * freed in its indexFlags element. Also, ensure DCache entry gets
997 * written out (set DFEntryMod).
1000 afs_dvnextTbl[adc->index] = afs_freeDCList;
1001 afs_freeDCList = adc->index;
1003 afs_indexFlags[adc->index] |= IFFree;
1004 adc->dflags |= DFEntryMod;
1006 if (afs_WaitForCacheDrain) {
1007 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1008 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1009 afs_WaitForCacheDrain = 0;
1010 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1013 } /* afs_FreeDCache */
1016 * Discard the cache element by moving it to the discardDCList.
1017 * This puts the cache element into a quasi-freed state, where
1018 * the space may be reused, but the file has not been truncated.
1020 * \note Major Assumptions Here:
1021 * Assumes that frag size is an integral power of two, less one,
1022 * and that this is a two's complement machine. I don't
1023 * know of any filesystems which violate this assumption...
1025 * \param adr Ptr to dcache entry.
1027 * \note Environment:
1028 * Must be called with afs_xdcache write-locked.
1032 afs_DiscardDCache(register struct dcache *adc)
1034 register afs_int32 size;
1036 AFS_STATCNT(afs_DiscardDCache);
1038 osi_Assert(adc->refCount == 1);
1040 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1041 afs_blocksDiscarded += size;
1042 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1044 afs_dvnextTbl[adc->index] = afs_discardDCList;
1045 afs_discardDCList = adc->index;
1046 afs_discardDCCount++;
1048 adc->f.fid.Fid.Volume = 0;
1049 adc->dflags |= DFEntryMod;
1050 afs_indexFlags[adc->index] |= IFDiscarded;
1052 if (afs_WaitForCacheDrain) {
1053 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1054 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1055 afs_WaitForCacheDrain = 0;
1056 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1060 } /*afs_DiscardDCache */
1063 * Free the next element on the list of discarded cache elements.
1066 afs_FreeDiscardedDCache(void)
1068 register struct dcache *tdc;
1069 register struct osi_file *tfile;
1070 register afs_int32 size;
1072 AFS_STATCNT(afs_FreeDiscardedDCache);
1074 MObtainWriteLock(&afs_xdcache, 510);
1075 if (!afs_blocksDiscarded) {
1076 MReleaseWriteLock(&afs_xdcache);
1081 * Get an entry from the list of discarded cache elements
1083 tdc = afs_GetDSlot(afs_discardDCList, 0);
1084 osi_Assert(tdc->refCount == 1);
1085 ReleaseReadLock(&tdc->tlock);
1087 afs_discardDCList = afs_dvnextTbl[tdc->index];
1088 afs_dvnextTbl[tdc->index] = NULLIDX;
1089 afs_discardDCCount--;
1090 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1091 afs_blocksDiscarded -= size;
1092 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1093 /* We can lock because we just took it off the free list */
1094 ObtainWriteLock(&tdc->lock, 626);
1095 MReleaseWriteLock(&afs_xdcache);
1098 * Truncate the element to reclaim its space
1100 tfile = afs_CFileOpen(&tdc->f.inode);
1101 afs_CFileTruncate(tfile, 0);
1102 afs_CFileClose(tfile);
1103 afs_AdjustSize(tdc, 0);
1104 afs_DCMoveBucket(tdc, 0, 0);
1107 * Free the element we just truncated
1109 MObtainWriteLock(&afs_xdcache, 511);
1110 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1111 afs_FreeDCache(tdc);
1112 tdc->f.states &= ~(DRO|DBackup|DRW);
1113 ReleaseWriteLock(&tdc->lock);
1115 MReleaseWriteLock(&afs_xdcache);
1119 * Free as many entries from the list of discarded cache elements
1120 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1125 afs_MaybeFreeDiscardedDCache(void)
1128 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1130 while (afs_blocksDiscarded
1131 && (afs_blocksUsed >
1132 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1133 afs_FreeDiscardedDCache();
1139 * Try to free up a certain number of disk slots.
1141 * \param anumber Targeted number of disk slots to free up.
1143 * \note Environment:
1144 * Must be called with afs_xdcache write-locked.
1148 afs_GetDownDSlot(int anumber)
1150 struct afs_q *tq, *nq;
1155 AFS_STATCNT(afs_GetDownDSlot);
1156 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1157 osi_Panic("diskless getdowndslot");
1159 if (CheckLock(&afs_xdcache) != -1)
1160 osi_Panic("getdowndslot nolock");
1162 /* decrement anumber first for all dudes in free list */
1163 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1166 return; /* enough already free */
1168 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1170 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1171 nq = QPrev(tq); /* in case we remove it */
1172 if (tdc->refCount == 0) {
1173 if ((ix = tdc->index) == NULLIDX)
1174 osi_Panic("getdowndslot");
1175 /* pull the entry out of the lruq and put it on the free list */
1176 QRemove(&tdc->lruq);
1178 /* write-through if modified */
1179 if (tdc->dflags & DFEntryMod) {
1180 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1182 * ask proxy to do this for us - we don't have the stack space
1184 while (tdc->dflags & DFEntryMod) {
1187 s = SPLOCK(afs_sgibklock);
1188 if (afs_sgibklist == NULL) {
1189 /* if slot is free, grab it. */
1190 afs_sgibklist = tdc;
1191 SV_SIGNAL(&afs_sgibksync);
1193 /* wait for daemon to (start, then) finish. */
1194 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1198 tdc->dflags &= ~DFEntryMod;
1199 afs_WriteDCache(tdc, 1);
1203 /* finally put the entry in the free list */
1204 afs_indexTable[ix] = NULL;
1205 afs_indexFlags[ix] &= ~IFEverUsed;
1206 tdc->index = NULLIDX;
1207 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1208 afs_freeDSList = tdc;
1212 } /*afs_GetDownDSlot */
1219 * Increment the reference count on a disk cache entry,
1220 * which already has a non-zero refcount. In order to
1221 * increment the refcount of a zero-reference entry, you
1222 * have to hold afs_xdcache.
1225 * adc : Pointer to the dcache entry to increment.
1228 * Nothing interesting.
1231 afs_RefDCache(struct dcache *adc)
1233 ObtainWriteLock(&adc->tlock, 627);
1234 if (adc->refCount < 0)
1235 osi_Panic("RefDCache: negative refcount");
1237 ReleaseWriteLock(&adc->tlock);
1246 * Decrement the reference count on a disk cache entry.
1249 * ad : Ptr to the dcache entry to decrement.
1252 * Nothing interesting.
1255 afs_PutDCache(register struct dcache *adc)
1257 AFS_STATCNT(afs_PutDCache);
1258 ObtainWriteLock(&adc->tlock, 276);
1259 if (adc->refCount <= 0)
1260 osi_Panic("putdcache");
1262 ReleaseWriteLock(&adc->tlock);
1271 * Try to discard all data associated with this file from the
1275 * avc : Pointer to the cache info for the file.
1278 * Both pvnLock and lock are write held.
1281 afs_TryToSmush(register struct vcache *avc, struct AFS_UCRED *acred, int sync)
1283 register struct dcache *tdc;
1286 AFS_STATCNT(afs_TryToSmush);
1287 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1288 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1289 sync = 1; /* XX Temp testing XX */
1291 #if defined(AFS_SUN5_ENV)
1292 ObtainWriteLock(&avc->vlock, 573);
1293 avc->activeV++; /* block new getpages */
1294 ReleaseWriteLock(&avc->vlock);
1297 /* Flush VM pages */
1298 osi_VM_TryToSmush(avc, acred, sync);
1301 * Get the hash chain containing all dce's for this fid
1303 i = DVHash(&avc->f.fid);
1304 MObtainWriteLock(&afs_xdcache, 277);
1305 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1306 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1307 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1308 int releaseTlock = 1;
1309 tdc = afs_GetDSlot(index, NULL);
1310 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1312 if ((afs_indexFlags[index] & IFDataMod) == 0
1313 && tdc->refCount == 1) {
1314 ReleaseReadLock(&tdc->tlock);
1316 afs_FlushDCache(tdc);
1319 afs_indexTable[index] = 0;
1322 ReleaseReadLock(&tdc->tlock);
1326 #if defined(AFS_SUN5_ENV)
1327 ObtainWriteLock(&avc->vlock, 545);
1328 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1329 avc->vstates &= ~VRevokeWait;
1330 afs_osi_Wakeup((char *)&avc->vstates);
1332 ReleaseWriteLock(&avc->vlock);
1334 MReleaseWriteLock(&afs_xdcache);
1336 * It's treated like a callback so that when we do lookups we'll
1337 * invalidate the unique bit if any
1338 * trytoSmush occured during the lookup call
1344 * afs_DCacheMissingChunks
1347 * Given the cached info for a file, return the number of chunks that
1348 * are not available from the dcache.
1351 * avc: Pointer to the (held) vcache entry to look in.
1354 * The number of chunks which are not currently cached.
1357 * The vcache entry is held upon entry.
1361 afs_DCacheMissingChunks(struct vcache *avc)
1364 afs_size_t totalLength = 0;
1365 afs_uint32 totalChunks = 0;
1368 totalLength = avc->f.m.Length;
1369 if (avc->f.truncPos < totalLength)
1370 totalLength = avc->f.truncPos;
1372 /* Length is 0, no chunk missing. */
1373 if (totalLength == 0)
1376 /* If totalLength is a multiple of chunksize, the last byte appears
1377 * as being part of the next chunk, which does not exist.
1378 * Decrementing totalLength by one fixes that.
1381 totalChunks = (AFS_CHUNK(totalLength) + 1);
1383 /* If we're a directory, we only ever have one chunk, regardless of
1384 * the size of the dir.
1386 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1390 printf("Should have %d chunks for %u bytes\n",
1391 totalChunks, (totalLength + 1));
1393 i = DVHash(&avc->f.fid);
1394 MObtainWriteLock(&afs_xdcache, 1001);
1395 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1396 i = afs_dvnextTbl[index];
1397 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1398 tdc = afs_GetDSlot(index, NULL);
1399 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1402 ReleaseReadLock(&tdc->tlock);
1406 MReleaseWriteLock(&afs_xdcache);
1408 /*printf("Missing %d chunks\n", totalChunks);*/
1410 return (totalChunks);
1417 * Given the cached info for a file and a byte offset into the
1418 * file, make sure the dcache entry for that file and containing
1419 * the given byte is available, returning it to our caller.
1422 * avc : Pointer to the (held) vcache entry to look in.
1423 * abyte : Which byte we want to get to.
1426 * Pointer to the dcache entry covering the file & desired byte,
1427 * or NULL if not found.
1430 * The vcache entry is held upon entry.
1434 afs_FindDCache(register struct vcache *avc, afs_size_t abyte)
1437 register afs_int32 i, index;
1438 register struct dcache *tdc = NULL;
1440 AFS_STATCNT(afs_FindDCache);
1441 chunk = AFS_CHUNK(abyte);
1444 * Hash on the [fid, chunk] and get the corresponding dcache index
1445 * after write-locking the dcache.
1447 i = DCHash(&avc->f.fid, chunk);
1448 MObtainWriteLock(&afs_xdcache, 278);
1449 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1450 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1451 tdc = afs_GetDSlot(index, NULL);
1452 ReleaseReadLock(&tdc->tlock);
1453 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1454 break; /* leaving refCount high for caller */
1458 index = afs_dcnextTbl[index];
1460 if (index != NULLIDX) {
1461 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1462 hadd32(afs_indexCounter, 1);
1463 MReleaseWriteLock(&afs_xdcache);
1466 MReleaseWriteLock(&afs_xdcache);
1468 } /*afs_FindDCache */
1473 * Get a fresh dcache from the free or discarded list.
1475 * \param avc Who's dcache is this going to be?
1476 * \param chunk The position where it will be placed in.
1477 * \param lock How are locks held.
1478 * \param ashFid If this dcache going to be used for a shadow dir,
1481 * \note Required locks:
1483 * - avc (R if (lock & 1) set and W otherwise)
1484 * \note It write locks the new dcache. The caller must unlock it.
1486 * \return The new dcache.
1488 struct dcache *afs_AllocDCache(struct vcache *avc,
1491 struct VenusFid *ashFid)
1493 struct dcache *tdc = NULL;
1494 afs_uint32 size = 0;
1495 struct osi_file *file;
1497 if (afs_discardDCList == NULLIDX
1498 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1500 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1501 tdc = afs_GetDSlot(afs_freeDCList, 0);
1502 osi_Assert(tdc->refCount == 1);
1503 ReleaseReadLock(&tdc->tlock);
1504 ObtainWriteLock(&tdc->lock, 604);
1505 afs_freeDCList = afs_dvnextTbl[tdc->index];
1508 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1509 tdc = afs_GetDSlot(afs_discardDCList, 0);
1510 osi_Assert(tdc->refCount == 1);
1511 ReleaseReadLock(&tdc->tlock);
1512 ObtainWriteLock(&tdc->lock, 605);
1513 afs_discardDCList = afs_dvnextTbl[tdc->index];
1514 afs_discardDCCount--;
1516 ((tdc->f.chunkBytes +
1517 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1518 tdc->f.states &= ~(DRO|DBackup|DRW);
1519 afs_DCMoveBucket(tdc, size, 0);
1520 afs_blocksDiscarded -= size;
1521 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1523 /* Truncate the chunk so zeroes get filled properly */
1524 file = afs_CFileOpen(&tdc->f.inode);
1525 afs_CFileTruncate(file, 0);
1526 afs_CFileClose(file);
1527 afs_AdjustSize(tdc, 0);
1533 * avc->lock(R) if setLocks
1534 * avc->lock(W) if !setLocks
1540 * Fill in the newly-allocated dcache record.
1542 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1544 /* Use shadow fid if provided. */
1545 tdc->f.fid = *ashFid;
1547 /* Use normal vcache's fid otherwise. */
1548 tdc->f.fid = avc->f.fid;
1549 if (avc->f.states & CRO)
1550 tdc->f.states = DRO;
1551 else if (avc->f.states & CBackup)
1552 tdc->f.states = DBackup;
1554 tdc->f.states = DRW;
1555 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1556 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1558 hones(tdc->f.versionNo); /* invalid value */
1559 tdc->f.chunk = chunk;
1560 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1562 if (tdc->lruq.prev == &tdc->lruq)
1563 osi_Panic("lruq 1");
1572 * This function is called to obtain a reference to data stored in
1573 * the disk cache, locating a chunk of data containing the desired
1574 * byte and returning a reference to the disk cache entry, with its
1575 * reference count incremented.
1579 * avc : Ptr to a vcache entry (unlocked)
1580 * abyte : Byte position in the file desired
1581 * areq : Request structure identifying the requesting user.
1582 * aflags : Settings as follows:
1584 * 2 : Return after creating entry.
1585 * 4 : called from afs_vnop_write.c
1586 * *alen contains length of data to be written.
1588 * aoffset : Set to the offset within the chunk where the resident
1590 * alen : Set to the number of bytes of data after the desired
1591 * byte (including the byte itself) which can be read
1595 * The vcache entry pointed to by avc is unlocked upon entry.
1599 struct AFSVolSync tsync;
1600 struct AFSFetchStatus OutStatus;
1601 struct AFSCallBack CallBack;
1605 * Update the vnode-to-dcache hint if we can get the vnode lock
1606 * right away. Assumes dcache entry is at least read-locked.
1609 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1611 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1612 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1615 ReleaseWriteLock(&v->lock);
1619 /* avc - Write-locked unless aflags & 1 */
1621 afs_GetDCache(register struct vcache *avc, afs_size_t abyte,
1622 register struct vrequest *areq, afs_size_t * aoffset,
1623 afs_size_t * alen, int aflags)
1625 register afs_int32 i, code, code1 = 0, shortcut;
1626 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1627 register afs_int32 adjustsize = 0;
1633 afs_size_t maxGoodLength; /* amount of good data at server */
1634 struct rx_call *tcall;
1635 afs_size_t Position = 0;
1636 #ifdef AFS_64BIT_CLIENT
1638 afs_size_t lengthFound; /* as returned from server */
1639 #endif /* AFS_64BIT_CLIENT */
1640 afs_int32 size, tlen; /* size of segment to transfer */
1641 struct tlocal1 *tsmall = 0;
1642 register struct dcache *tdc;
1643 register struct osi_file *file;
1644 register struct afs_conn *tc;
1646 struct server *newCallback = NULL;
1647 char setNewCallback;
1648 char setVcacheStatus;
1649 char doVcacheUpdate;
1651 int doAdjustSize = 0;
1652 int doReallyAdjustSize = 0;
1653 int overWriteWholeChunk = 0;
1657 struct afs_stats_xferData *xferP; /* Ptr to this op's xfer struct */
1658 osi_timeval_t xferStartTime, /*FS xfer start time */
1659 xferStopTime; /*FS xfer stop time */
1660 afs_size_t bytesToXfer; /* # bytes to xfer */
1661 afs_size_t bytesXferred; /* # bytes actually xferred */
1662 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1663 int fromReplica; /*Are we reading from a replica? */
1664 int numFetchLoops; /*# times around the fetch/analyze loop */
1665 #endif /* AFS_NOSTATS */
1667 AFS_STATCNT(afs_GetDCache);
1671 setLocks = aflags & 1;
1674 * Determine the chunk number and offset within the chunk corresponding
1675 * to the desired byte.
1677 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1680 chunk = AFS_CHUNK(abyte);
1683 /* come back to here if we waited for the cache to drain. */
1686 setNewCallback = setVcacheStatus = 0;
1690 ObtainWriteLock(&avc->lock, 616);
1692 ObtainReadLock(&avc->lock);
1697 * avc->lock(R) if setLocks && !slowPass
1698 * avc->lock(W) if !setLocks || slowPass
1703 /* check hints first! (might could use bcmp or some such...) */
1704 if ((tdc = avc->dchint)) {
1708 * The locking order between afs_xdcache and dcache lock matters.
1709 * The hint dcache entry could be anywhere, even on the free list.
1710 * Locking afs_xdcache ensures that noone is trying to pull dcache
1711 * entries from the free list, and thereby assuming them to be not
1712 * referenced and not locked.
1714 MObtainReadLock(&afs_xdcache);
1715 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1717 if (dcLocked && (tdc->index != NULLIDX)
1718 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1719 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1720 /* got the right one. It might not be the right version, and it
1721 * might be fetching, but it's the right dcache entry.
1723 /* All this code should be integrated better with what follows:
1724 * I can save a good bit more time under a write lock if I do..
1726 ObtainWriteLock(&tdc->tlock, 603);
1728 ReleaseWriteLock(&tdc->tlock);
1730 MReleaseReadLock(&afs_xdcache);
1733 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1734 && !(tdc->dflags & DFFetching)) {
1736 afs_stats_cmperf.dcacheHits++;
1737 MObtainWriteLock(&afs_xdcache, 559);
1738 QRemove(&tdc->lruq);
1739 QAdd(&afs_DLRU, &tdc->lruq);
1740 MReleaseWriteLock(&afs_xdcache);
1743 * avc->lock(R) if setLocks && !slowPass
1744 * avc->lock(W) if !setLocks || slowPass
1751 ReleaseSharedLock(&tdc->lock);
1752 MReleaseReadLock(&afs_xdcache);
1760 * avc->lock(R) if setLocks && !slowPass
1761 * avc->lock(W) if !setLocks || slowPass
1762 * tdc->lock(S) if tdc
1765 if (!tdc) { /* If the hint wasn't the right dcache entry */
1767 * Hash on the [fid, chunk] and get the corresponding dcache index
1768 * after write-locking the dcache.
1773 * avc->lock(R) if setLocks && !slowPass
1774 * avc->lock(W) if !setLocks || slowPass
1777 i = DCHash(&avc->f.fid, chunk);
1778 /* check to make sure our space is fine */
1779 afs_MaybeWakeupTruncateDaemon();
1781 MObtainWriteLock(&afs_xdcache, 280);
1783 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1784 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1785 tdc = afs_GetDSlot(index, NULL);
1786 ReleaseReadLock(&tdc->tlock);
1789 * avc->lock(R) if setLocks && !slowPass
1790 * avc->lock(W) if !setLocks || slowPass
1793 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1794 /* Move it up in the beginning of the list */
1795 if (afs_dchashTbl[i] != index) {
1796 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1797 afs_dcnextTbl[index] = afs_dchashTbl[i];
1798 afs_dchashTbl[i] = index;
1800 MReleaseWriteLock(&afs_xdcache);
1801 ObtainSharedLock(&tdc->lock, 606);
1802 break; /* leaving refCount high for caller */
1808 index = afs_dcnextTbl[index];
1812 * If we didn't find the entry, we'll create one.
1814 if (index == NULLIDX) {
1817 * avc->lock(R) if setLocks
1818 * avc->lock(W) if !setLocks
1821 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1822 avc, ICL_TYPE_INT32, chunk);
1824 /* Make sure there is a free dcache entry for us to use */
1825 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1828 avc->f.states |= CDCLock;
1829 /* just need slots */
1830 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1832 avc->f.states &= ~CDCLock;
1833 if (afs_discardDCList != NULLIDX
1834 || afs_freeDCList != NULLIDX)
1836 /* If we can't get space for 5 mins we give up and panic */
1837 if (++downDCount > 300) {
1838 #if defined(AFS_CACHE_BYPASS)
1839 afs_warn("GetDCache calling osi_Panic: No space in five minutes.\n downDCount: %d\n aoffset: %d alen: %d\n", downDCount, aoffset, alen);
1841 osi_Panic("getdcache");
1843 MReleaseWriteLock(&afs_xdcache);
1846 * avc->lock(R) if setLocks
1847 * avc->lock(W) if !setLocks
1849 afs_osi_Wait(1000, 0, 0);
1854 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1857 * Now add to the two hash chains - note that i is still set
1858 * from the above DCHash call.
1860 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1861 afs_dchashTbl[i] = tdc->index;
1862 i = DVHash(&avc->f.fid);
1863 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1864 afs_dvhashTbl[i] = tdc->index;
1865 tdc->dflags = DFEntryMod;
1867 afs_MaybeWakeupTruncateDaemon();
1868 MReleaseWriteLock(&afs_xdcache);
1869 ConvertWToSLock(&tdc->lock);
1874 /* vcache->dcache hint failed */
1877 * avc->lock(R) if setLocks && !slowPass
1878 * avc->lock(W) if !setLocks || slowPass
1881 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1882 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1883 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1884 hgetlo(avc->f.m.DataVersion));
1886 * Here we have the entry in tdc, with its refCount incremented.
1887 * Note: we don't use the S-lock on avc; it costs concurrency when
1888 * storing a file back to the server.
1892 * Not a newly created file so we need to check the file's length and
1893 * compare data versions since someone could have changed the data or we're
1894 * reading a file written elsewhere. We only want to bypass doing no-op
1895 * read rpcs on newly created files (dv of 0) since only then we guarantee
1896 * that this chunk's data hasn't been filled by another client.
1898 size = AFS_CHUNKSIZE(abyte);
1899 if (aflags & 4) /* called from write */
1901 else /* called from read */
1902 tlen = tdc->validPos - abyte;
1903 Position = AFS_CHUNKTOBASE(chunk);
1904 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1905 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1906 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1907 ICL_HANDLE_OFFSET(Position));
1908 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
1910 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
1911 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
1912 overWriteWholeChunk = 1;
1913 if (doAdjustSize || overWriteWholeChunk) {
1914 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1916 #ifdef AFS_SGI64_ENV
1919 #else /* AFS_SGI64_ENV */
1922 #endif /* AFS_SGI64_ENV */
1923 #else /* AFS_SGI_ENV */
1926 #endif /* AFS_SGI_ENV */
1927 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
1928 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1929 #if defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV)
1930 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
1932 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
1934 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1935 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
1936 doReallyAdjustSize = 1;
1938 if (doReallyAdjustSize || overWriteWholeChunk) {
1939 /* no data in file to read at this position */
1940 UpgradeSToWLock(&tdc->lock, 607);
1941 file = afs_CFileOpen(&tdc->f.inode);
1942 afs_CFileTruncate(file, 0);
1943 afs_CFileClose(file);
1944 afs_AdjustSize(tdc, 0);
1945 hset(tdc->f.versionNo, avc->f.m.DataVersion);
1946 tdc->dflags |= DFEntryMod;
1948 ConvertWToSLock(&tdc->lock);
1953 * We must read in the whole chunk if the version number doesn't
1957 /* don't need data, just a unique dcache entry */
1958 ObtainWriteLock(&afs_xdcache, 608);
1959 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1960 hadd32(afs_indexCounter, 1);
1961 ReleaseWriteLock(&afs_xdcache);
1963 updateV2DC(setLocks, avc, tdc, 553);
1964 if (vType(avc) == VDIR)
1967 *aoffset = AFS_CHUNKOFFSET(abyte);
1968 if (tdc->validPos < abyte)
1969 *alen = (afs_size_t) 0;
1971 *alen = tdc->validPos - abyte;
1972 ReleaseSharedLock(&tdc->lock);
1975 ReleaseWriteLock(&avc->lock);
1977 ReleaseReadLock(&avc->lock);
1979 return tdc; /* check if we're done */
1984 * avc->lock(R) if setLocks && !slowPass
1985 * avc->lock(W) if !setLocks || slowPass
1988 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
1990 setNewCallback = setVcacheStatus = 0;
1994 * avc->lock(R) if setLocks && !slowPass
1995 * avc->lock(W) if !setLocks || slowPass
1998 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2000 * Version number mismatch.
2003 * If we are disconnected, then we can't do much of anything
2004 * because the data doesn't match the file.
2006 if (AFS_IS_DISCONNECTED) {
2007 ReleaseSharedLock(&tdc->lock);
2010 ReleaseWriteLock(&avc->lock);
2012 ReleaseReadLock(&avc->lock);
2014 /* Flush the Dcache */
2019 UpgradeSToWLock(&tdc->lock, 609);
2022 * If data ever existed for this vnode, and this is a text object,
2023 * do some clearing. Now, you'd think you need only do the flush
2024 * when VTEXT is on, but VTEXT is turned off when the text object
2025 * is freed, while pages are left lying around in memory marked
2026 * with this vnode. If we would reactivate (create a new text
2027 * object from) this vnode, we could easily stumble upon some of
2028 * these old pages in pagein. So, we always flush these guys.
2029 * Sun has a wonderful lack of useful invariants in this system.
2031 * avc->flushDV is the data version # of the file at the last text
2032 * flush. Clearly, at least, we don't have to flush the file more
2033 * often than it changes
2035 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2037 * By here, the cache entry is always write-locked. We can
2038 * deadlock if we call osi_Flush with the cache entry locked...
2039 * Unlock the dcache too.
2041 ReleaseWriteLock(&tdc->lock);
2042 if (setLocks && !slowPass)
2043 ReleaseReadLock(&avc->lock);
2045 ReleaseWriteLock(&avc->lock);
2049 * Call osi_FlushPages in open, read/write, and map, since it
2050 * is too hard here to figure out if we should lock the
2053 if (setLocks && !slowPass)
2054 ObtainReadLock(&avc->lock);
2056 ObtainWriteLock(&avc->lock, 66);
2057 ObtainWriteLock(&tdc->lock, 610);
2062 * avc->lock(R) if setLocks && !slowPass
2063 * avc->lock(W) if !setLocks || slowPass
2067 /* Watch for standard race condition around osi_FlushText */
2068 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2069 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2070 afs_stats_cmperf.dcacheHits++;
2071 ConvertWToSLock(&tdc->lock);
2075 /* Sleep here when cache needs to be drained. */
2076 if (setLocks && !slowPass
2077 && (afs_blocksUsed >
2078 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2079 /* Make sure truncate daemon is running */
2080 afs_MaybeWakeupTruncateDaemon();
2081 ObtainWriteLock(&tdc->tlock, 614);
2082 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2083 ReleaseWriteLock(&tdc->tlock);
2084 ReleaseWriteLock(&tdc->lock);
2085 ReleaseReadLock(&avc->lock);
2086 while ((afs_blocksUsed - afs_blocksDiscarded) >
2087 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2088 afs_WaitForCacheDrain = 1;
2089 afs_osi_Sleep(&afs_WaitForCacheDrain);
2091 afs_MaybeFreeDiscardedDCache();
2092 /* need to check if someone else got the chunk first. */
2093 goto RetryGetDCache;
2096 /* Do not fetch data beyond truncPos. */
2097 maxGoodLength = avc->f.m.Length;
2098 if (avc->f.truncPos < maxGoodLength)
2099 maxGoodLength = avc->f.truncPos;
2100 Position = AFS_CHUNKBASE(abyte);
2101 if (vType(avc) == VDIR) {
2102 size = avc->f.m.Length;
2103 if (size > tdc->f.chunkBytes) {
2104 /* pre-reserve space for file */
2105 afs_AdjustSize(tdc, size);
2107 size = 999999999; /* max size for transfer */
2109 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2110 /* don't read past end of good data on server */
2111 if (Position + size > maxGoodLength)
2112 size = maxGoodLength - Position;
2114 size = 0; /* Handle random races */
2115 if (size > tdc->f.chunkBytes) {
2116 /* pre-reserve space for file */
2117 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2118 /* max size for transfer still in size */
2121 if (afs_mariner && !tdc->f.chunk)
2122 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2124 * Right now, we only have one tool, and it's a hammer. So, we
2125 * fetch the whole file.
2127 DZap(tdc); /* pages in cache may be old */
2128 file = afs_CFileOpen(&tdc->f.inode);
2129 afs_RemoveVCB(&avc->f.fid);
2130 tdc->f.states |= DWriting;
2131 tdc->dflags |= DFFetching;
2132 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2133 if (tdc->mflags & DFFetchReq) {
2134 tdc->mflags &= ~DFFetchReq;
2135 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2136 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2137 __FILE__, ICL_TYPE_INT32, __LINE__,
2138 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2142 (struct tlocal1 *)osi_AllocLargeSpace(sizeof(struct tlocal1));
2143 setVcacheStatus = 0;
2146 * Remember if we are doing the reading from a replicated volume,
2147 * and how many times we've zipped around the fetch/analyze loop.
2149 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2151 accP = &(afs_stats_cmfullperf.accessinf);
2153 (accP->replicatedRefs)++;
2155 (accP->unreplicatedRefs)++;
2156 #endif /* AFS_NOSTATS */
2157 /* this is a cache miss */
2158 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2159 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2160 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2163 afs_stats_cmperf.dcacheMisses++;
2166 * Dynamic root support: fetch data from local memory.
2168 if (afs_IsDynroot(avc)) {
2172 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2174 dynrootDir += Position;
2175 dynrootLen -= Position;
2176 if (size > dynrootLen)
2180 code = afs_CFileWrite(file, 0, dynrootDir, size);
2188 tdc->validPos = Position + size;
2189 afs_CFileTruncate(file, size); /* prune it */
2190 } else if (afs_IsDynrootMount(avc)) {
2194 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2196 dynrootDir += Position;
2197 dynrootLen -= Position;
2198 if (size > dynrootLen)
2202 code = afs_CFileWrite(file, 0, dynrootDir, size);
2210 tdc->validPos = Position + size;
2211 afs_CFileTruncate(file, size); /* prune it */
2214 * Not a dynamic vnode: do the real fetch.
2219 * avc->lock(R) if setLocks && !slowPass
2220 * avc->lock(W) if !setLocks || slowPass
2224 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
2226 #ifdef AFS_64BIT_CLIENT
2227 afs_int32 length_hi;
2229 afs_int32 length, bytes;
2233 (accP->numReplicasAccessed)++;
2235 #endif /* AFS_NOSTATS */
2236 if (!setLocks || slowPass) {
2237 avc->callback = tc->srvr->server;
2239 newCallback = tc->srvr->server;
2244 tcall = rx_NewCall(tc->id);
2247 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2248 #ifdef AFS_64BIT_CLIENT
2249 length_hi = code = 0;
2250 if (!afs_serverHasNo64Bit(tc)) {
2254 StartRXAFS_FetchData64(tcall,
2255 (struct AFSFid *)&avc->f.fid.
2256 Fid, Position, tsize);
2259 afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2260 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2264 rx_Read(tcall, (char *)&length_hi,
2267 if (bytes == sizeof(afs_int32)) {
2268 length_hi = ntohl(length_hi);
2271 code = rx_Error(tcall);
2273 code1 = rx_EndCall(tcall, code);
2275 tcall = (struct rx_call *)0;
2279 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2280 if (Position > 0x7FFFFFFF) {
2287 tcall = rx_NewCall(tc->id);
2289 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2290 &avc->f.fid.Fid, pos,
2294 afs_serverSetNo64Bit(tc);
2299 rx_Read(tcall, (char *)&length,
2302 if (bytes == sizeof(afs_int32)) {
2303 length = ntohl(length);
2305 code = rx_Error(tcall);
2308 FillInt64(lengthFound, length_hi, length);
2309 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2310 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2312 ICL_HANDLE_OFFSET(lengthFound));
2313 #else /* AFS_64BIT_CLIENT */
2316 StartRXAFS_FetchData(tcall,
2317 (struct AFSFid *)&avc->f.fid.Fid,
2323 rx_Read(tcall, (char *)&length,
2326 if (bytes == sizeof(afs_int32)) {
2327 length = ntohl(length);
2329 code = rx_Error(tcall);
2332 #endif /* AFS_64BIT_CLIENT */
2337 &(afs_stats_cmfullperf.rpc.
2338 fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2339 osi_GetuTime(&xferStartTime);
2342 afs_CacheFetchProc(tcall, file,
2343 (afs_size_t) Position, tdc,
2345 &bytesXferred, length);
2347 osi_GetuTime(&xferStopTime);
2348 (xferP->numXfers)++;
2350 (xferP->numSuccesses)++;
2351 afs_stats_XferSumBytes
2352 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2354 (xferP->sumBytes) +=
2355 (afs_stats_XferSumBytes
2356 [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2357 afs_stats_XferSumBytes
2358 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2359 if (bytesXferred < xferP->minBytes)
2360 xferP->minBytes = bytesXferred;
2361 if (bytesXferred > xferP->maxBytes)
2362 xferP->maxBytes = bytesXferred;
2365 * Tally the size of the object. Note: we tally the actual size,
2366 * NOT the number of bytes that made it out over the wire.
2368 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2369 (xferP->count[0])++;
2370 else if (bytesToXfer <=
2371 AFS_STATS_MAXBYTES_BUCKET1)
2372 (xferP->count[1])++;
2373 else if (bytesToXfer <=
2374 AFS_STATS_MAXBYTES_BUCKET2)
2375 (xferP->count[2])++;
2376 else if (bytesToXfer <=
2377 AFS_STATS_MAXBYTES_BUCKET3)
2378 (xferP->count[3])++;
2379 else if (bytesToXfer <=
2380 AFS_STATS_MAXBYTES_BUCKET4)
2381 (xferP->count[4])++;
2382 else if (bytesToXfer <=
2383 AFS_STATS_MAXBYTES_BUCKET5)
2384 (xferP->count[5])++;
2385 else if (bytesToXfer <=
2386 AFS_STATS_MAXBYTES_BUCKET6)
2387 (xferP->count[6])++;
2388 else if (bytesToXfer <=
2389 AFS_STATS_MAXBYTES_BUCKET7)
2390 (xferP->count[7])++;
2392 (xferP->count[8])++;
2394 afs_stats_GetDiff(elapsedTime, xferStartTime,
2396 afs_stats_AddTo((xferP->sumTime), elapsedTime);
2397 afs_stats_SquareAddTo((xferP->sqrTime),
2399 if (afs_stats_TimeLessThan
2400 (elapsedTime, (xferP->minTime))) {
2401 afs_stats_TimeAssign((xferP->minTime),
2404 if (afs_stats_TimeGreaterThan
2405 (elapsedTime, (xferP->maxTime))) {
2406 afs_stats_TimeAssign((xferP->maxTime),
2412 afs_CacheFetchProc(tcall, file, Position, tdc,
2414 #endif /* AFS_NOSTATS */
2419 EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2427 code1 = rx_EndCall(tcall, code);
2436 /* callback could have been broken (or expired) in a race here,
2437 * but we return the data anyway. It's as good as we knew about
2438 * when we started. */
2440 * validPos is updated by CacheFetchProc, and can only be
2441 * modifed under a dcache write lock, which we've blocked out
2443 size = tdc->validPos - Position; /* actual segment size */
2446 afs_CFileTruncate(file, size); /* prune it */
2448 if (!setLocks || slowPass) {
2449 ObtainWriteLock(&afs_xcbhash, 453);
2450 afs_DequeueCallback(avc);
2451 avc->f.states &= ~(CStatd | CUnique);
2452 avc->callback = NULL;
2453 ReleaseWriteLock(&afs_xcbhash);
2454 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2455 osi_dnlc_purgedp(avc);
2457 /* Something lost. Forget about performance, and go
2458 * back with a vcache write lock.
2460 afs_CFileTruncate(file, 0);
2461 afs_AdjustSize(tdc, 0);
2462 afs_CFileClose(file);
2463 osi_FreeLargeSpace(tsmall);
2465 ReleaseWriteLock(&tdc->lock);
2468 ReleaseReadLock(&avc->lock);
2470 goto RetryGetDCache;
2474 } while (afs_Analyze
2475 (tc, code, &avc->f.fid, areq,
2476 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2480 * avc->lock(R) if setLocks && !slowPass
2481 * avc->lock(W) if !setLocks || slowPass
2487 * In the case of replicated access, jot down info on the number of
2488 * attempts it took before we got through or gave up.
2491 if (numFetchLoops <= 1)
2492 (accP->refFirstReplicaOK)++;
2493 if (numFetchLoops > accP->maxReplicasPerRef)
2494 accP->maxReplicasPerRef = numFetchLoops;
2496 #endif /* AFS_NOSTATS */
2498 tdc->dflags &= ~DFFetching;
2499 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2500 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2501 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2502 tdc, ICL_TYPE_INT32, tdc->dflags);
2503 if (avc->execsOrWriters == 0)
2504 tdc->f.states &= ~DWriting;
2506 /* now, if code != 0, we have an error and should punt.
2507 * note that we have the vcache write lock, either because
2508 * !setLocks or slowPass.
2511 afs_CFileTruncate(file, 0);
2512 afs_AdjustSize(tdc, 0);
2513 afs_CFileClose(file);
2514 ZapDCE(tdc); /* sets DFEntryMod */
2515 if (vType(avc) == VDIR) {
2518 tdc->f.states &= ~(DRO|DBackup|DRW);
2519 afs_DCMoveBucket(tdc, 0, 0);
2520 ReleaseWriteLock(&tdc->lock);
2522 if (!afs_IsDynroot(avc)) {
2523 ObtainWriteLock(&afs_xcbhash, 454);
2524 afs_DequeueCallback(avc);
2525 avc->f.states &= ~(CStatd | CUnique);
2526 ReleaseWriteLock(&afs_xcbhash);
2527 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2528 osi_dnlc_purgedp(avc);
2531 * avc->lock(W); assert(!setLocks || slowPass)
2533 osi_Assert(!setLocks || slowPass);
2539 /* otherwise we copy in the just-fetched info */
2540 afs_CFileClose(file);
2541 afs_AdjustSize(tdc, size); /* new size */
2543 * Copy appropriate fields into vcache. Status is
2544 * copied later where we selectively acquire the
2545 * vcache write lock.
2548 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2550 setVcacheStatus = 1;
2551 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2552 tsmall->OutStatus.DataVersion);
2553 tdc->dflags |= DFEntryMod;
2554 afs_indexFlags[tdc->index] |= IFEverUsed;
2555 ConvertWToSLock(&tdc->lock);
2556 } /*Data version numbers don't match */
2559 * Data version numbers match.
2561 afs_stats_cmperf.dcacheHits++;
2562 } /*Data version numbers match */
2564 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2568 * avc->lock(R) if setLocks && !slowPass
2569 * avc->lock(W) if !setLocks || slowPass
2570 * tdc->lock(S) if tdc
2574 * See if this was a reference to a file in the local cell.
2576 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2577 afs_stats_cmperf.dlocalAccesses++;
2579 afs_stats_cmperf.dremoteAccesses++;
2581 /* Fix up LRU info */
2584 MObtainWriteLock(&afs_xdcache, 602);
2585 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2586 hadd32(afs_indexCounter, 1);
2587 MReleaseWriteLock(&afs_xdcache);
2589 /* return the data */
2590 if (vType(avc) == VDIR)
2593 *aoffset = AFS_CHUNKOFFSET(abyte);
2594 *alen = (tdc->f.chunkBytes - *aoffset);
2595 ReleaseSharedLock(&tdc->lock);
2600 * avc->lock(R) if setLocks && !slowPass
2601 * avc->lock(W) if !setLocks || slowPass
2604 /* Fix up the callback and status values in the vcache */
2606 if (setLocks && !slowPass) {
2609 * This is our dirty little secret to parallel fetches.
2610 * We don't write-lock the vcache while doing the fetch,
2611 * but potentially we'll need to update the vcache after
2612 * the fetch is done.
2614 * Drop the read lock and try to re-obtain the write
2615 * lock. If the vcache still has the same DV, it's
2616 * ok to go ahead and install the new data.
2618 afs_hyper_t currentDV, statusDV;
2620 hset(currentDV, avc->f.m.DataVersion);
2622 if (setNewCallback && avc->callback != newCallback)
2626 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2627 tsmall->OutStatus.DataVersion);
2629 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2631 if (setVcacheStatus && !hsame(currentDV, statusDV))
2635 ReleaseReadLock(&avc->lock);
2637 if (doVcacheUpdate) {
2638 ObtainWriteLock(&avc->lock, 615);
2639 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2640 /* We lose. Someone will beat us to it. */
2642 ReleaseWriteLock(&avc->lock);
2647 /* With slow pass, we've already done all the updates */
2649 ReleaseWriteLock(&avc->lock);
2652 /* Check if we need to perform any last-minute fixes with a write-lock */
2653 if (!setLocks || doVcacheUpdate) {
2655 avc->callback = newCallback;
2656 if (tsmall && setVcacheStatus)
2657 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2659 ReleaseWriteLock(&avc->lock);
2663 osi_FreeLargeSpace(tsmall);
2666 } /*afs_GetDCache */
2670 * afs_WriteThroughDSlots
2673 * Sweep through the dcache slots and write out any modified
2674 * in-memory data back on to our caching store.
2680 * The afs_xdcache is write-locked through this whole affair.
2683 afs_WriteThroughDSlots(void)
2685 register struct dcache *tdc;
2686 register afs_int32 i, touchedit = 0;
2688 struct afs_q DirtyQ, *tq;
2690 AFS_STATCNT(afs_WriteThroughDSlots);
2693 * Because of lock ordering, we can't grab dcache locks while
2694 * holding afs_xdcache. So we enter xdcache, get a reference
2695 * for every dcache entry, and exit xdcache.
2697 MObtainWriteLock(&afs_xdcache, 283);
2699 for (i = 0; i < afs_cacheFiles; i++) {
2700 tdc = afs_indexTable[i];
2702 /* Grab tlock in case the existing refcount isn't zero */
2703 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2704 ObtainWriteLock(&tdc->tlock, 623);
2706 ReleaseWriteLock(&tdc->tlock);
2708 QAdd(&DirtyQ, &tdc->dirty);
2711 MReleaseWriteLock(&afs_xdcache);
2714 * Now, for each dcache entry we found, check if it's dirty.
2715 * If so, get write-lock, get afs_xdcache, which protects
2716 * afs_cacheInodep, and flush it. Don't forget to put back
2720 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2722 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2724 if (tdc->dflags & DFEntryMod) {
2727 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2729 /* Now that we have the write lock, double-check */
2730 if (wrLock && (tdc->dflags & DFEntryMod)) {
2731 tdc->dflags &= ~DFEntryMod;
2732 MObtainWriteLock(&afs_xdcache, 620);
2733 afs_WriteDCache(tdc, 1);
2734 MReleaseWriteLock(&afs_xdcache);
2738 ReleaseWriteLock(&tdc->lock);
2744 MObtainWriteLock(&afs_xdcache, 617);
2745 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2746 /* Touch the file to make sure that the mtime on the file is kept
2747 * up-to-date to avoid losing cached files on cold starts because
2748 * their mtime seems old...
2750 struct afs_fheader theader;
2752 theader.magic = AFS_FHMAGIC;
2753 theader.firstCSize = AFS_FIRSTCSIZE;
2754 theader.otherCSize = AFS_OTHERCSIZE;
2755 theader.version = AFS_CI_VERSION;
2756 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2758 MReleaseWriteLock(&afs_xdcache);
2765 * Return a pointer to an freshly initialized dcache entry using
2766 * a memory-based cache. The tlock will be read-locked.
2769 * aslot : Dcache slot to look at.
2770 * tmpdc : Ptr to dcache entry.
2773 * Must be called with afs_xdcache write-locked.
2777 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2779 register struct dcache *tdc;
2782 AFS_STATCNT(afs_MemGetDSlot);
2783 if (CheckLock(&afs_xdcache) != -1)
2784 osi_Panic("getdslot nolock");
2785 if (aslot < 0 || aslot >= afs_cacheFiles)
2786 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2787 tdc = afs_indexTable[aslot];
2789 QRemove(&tdc->lruq); /* move to queue head */
2790 QAdd(&afs_DLRU, &tdc->lruq);
2791 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2792 ObtainWriteLock(&tdc->tlock, 624);
2794 ConvertWToRLock(&tdc->tlock);
2797 if (tmpdc == NULL) {
2798 if (!afs_freeDSList)
2799 afs_GetDownDSlot(4);
2800 if (!afs_freeDSList) {
2801 /* none free, making one is better than a panic */
2802 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2803 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2804 #ifdef KERNEL_HAVE_PIN
2805 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2808 tdc = afs_freeDSList;
2809 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2812 tdc->dflags = 0; /* up-to-date, not in free q */
2814 QAdd(&afs_DLRU, &tdc->lruq);
2815 if (tdc->lruq.prev == &tdc->lruq)
2816 osi_Panic("lruq 3");
2822 /* initialize entry */
2823 tdc->f.fid.Cell = 0;
2824 tdc->f.fid.Fid.Volume = 0;
2826 hones(tdc->f.versionNo);
2827 tdc->f.inode.mem = aslot;
2828 tdc->dflags |= DFEntryMod;
2831 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2834 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2835 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2836 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2839 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2840 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2841 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2842 ObtainReadLock(&tdc->tlock);
2845 afs_indexTable[aslot] = tdc;
2848 } /*afs_MemGetDSlot */
2850 unsigned int last_error = 0, lasterrtime = 0;
2856 * Return a pointer to an freshly initialized dcache entry using
2857 * a UFS-based disk cache. The dcache tlock will be read-locked.
2860 * aslot : Dcache slot to look at.
2861 * tmpdc : Ptr to dcache entry.
2864 * afs_xdcache lock write-locked.
2867 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2869 register afs_int32 code;
2870 register struct dcache *tdc;
2874 AFS_STATCNT(afs_UFSGetDSlot);
2875 if (CheckLock(&afs_xdcache) != -1)
2876 osi_Panic("getdslot nolock");
2877 if (aslot < 0 || aslot >= afs_cacheFiles)
2878 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2879 tdc = afs_indexTable[aslot];
2881 QRemove(&tdc->lruq); /* move to queue head */
2882 QAdd(&afs_DLRU, &tdc->lruq);
2883 /* Grab tlock in case refCount != 0 */
2884 ObtainWriteLock(&tdc->tlock, 625);
2886 ConvertWToRLock(&tdc->tlock);
2889 /* otherwise we should read it in from the cache file */
2891 * If we weren't passed an in-memory region to place the file info,
2892 * we have to allocate one.
2894 if (tmpdc == NULL) {
2895 if (!afs_freeDSList)
2896 afs_GetDownDSlot(4);
2897 if (!afs_freeDSList) {
2898 /* none free, making one is better than a panic */
2899 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2900 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2901 #ifdef KERNEL_HAVE_PIN
2902 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2905 tdc = afs_freeDSList;
2906 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2909 tdc->dflags = 0; /* up-to-date, not in free q */
2911 QAdd(&afs_DLRU, &tdc->lruq);
2912 if (tdc->lruq.prev == &tdc->lruq)
2913 osi_Panic("lruq 3");
2920 * Seek to the aslot'th entry and read it in.
2923 afs_osi_Read(afs_cacheInodep,
2924 sizeof(struct fcache) * aslot +
2925 sizeof(struct afs_fheader), (char *)(&tdc->f),
2926 sizeof(struct fcache));
2928 if (code != sizeof(struct fcache))
2930 if (!afs_CellNumValid(tdc->f.fid.Cell))
2934 tdc->f.fid.Cell = 0;
2935 tdc->f.fid.Fid.Volume = 0;
2937 hones(tdc->f.versionNo);
2938 tdc->dflags |= DFEntryMod;
2939 #if defined(KERNEL_HAVE_UERROR)
2940 last_error = getuerror();
2942 lasterrtime = osi_Time();
2943 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2944 tdc->f.states &= ~(DRO|DBackup|DRW);
2945 afs_DCMoveBucket(tdc, 0, 0);
2948 if (tdc->f.states & DRO) {
2949 afs_DCMoveBucket(tdc, 0, 2);
2950 } else if (tdc->f.states & DBackup) {
2951 afs_DCMoveBucket(tdc, 0, 1);
2953 afs_DCMoveBucket(tdc, 0, 1);
2959 if (tdc->f.chunk >= 0)
2960 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2965 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2966 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2967 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2970 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2971 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2972 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2973 ObtainReadLock(&tdc->tlock);
2976 * If we didn't read into a temporary dcache region, update the
2977 * slot pointer table.
2980 afs_indexTable[aslot] = tdc;
2983 } /*afs_UFSGetDSlot */
2988 * Write a particular dcache entry back to its home in the
2991 * \param adc Pointer to the dcache entry to write.
2992 * \param atime If true, set the modtime on the file to the current time.
2994 * \note Environment:
2995 * Must be called with the afs_xdcache lock at least read-locked,
2996 * and dcache entry at least read-locked.
2997 * The reference count is not changed.
3001 afs_WriteDCache(register struct dcache *adc, int atime)
3003 register afs_int32 code;
3005 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3007 AFS_STATCNT(afs_WriteDCache);
3008 osi_Assert(WriteLocked(&afs_xdcache));
3010 adc->f.modTime = osi_Time();
3012 * Seek to the right dcache slot and write the in-memory image out to disk.
3014 afs_cellname_write();
3016 afs_osi_Write(afs_cacheInodep,
3017 sizeof(struct fcache) * adc->index +
3018 sizeof(struct afs_fheader), (char *)(&adc->f),
3019 sizeof(struct fcache));
3020 if (code != sizeof(struct fcache))
3028 * Wake up users of a particular file waiting for stores to take
3031 * \param avc Ptr to related vcache entry.
3033 * \note Environment:
3034 * Nothing interesting.
3037 afs_wakeup(register struct vcache *avc)
3040 register struct brequest *tb;
3042 AFS_STATCNT(afs_wakeup);
3043 for (i = 0; i < NBRS; i++, tb++) {
3044 /* if request is valid and for this file, we've found it */
3045 if (tb->refCount > 0 && avc == tb->vc) {
3048 * If CSafeStore is on, then we don't awaken the guy
3049 * waiting for the store until the whole store has finished.
3050 * Otherwise, we do it now. Note that if CSafeStore is on,
3051 * the BStore routine actually wakes up the user, instead
3053 * I think this is redundant now because this sort of thing
3054 * is already being handled by the higher-level code.
3056 if ((avc->f.states & CSafeStore) == 0) {
3058 tb->flags |= BUVALID;
3059 if (tb->flags & BUWAIT) {
3060 tb->flags &= ~BUWAIT;
3072 * Given a file name and inode, set up that file to be an
3073 * active member in the AFS cache. This also involves checking
3074 * the usability of its data.
3076 * \param afile Name of the cache file to initialize.
3077 * \param ainode Inode of the file.
3079 * \note Environment:
3080 * This function is called only during initialization.
3083 afs_InitCacheFile(char *afile, ino_t ainode)
3085 register afs_int32 code;
3088 struct osi_file *tfile;
3089 struct osi_stat tstat;
3090 register struct dcache *tdc;
3092 AFS_STATCNT(afs_InitCacheFile);
3093 index = afs_stats_cmperf.cacheNumEntries;
3094 if (index >= afs_cacheFiles)
3097 MObtainWriteLock(&afs_xdcache, 282);
3098 tdc = afs_GetDSlot(index, NULL);
3099 ReleaseReadLock(&tdc->tlock);
3100 MReleaseWriteLock(&afs_xdcache);
3102 ObtainWriteLock(&tdc->lock, 621);
3103 MObtainWriteLock(&afs_xdcache, 622);
3105 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
3107 ReleaseWriteLock(&afs_xdcache);
3108 ReleaseWriteLock(&tdc->lock);
3113 /* Add any other 'complex' inode types here ... */
3114 #if defined(UKERNEL) || !defined(LINUX_USE_FH)
3115 tdc->f.inode.ufs = ainode;
3117 osi_Panic("Can't init cache with inode numbers when complex inodes are "
3122 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3124 tfile = osi_UFSOpen(&tdc->f.inode);
3125 code = afs_osi_Stat(tfile, &tstat);
3127 osi_Panic("initcachefile stat");
3130 * If file size doesn't match the cache info file, it's probably bad.
3132 if (tdc->f.chunkBytes != tstat.size)
3134 tdc->f.chunkBytes = 0;
3137 * If file changed within T (120?) seconds of cache info file, it's
3138 * probably bad. In addition, if slot changed within last T seconds,
3139 * the cache info file may be incorrectly identified, and so slot
3142 if (cacheInfoModTime < tstat.mtime + 120)
3144 if (cacheInfoModTime < tdc->f.modTime + 120)
3146 /* In case write through is behind, make sure cache items entry is
3147 * at least as new as the chunk.
3149 if (tdc->f.modTime < tstat.mtime)
3152 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3153 if (tstat.size != 0)
3154 osi_UFSTruncate(tfile, 0);
3155 tdc->f.states &= ~(DRO|DBackup|DRW);
3156 afs_DCMoveBucket(tdc, 0, 0);
3157 /* put entry in free cache slot list */
3158 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3159 afs_freeDCList = index;
3161 afs_indexFlags[index] |= IFFree;
3162 afs_indexUnique[index] = 0;
3165 * We must put this entry in the appropriate hash tables.
3166 * Note that i is still set from the above DCHash call
3168 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3169 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3170 afs_dchashTbl[code] = tdc->index;
3171 code = DVHash(&tdc->f.fid);
3172 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3173 afs_dvhashTbl[code] = tdc->index;
3174 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3176 /* has nontrivial amt of data */
3177 afs_indexFlags[index] |= IFEverUsed;
3178 afs_stats_cmperf.cacheFilesReused++;
3180 * Initialize index times to file's mod times; init indexCounter
3183 hset32(afs_indexTimes[index], tstat.atime);
3184 if (hgetlo(afs_indexCounter) < tstat.atime) {
3185 hset32(afs_indexCounter, tstat.atime);
3187 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3188 } /*File is not bad */
3190 osi_UFSClose(tfile);
3191 tdc->f.states &= ~DWriting;
3192 tdc->dflags &= ~DFEntryMod;
3193 /* don't set f.modTime; we're just cleaning up */
3194 afs_WriteDCache(tdc, 0);
3195 ReleaseWriteLock(&afs_xdcache);
3196 ReleaseWriteLock(&tdc->lock);
3198 afs_stats_cmperf.cacheNumEntries++;
3203 /*Max # of struct dcache's resident at any time*/
3205 * If 'dchint' is enabled then in-memory dcache min is increased because of
3211 * Initialize dcache related variables.
3221 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3223 register struct dcache *tdp;
3227 afs_freeDCList = NULLIDX;
3228 afs_discardDCList = NULLIDX;
3229 afs_freeDCCount = 0;
3230 afs_freeDSList = NULL;
3231 hzero(afs_indexCounter);
3233 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3239 if (achunk < 0 || achunk > 30)
3240 achunk = 13; /* Use default */
3241 AFS_SETCHUNKSIZE(achunk);
3247 if (aflags & AFSCALL_INIT_MEMCACHE) {
3249 * Use a memory cache instead of a disk cache
3251 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3252 afs_cacheType = &afs_MemCacheOps;
3253 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3254 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3255 /* ablocks is reported in 1K blocks */
3256 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3258 printf("afsd: memory cache too large for available memory.\n");
3259 printf("afsd: AFS files cannot be accessed.\n\n");
3261 afiles = ablocks = 0;
3263 printf("Memory cache: Allocating %d dcache entries...",
3266 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3267 afs_cacheType = &afs_UfsCacheOps;
3270 if (aDentries > 512)
3271 afs_dhashsize = 2048;
3272 /* initialize hash tables */
3274 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3276 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3277 for (i = 0; i < afs_dhashsize; i++) {
3278 afs_dvhashTbl[i] = NULLIDX;
3279 afs_dchashTbl[i] = NULLIDX;
3281 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3282 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3283 for (i = 0; i < afiles; i++) {
3284 afs_dvnextTbl[i] = NULLIDX;
3285 afs_dcnextTbl[i] = NULLIDX;
3288 /* Allocate and zero the pointer array to the dcache entries */
3289 afs_indexTable = (struct dcache **)
3290 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3291 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3293 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3294 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3296 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3297 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3298 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3299 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3301 /* Allocate and thread the struct dcache entries themselves */
3302 tdp = afs_Initial_freeDSList =
3303 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3304 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3305 #ifdef KERNEL_HAVE_PIN
3306 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3307 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3308 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3309 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3310 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3311 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3312 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3313 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3314 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3317 afs_freeDSList = &tdp[0];
3318 for (i = 0; i < aDentries - 1; i++) {
3319 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3320 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3321 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3322 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3324 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3325 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3326 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3327 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3329 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3330 afs_cacheBlocks = ablocks;
3331 afs_ComputeCacheParms(); /* compute parms based on cache size */
3333 afs_dcentries = aDentries;
3335 afs_stats_cmperf.cacheBucket0_Discarded =
3336 afs_stats_cmperf.cacheBucket1_Discarded =
3337 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3343 * Shuts down the cache.
3347 shutdown_dcache(void)
3351 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3352 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3353 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3354 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3355 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3356 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3357 afs_osi_Free(afs_Initial_freeDSList,
3358 afs_dcentries * sizeof(struct dcache));
3359 #ifdef KERNEL_HAVE_PIN
3360 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3361 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3362 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3363 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3364 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3365 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3366 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3370 for (i = 0; i < afs_dhashsize; i++) {
3371 afs_dvhashTbl[i] = NULLIDX;
3372 afs_dchashTbl[i] = NULLIDX;
3375 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3376 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3378 afs_blocksUsed = afs_dcentries = 0;
3379 afs_stats_cmperf.cacheBucket0_Discarded =
3380 afs_stats_cmperf.cacheBucket1_Discarded =
3381 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3382 hzero(afs_indexCounter);
3384 afs_freeDCCount = 0;
3385 afs_freeDCList = NULLIDX;
3386 afs_discardDCList = NULLIDX;
3387 afs_freeDSList = afs_Initial_freeDSList = 0;
3389 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3395 * Get a dcache ready for writing, respecting the current cache size limits
3397 * len is required because afs_GetDCache with flag == 4 expects the length
3398 * field to be filled. It decides from this whether it's necessary to fetch
3399 * data into the chunk before writing or not (when the whole chunk is
3402 * \param avc The vcache to fetch a dcache for
3403 * \param filePos The start of the section to be written
3404 * \param len The length of the section to be written
3408 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3409 * must be released and afs_PutDCache() called to free dcache.
3412 * \note avc->lock must be held on entry. Function may release and reobtain
3413 * avc->lock and GLOCK.
3417 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3418 afs_size_t len, struct vrequest *areq,
3420 struct dcache *tdc = NULL;
3423 /* read the cached info */
3425 tdc = afs_FindDCache(avc, filePos);
3427 ObtainWriteLock(&tdc->lock, 657);
3428 } else if (afs_blocksUsed >
3429 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3430 tdc = afs_FindDCache(avc, filePos);
3432 ObtainWriteLock(&tdc->lock, 658);
3433 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3434 || (tdc->dflags & DFFetching)) {
3435 ReleaseWriteLock(&tdc->lock);
3441 afs_MaybeWakeupTruncateDaemon();
3442 while (afs_blocksUsed >
3443 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3444 ReleaseWriteLock(&avc->lock);
3445 if (afs_blocksUsed - afs_blocksDiscarded >
3446 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3447 afs_WaitForCacheDrain = 1;
3448 afs_osi_Sleep(&afs_WaitForCacheDrain);
3450 afs_MaybeFreeDiscardedDCache();
3451 afs_MaybeWakeupTruncateDaemon();
3452 ObtainWriteLock(&avc->lock, 509);
3454 avc->f.states |= CDirty;
3455 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3457 ObtainWriteLock(&tdc->lock, 659);
3460 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3462 ObtainWriteLock(&tdc->lock, 660);
3465 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3466 afs_stats_cmperf.cacheCurrDirtyChunks++;
3467 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3469 if (!(tdc->f.states & DWriting)) {
3470 /* don't mark entry as mod if we don't have to */
3471 tdc->f.states |= DWriting;
3472 tdc->dflags |= DFEntryMod;
3478 #if defined(AFS_DISCON_ENV)
3481 * Make a shadow copy of a dir's dcache. It's used for disconnected
3482 * operations like remove/create/rename to keep the original directory data.
3483 * On reconnection, we can diff the original data with the server and get the
3484 * server changes and with the local data to get the local changes.
3486 * \param avc The dir vnode.
3487 * \param adc The dir dcache.
3489 * \return 0 for success.
3491 * \note The vcache entry must be write locked.
3492 * \note The dcache entry must be read locked.
3494 int afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3496 int i, code, ret_code = 0, written, trans_size;
3497 struct dcache *new_dc = NULL;
3498 struct osi_file *tfile_src, *tfile_dst;
3499 struct VenusFid shadow_fid;
3502 /* Is this a dir? */
3503 if (vType(avc) != VDIR)
3506 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3509 /* Generate a fid for the shadow dir. */
3510 shadow_fid.Cell = avc->f.fid.Cell;
3511 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3512 afs_GenShadowFid(&shadow_fid);
3514 ObtainWriteLock(&afs_xdcache, 716);
3516 /* Get a fresh dcache. */
3517 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3519 ObtainReadLock(&adc->mflock);
3521 /* Set up the new fid. */
3522 /* Copy interesting data from original dir dcache. */
3523 new_dc->mflags = adc->mflags;
3524 new_dc->dflags = adc->dflags;
3525 new_dc->f.modTime = adc->f.modTime;
3526 new_dc->f.versionNo = adc->f.versionNo;
3527 new_dc->f.states = adc->f.states;
3528 new_dc->f.chunk= adc->f.chunk;
3529 new_dc->f.chunkBytes = adc->f.chunkBytes;
3531 ReleaseReadLock(&adc->mflock);
3533 /* Now add to the two hash chains */
3534 i = DCHash(&shadow_fid, 0);
3535 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3536 afs_dchashTbl[i] = new_dc->index;
3538 i = DVHash(&shadow_fid);
3539 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3540 afs_dvhashTbl[i] = new_dc->index;
3542 ReleaseWriteLock(&afs_xdcache);
3544 /* Alloc a 4k block. */
3545 data = (char *) afs_osi_Alloc(4096);
3547 printf("afs_MakeShadowDir: could not alloc data\n");
3552 /* Open the files. */
3553 tfile_src = afs_CFileOpen(&adc->f.inode);
3554 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3556 /* And now copy dir dcache data into this dcache,
3560 while (written < adc->f.chunkBytes) {
3561 trans_size = adc->f.chunkBytes - written;
3562 if (trans_size > 4096)
3565 /* Read a chunk from the dcache. */
3566 code = afs_CFileRead(tfile_src, written, data, trans_size);
3567 if (code < trans_size) {
3572 /* Write it to the new dcache. */
3573 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3574 if (code < trans_size) {
3579 written+=trans_size;
3582 afs_CFileClose(tfile_dst);
3583 afs_CFileClose(tfile_src);
3585 afs_osi_Free(data, 4096);
3587 ReleaseWriteLock(&new_dc->lock);
3588 afs_PutDCache(new_dc);
3591 ObtainWriteLock(&afs_xvcache, 763);
3592 ObtainWriteLock(&afs_disconDirtyLock, 765);
3593 QAdd(&afs_disconShadow, &avc->shadowq);
3595 ReleaseWriteLock(&afs_disconDirtyLock);
3596 ReleaseWriteLock(&afs_xvcache);
3598 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3599 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3607 * Delete the dcaches of a shadow dir.
3609 * \param avc The vcache containing the shadow fid.
3611 * \note avc must be write locked.
3613 void afs_DeleteShadowDir(struct vcache *avc)
3616 struct VenusFid shadow_fid;
3618 shadow_fid.Cell = avc->f.fid.Cell;
3619 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3620 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3621 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3623 tdc = afs_FindDCacheByFid(&shadow_fid);
3625 afs_HashOutDCache(tdc, 1);
3626 afs_DiscardDCache(tdc);
3629 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3630 ObtainWriteLock(&afs_disconDirtyLock, 708);
3631 QRemove(&avc->shadowq);
3632 ReleaseWriteLock(&afs_disconDirtyLock);
3633 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3637 * Populate a dcache with empty chunks up to a given file size,
3638 * used before extending a file in order to avoid 'holes' which
3639 * we can't access in disconnected mode.
3641 * \param avc The vcache which is being extended (locked)
3642 * \param alen The new length of the file
3645 void afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq) {
3647 afs_size_t len, offset;
3648 afs_int32 start, end;
3650 /* We're doing this to deal with the situation where we extend
3651 * by writing after lseek()ing past the end of the file . If that
3652 * extension skips chunks, then those chunks won't be created, and
3653 * GetDCache will assume that they have to be fetched from the server.
3654 * So, for each chunk between the current file position, and the new
3655 * length we GetDCache for that chunk.
3658 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3661 if (avc->f.m.Length == 0)
3664 start = AFS_CHUNK(avc->f.m.Length)+1;
3666 end = AFS_CHUNK(apos);
3669 len = AFS_CHUNKTOSIZE(start);
3670 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);