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
10 /* Copyright (C) 1994 Cazamar Systems, Inc. */
12 #include <afs/param.h>
23 #include "cm_memmap.h"
26 #define TRACE_BUFFER 1
29 extern void afsi_log(char *pattern, ...);
31 /* This module implements the buffer package used by the local transaction
32 * system (cm). It is initialized by calling cm_Init, which calls buf_Init;
33 * it must be initalized before any of its main routines are called.
35 * Each buffer is hashed into a hash table by file ID and offset, and if its
36 * reference count is zero, it is also in a free list.
38 * There are two locks involved in buffer processing. The global lock
39 * buf_globalLock protects all of the global variables defined in this module,
40 * the reference counts and hash pointers in the actual cm_buf_t structures,
41 * and the LRU queue pointers in the buffer structures.
43 * The mutexes in the buffer structures protect the remaining fields in the
44 * buffers, as well the data itself.
46 * The locking hierarchy here is this:
48 * - resv multiple simul. buffers reservation
49 * - lock buffer I/O flags
50 * - lock buffer's mutex
51 * - lock buf_globalLock
55 /* global debugging log */
56 osi_log_t *buf_logp = NULL;
58 /* Global lock protecting hash tables and free lists */
59 osi_rwlock_t buf_globalLock;
61 /* ptr to head of the free list (most recently used) and the
62 * tail (the guy to remove first). We use osi_Q* functions
63 * to put stuff in buf_freeListp, and maintain the end
67 /* a pointer to a list of all buffers, just so that we can find them
68 * easily for debugging, and for the incr syncer. Locked under
72 /* defaults setup; these variables may be manually assigned into
73 * before calling cm_Init, as a way of changing these defaults.
76 /* callouts for reading and writing data, etc */
77 cm_buf_ops_t *cm_buf_opsp;
80 /* for experimental disk caching support in Win95 client */
81 cm_buf_t *buf_diskFreeListp;
82 cm_buf_t *buf_diskFreeListEndp;
83 cm_buf_t *buf_diskAllp;
84 extern int cm_diskCacheEnabled;
85 #endif /* DISKCACHE95 */
87 /* set this to 1 when we are terminating to prevent access attempts */
88 static int buf_ShutdownFlag = 0;
91 void buf_HoldLockedDbg(cm_buf_t *bp, char *file, long line)
93 void buf_HoldLocked(cm_buf_t *bp)
98 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
99 refCount = InterlockedIncrement(&bp->refCount);
100 #ifdef DEBUG_REFCOUNT
101 osi_Log2(afsd_logp,"buf_HoldLocked bp 0x%p ref %d",bp, refCount);
102 afsi_log("%s:%d buf_HoldLocked bp 0x%p, ref %d", file, line, bp, refCount);
106 /* hold a reference to an already held buffer */
107 #ifdef DEBUG_REFCOUNT
108 void buf_HoldDbg(cm_buf_t *bp, char *file, long line)
110 void buf_Hold(cm_buf_t *bp)
115 lock_ObtainRead(&buf_globalLock);
116 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
117 refCount = InterlockedIncrement(&bp->refCount);
118 #ifdef DEBUG_REFCOUNT
119 osi_Log2(afsd_logp,"buf_Hold bp 0x%p ref %d",bp, refCount);
120 afsi_log("%s:%d buf_Hold bp 0x%p, ref %d", file, line, bp, refCount);
122 lock_ReleaseRead(&buf_globalLock);
125 /* code to drop reference count while holding buf_globalLock */
126 #ifdef DEBUG_REFCOUNT
127 void buf_ReleaseLockedDbg(cm_buf_t *bp, afs_uint32 writeLocked, char *file, long line)
129 void buf_ReleaseLocked(cm_buf_t *bp, afs_uint32 writeLocked)
135 lock_AssertWrite(&buf_globalLock);
137 lock_AssertRead(&buf_globalLock);
139 /* ensure that we're in the LRU queue if our ref count is 0 */
140 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
142 refCount = InterlockedDecrement(&bp->refCount);
143 #ifdef DEBUG_REFCOUNT
144 osi_Log3(afsd_logp,"buf_ReleaseLocked %s bp 0x%p ref %d",writeLocked?"write":"read", bp, refCount);
145 afsi_log("%s:%d buf_ReleaseLocked %s bp 0x%p, ref %d", file, line, writeLocked?"write":"read", bp, refCount);
149 osi_panic("buf refcount 0",__FILE__,__LINE__);;
151 osi_assertx(refCount >= 0, "cm_buf_t refCount == 0");
155 * If we are read locked there could be a race condition
156 * with buf_Find() so we must obtain a write lock and
157 * double check that the refCount is actually zero
158 * before we remove the buffer from the LRU queue.
161 lock_ConvertRToW(&buf_globalLock);
163 if (bp->refCount == 0 &&
164 !(bp->qFlags & CM_BUF_QINLRU)) {
165 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
167 /* watch for transition from empty to one element */
168 if (!cm_data.buf_freeListEndp)
169 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
170 bp->qFlags |= CM_BUF_QINLRU;
174 lock_ConvertWToR(&buf_globalLock);
178 /* release a buffer. Buffer must be referenced, but unlocked. */
179 #ifdef DEBUG_REFCOUNT
180 void buf_ReleaseDbg(cm_buf_t *bp, char *file, long line)
182 void buf_Release(cm_buf_t *bp)
187 /* ensure that we're in the LRU queue if our ref count is 0 */
188 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
190 refCount = InterlockedDecrement(&bp->refCount);
191 #ifdef DEBUG_REFCOUNT
192 osi_Log2(afsd_logp,"buf_Release bp 0x%p ref %d", bp, refCount);
193 afsi_log("%s:%d buf_ReleaseLocked bp 0x%p, ref %d", file, line, bp, refCount);
197 osi_panic("buf refcount 0",__FILE__,__LINE__);;
199 osi_assertx(refCount >= 0, "cm_buf_t refCount == 0");
202 lock_ObtainWrite(&buf_globalLock);
203 if (bp->refCount == 0 &&
204 !(bp->qFlags & CM_BUF_QINLRU)) {
205 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
207 /* watch for transition from empty to one element */
208 if (!cm_data.buf_freeListEndp)
209 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
210 bp->qFlags |= CM_BUF_QINLRU;
212 lock_ReleaseWrite(&buf_globalLock);
217 buf_Sync(int quitOnShutdown)
219 cm_buf_t **bpp, *bp, *prevbp;
220 afs_uint32 wasDirty = 0;
223 /* go through all of the dirty buffers */
224 lock_ObtainRead(&buf_globalLock);
225 for (bpp = &cm_data.buf_dirtyListp, prevbp = NULL; bp = *bpp; ) {
226 if (quitOnShutdown && buf_ShutdownFlag)
229 lock_ReleaseRead(&buf_globalLock);
230 /* all dirty buffers are held when they are added to the
231 * dirty list. No need for an additional hold.
233 lock_ObtainMutex(&bp->mx);
235 if (bp->flags & CM_BUF_DIRTY && !(bp->qFlags & CM_BUF_QREDIR)) {
236 /* start cleaning the buffer; don't touch log pages since
237 * the log code counts on knowing exactly who is writing
238 * a log page at any given instant.
240 * only attempt to write the buffer if the volume might
246 volp = cm_GetVolumeByFID(&bp->fid);
247 switch (cm_GetVolumeStatus(volp, bp->fid.volume)) {
251 req.flags |= CM_REQ_NORETRY;
252 buf_CleanAsyncLocked(NULL, bp, &req, 0, &dirty);
258 /* the buffer may or may not have been dirty
259 * and if dirty may or may not have been cleaned
260 * successfully. check the dirty flag again.
262 if (!(bp->flags & CM_BUF_DIRTY)) {
263 /* remove the buffer from the dirty list */
264 lock_ObtainWrite(&buf_globalLock);
265 #ifdef DEBUG_REFCOUNT
266 if (bp->dirtyp == NULL && bp != cm_data.buf_dirtyListEndp) {
267 osi_Log1(afsd_logp,"buf_IncrSyncer bp 0x%p list corruption",bp);
268 afsi_log("buf_IncrSyncer bp 0x%p list corruption", bp);
273 bp->qFlags &= ~CM_BUF_QINDL;
274 if (cm_data.buf_dirtyListp == NULL)
275 cm_data.buf_dirtyListEndp = NULL;
276 else if (cm_data.buf_dirtyListEndp == bp)
277 cm_data.buf_dirtyListEndp = prevbp;
278 buf_ReleaseLocked(bp, TRUE);
279 lock_ConvertWToR(&buf_globalLock);
281 if (buf_ShutdownFlag) {
284 char volstr[VL_MAXNAMELEN+12]="";
287 volp = cm_GetVolumeByFID(&bp->fid);
290 if (bp->fid.volume == volp->vol[RWVOL].ID)
292 else if (bp->fid.volume == volp->vol[ROVOL].ID)
294 else if (bp->fid.volume == volp->vol[BACKVOL].ID)
298 snprintf(volstr, sizeof(volstr), "%s%s", volp->namep, ext);
300 cellp = cm_FindCellByID(bp->fid.cell, CM_FLAG_NOPROBE);
301 snprintf(volstr, sizeof(volstr), "%u", bp->fid.volume);
304 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_DIRTY_BUFFER_AT_SHUTDOWN,
305 cellp->name, volstr, bp->fid.vnode, bp->fid.unique,
306 bp->offset.QuadPart+bp->dirty_offset, bp->dirty_length);
309 /* advance the pointer so we don't loop forever */
310 lock_ObtainRead(&buf_globalLock);
314 lock_ReleaseMutex(&bp->mx);
315 } /* for loop over a bunch of buffers */
316 lock_ReleaseRead(&buf_globalLock);
321 /* incremental sync daemon. Writes all dirty buffers every 5000 ms */
322 void buf_IncrSyncer(long parm)
327 while (buf_ShutdownFlag == 0) {
330 i = SleepEx(5000, 1);
337 wasDirty = buf_Sync(1);
338 } /* whole daemon's while loop */
342 buf_ValidateBuffers(void)
344 cm_buf_t * bp, *bpf, *bpa, *bpb;
345 afs_uint64 countb = 0, countf = 0, counta = 0;
347 if (cm_data.buf_freeListp == NULL && cm_data.buf_freeListEndp != NULL ||
348 cm_data.buf_freeListp != NULL && cm_data.buf_freeListEndp == NULL) {
349 afsi_log("cm_ValidateBuffers failure: inconsistent free list pointers");
350 fprintf(stderr, "cm_ValidateBuffers failure: inconsistent free list pointers\n");
354 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
355 if (bp->magic != CM_BUF_MAGIC) {
356 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
357 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
363 if (countb > cm_data.buf_nbuffers) {
364 afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
365 fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
370 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
371 if (bp->magic != CM_BUF_MAGIC) {
372 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
373 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
379 if (countf > cm_data.buf_nbuffers) {
380 afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
381 fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
386 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
387 if (bp->magic != CM_BUF_MAGIC) {
388 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
389 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
395 if (counta > cm_data.buf_nbuffers) {
396 afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
397 fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
402 if (countb != countf) {
403 afsi_log("cm_ValidateBuffers failure: countb != countf");
404 fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
408 if (counta != cm_data.buf_nbuffers) {
409 afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
410 fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
417 void buf_Shutdown(void)
419 /* disable the buf_IncrSyncer() threads */
420 buf_ShutdownFlag = 1;
422 /* then force all dirty buffers to the file servers */
426 /* initialize the buffer package; called with no locks
427 * held during the initialization phase.
429 long buf_Init(int newFile, cm_buf_ops_t *opsp, afs_uint64 nbuffers)
431 static osi_once_t once;
440 cm_data.buf_nbuffers = nbuffers;
442 /* Have to be able to reserve a whole chunk */
443 if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
444 return CM_ERROR_TOOFEWBUFS;
447 /* recall for callouts */
450 if (osi_Once(&once)) {
451 /* initialize global locks */
452 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock", LOCK_HIERARCHY_BUF_GLOBAL);
455 /* remember this for those who want to reset it */
456 cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
458 /* lower hash size to a prime number */
459 cm_data.buf_hashSize = osi_PrimeLessThan((afs_uint32)(cm_data.buf_nbuffers/7 + 1));
461 /* create hash table */
462 memset((void *)cm_data.buf_scacheHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
464 /* another hash table */
465 memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
467 /* create buffer headers and put in free list */
468 bp = cm_data.bufHeaderBaseAddress;
469 data = cm_data.bufDataBaseAddress;
470 cm_data.buf_allp = NULL;
472 for (i=0; i<cm_data.buf_nbuffers; i++) {
473 osi_assertx(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress,
474 "invalid cm_buf_t address");
475 osi_assertx(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData,
476 "invalid cm_buf_t data address");
478 /* allocate and zero some storage */
479 memset(bp, 0, sizeof(cm_buf_t));
480 bp->magic = CM_BUF_MAGIC;
481 /* thread on list of all buffers */
482 bp->allp = cm_data.buf_allp;
483 cm_data.buf_allp = bp;
485 osi_QAdd((osi_queue_t **)&cm_data.buf_freeListp, &bp->q);
486 bp->qFlags |= CM_BUF_QINLRU;
487 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
489 /* grab appropriate number of bytes from aligned zone */
492 /* setup last buffer pointer */
494 cm_data.buf_freeListEndp = bp;
498 data += cm_data.buf_blockSize;
501 /* none reserved at first */
502 cm_data.buf_reservedBufs = 0;
504 /* just for safety's sake */
505 cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
507 bp = cm_data.bufHeaderBaseAddress;
508 data = cm_data.bufDataBaseAddress;
510 for (i=0; i<cm_data.buf_nbuffers; i++) {
511 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
514 bp->waitRequests = 0;
515 bp->flags &= ~CM_BUF_WAITING;
521 buf_ValidateBufQueues();
525 /* init the buffer trace log */
526 buf_logp = osi_LogCreate("buffer", 1000);
527 osi_LogEnable(buf_logp);
532 /* and create the incr-syncer */
533 phandle = thrd_Create(0, 0,
534 (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
537 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
538 CloseHandle(phandle);
542 buf_ValidateBufQueues();
547 /* add nbuffers to the buffer pool, if possible.
548 * Called with no locks held.
550 long buf_AddBuffers(afs_uint64 nbuffers)
552 /* The size of a virtual cache cannot be changed after it has
553 * been created. Subsequent calls to MapViewofFile() with
554 * an existing mapping object name would not allow the
555 * object to be resized. Return failure immediately.
557 * A similar problem now occurs with the persistent cache
558 * given that the memory mapped file now contains a complex
561 afsi_log("request to add %d buffers to the existing cache of size %d denied",
562 nbuffers, cm_data.buf_nbuffers);
564 return CM_ERROR_INVAL;
567 /* interface to set the number of buffers to an exact figure.
568 * Called with no locks held.
570 long buf_SetNBuffers(afs_uint64 nbuffers)
573 return CM_ERROR_INVAL;
574 if (nbuffers == cm_data.buf_nbuffers)
576 else if (nbuffers > cm_data.buf_nbuffers)
577 return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
579 return CM_ERROR_INVAL;
582 /* wait for reading or writing to clear; called with write-locked
583 * buffer and unlocked scp and returns with locked buffer.
585 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
590 osi_assertx(scp->magic == CM_SCACHE_MAGIC, "invalid cm_scache_t magic");
591 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
594 /* if no IO is happening, we're done */
595 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
598 /* otherwise I/O is happening, but some other thread is waiting for
599 * the I/O already. Wait for that guy to figure out what happened,
600 * and then check again.
602 if ( bp->flags & CM_BUF_WAITING ) {
605 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%p", bp);
607 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%p", bp);
608 bp->flags |= CM_BUF_WAITING;
609 bp->waitCount = bp->waitRequests = 1;
611 osi_SleepM((LONG_PTR)bp, &bp->mx);
613 cm_UpdateServerPriority();
615 lock_ObtainMutex(&bp->mx);
616 osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%p", bp);
618 if (bp->waitCount == 0) {
619 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%p", bp);
620 bp->flags &= ~CM_BUF_WAITING;
621 bp->waitRequests = 0;
625 if (scp = cm_FindSCache(&bp->fid))
629 lock_ObtainRead(&scp->rw);
630 if (scp->flags & CM_SCACHEFLAG_WAITING) {
631 osi_Log1(buf_logp, "buf_WaitIO waking scp 0x%p", scp);
632 osi_Wakeup((LONG_PTR)&scp->flags);
634 lock_ReleaseRead(&scp->rw);
638 /* if we get here, the IO is done, but we may have to wakeup people waiting for
639 * the I/O to complete. Do so.
641 if (bp->flags & CM_BUF_WAITING) {
642 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
643 osi_Wakeup((LONG_PTR) bp);
645 osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%p", bp);
648 cm_ReleaseSCache(scp);
651 /* find a buffer, if any, for a particular file ID and offset. Assumes
652 * that buf_globalLock is write locked when called.
654 cm_buf_t *buf_FindLocked(struct cm_scache *scp, osi_hyper_t *offsetp)
659 i = BUF_HASH(&scp->fid, offsetp);
660 for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp) {
661 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
662 && offsetp->LowPart == bp->offset.LowPart
663 && offsetp->HighPart == bp->offset.HighPart) {
669 /* return whatever we found, if anything */
673 /* find a buffer with offset *offsetp for vnode *scp. Called
674 * with no locks held.
676 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
680 lock_ObtainRead(&buf_globalLock);
681 bp = buf_FindLocked(scp, offsetp);
682 lock_ReleaseRead(&buf_globalLock);
687 /* find a buffer, if any, for a particular file ID and offset. Assumes
688 * that buf_globalLock is write locked when called. Uses the all buffer
691 cm_buf_t *buf_FindAllLocked(struct cm_scache *scp, osi_hyper_t *offsetp, afs_uint32 flags)
696 for(bp = cm_data.buf_allp; bp; bp=bp->allp) {
697 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
698 && offsetp->LowPart == bp->offset.LowPart
699 && offsetp->HighPart == bp->offset.HighPart) {
705 for(bp = cm_data.buf_allp; bp; bp=bp->allp) {
706 if (cm_FidCmp(&scp->fid, &bp->fid) == 0) {
709 fileOffset = offsetp->QuadPart + cm_data.baseAddress;
710 if (fileOffset == bp->datap) {
717 /* return whatever we found, if anything */
721 /* find a buffer with offset *offsetp for vnode *scp. Called
722 * with no locks held. Use the all buffer list.
724 cm_buf_t *buf_FindAll(struct cm_scache *scp, osi_hyper_t *offsetp, afs_uint32 flags)
728 lock_ObtainRead(&buf_globalLock);
729 bp = buf_FindAllLocked(scp, offsetp, flags);
730 lock_ReleaseRead(&buf_globalLock);
735 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
738 * Makes sure that there's only one person writing this block
739 * at any given time, and also ensures that the log is forced sufficiently far,
740 * if this buffer contains logged data.
742 * Returns non-zero if the buffer was dirty.
744 afs_uint32 buf_CleanAsyncLocked(cm_scache_t *scp, cm_buf_t *bp, cm_req_t *reqp,
745 afs_uint32 flags, afs_uint32 *pisdirty)
748 afs_uint32 isdirty = 0;
752 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
754 if (scp = cm_FindSCache(&bp->fid))
758 osi_Log1(buf_logp, "buf_CleanAsyncLocked unable to start I/O - scp not found buf 0x%p", bp);
759 code = CM_ERROR_NOSUCHFILE;
762 while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
764 lock_ReleaseMutex(&bp->mx);
766 osi_Log2(buf_logp, "buf_CleanAsyncLocked starts I/O on scp 0x%p buf 0x%p", scp, bp);
769 LargeIntegerAdd(offset, ConvertLongToLargeInteger(bp->dirty_offset));
770 code = (*cm_buf_opsp->Writep)(scp, &offset,
772 /* we might as well try to write all of the contiguous
773 * dirty buffers in one RPC
779 flags, bp->userp, reqp);
780 osi_Log3(buf_logp, "buf_CleanAsyncLocked I/O on scp 0x%p buf 0x%p, done=%d", scp, bp, code);
782 lock_ObtainMutex(&bp->mx);
783 /* if the Write routine returns No Such File, clear the dirty flag
784 * because we aren't going to be able to write this data to the file
787 if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BADFD || code == CM_ERROR_NOACCESS ||
788 code == CM_ERROR_QUOTA || code == CM_ERROR_SPACE || code == CM_ERROR_TOOBIG ||
789 code == CM_ERROR_READONLY || code == CM_ERROR_NOSUCHPATH){
790 bp->flags &= ~CM_BUF_DIRTY;
791 bp->flags |= CM_BUF_ERROR;
792 bp->dirty_offset = 0;
793 bp->dirty_length = 0;
795 bp->dataVersion = CM_BUF_VERSION_BAD;
801 /* Disk cache support */
802 /* write buffer to disk cache (synchronous for now) */
803 diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
804 #endif /* DISKCACHE95 */
806 /* if we get here and retries are not permitted
807 * then we need to exit this loop regardless of
808 * whether or not we were able to clear the dirty bit
810 if (reqp->flags & CM_REQ_NORETRY)
813 /* Ditto if the hardDeadTimeout or idleTimeout was reached */
814 if (code == CM_ERROR_TIMEDOUT || code == CM_ERROR_ALLDOWN ||
815 code == CM_ERROR_ALLBUSY || code == CM_ERROR_ALLOFFLINE ||
816 code == CM_ERROR_CLOCKSKEW) {
822 cm_ReleaseSCache(scp);
824 /* if someone was waiting for the I/O that just completed or failed,
827 if (bp->flags & CM_BUF_WAITING) {
828 /* turn off flags and wakeup users */
829 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
830 osi_Wakeup((LONG_PTR) bp);
839 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
840 * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
841 * The buffer must already be clean, and no I/O should be happening to it.
843 void buf_Recycle(cm_buf_t *bp)
848 cm_buf_t *prevBp, *nextBp;
850 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
852 /* if we get here, we know that the buffer still has a 0 ref count,
853 * and that it is clean and has no currently pending I/O. This is
854 * the dude to return.
855 * Remember that as long as the ref count is 0, we know that we won't
856 * have any lock conflicts, so we can grab the buffer lock out of
857 * order in the locking hierarchy.
859 osi_Log3( buf_logp, "buf_Recycle recycles 0x%p, off 0x%x:%08x",
860 bp, bp->offset.HighPart, bp->offset.LowPart);
862 osi_assertx(bp->refCount == 0, "cm_buf_t refcount != 0");
863 osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)),
864 "incorrect cm_buf_t flags");
865 lock_AssertWrite(&buf_globalLock);
867 if (bp->qFlags & CM_BUF_QINHASH) {
868 /* Remove from hash */
870 i = BUF_HASH(&bp->fid, &bp->offset);
871 lbpp = &(cm_data.buf_scacheHashTablepp[i]);
872 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
877 /* we better find it */
878 osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
880 *lbpp = bp->hashp; /* hash out */
883 /* Remove from file hash */
885 i = BUF_FILEHASH(&bp->fid);
886 prevBp = bp->fileHashBackp;
887 bp->fileHashBackp = NULL;
888 nextBp = bp->fileHashp;
889 bp->fileHashp = NULL;
891 prevBp->fileHashp = nextBp;
893 cm_data.buf_fileHashTablepp[i] = nextBp;
895 nextBp->fileHashBackp = prevBp;
897 bp->qFlags &= ~CM_BUF_QINHASH;
900 /* make the fid unrecognizable */
901 memset(&bp->fid, 0, sizeof(cm_fid_t));
903 /* clean up junk flags */
904 bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
905 bp->dataVersion = CM_BUF_VERSION_BAD; /* unknown so far */
908 /* recycle a buffer, removing it from the free list, hashing in its new identity
909 * and returning it write-locked so that no one can use it. Called without
910 * any locks held, and can return an error if it loses the race condition and
911 * finds that someone else created the desired buffer.
913 * If success is returned, the buffer is returned write-locked.
915 * May be called with null scp and offsetp, if we're just trying to reclaim some
916 * space from the buffer pool. In that case, the buffer will be returned
917 * without being hashed into the hash table.
919 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp, cm_buf_t **bufpp)
921 cm_buf_t *bp; /* buffer we're dealing with */
922 cm_buf_t *nextBp; /* next buffer in file hash chain */
923 afs_uint32 i; /* temp */
926 buf_ValidateBufQueues();
931 lock_ObtainRead(&scp->bufCreateLock);
932 lock_ObtainWrite(&buf_globalLock);
933 /* check to see if we lost the race */
935 if (bp = buf_FindLocked(scp, offsetp)) {
936 /* Do not call buf_ReleaseLocked() because we
937 * do not want to allow the buffer to be added
940 afs_int32 refCount = InterlockedDecrement(&bp->refCount);
941 #ifdef DEBUG_REFCOUNT
942 osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, refCount);
943 afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, refCount);
945 lock_ReleaseWrite(&buf_globalLock);
946 lock_ReleaseRead(&scp->bufCreateLock);
947 return CM_BUF_EXISTS;
951 /* does this fix the problem below? it's a simple solution. */
952 if (!cm_data.buf_freeListEndp)
954 lock_ReleaseWrite(&buf_globalLock);
955 lock_ReleaseRead(&scp->bufCreateLock);
956 osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List is empty - sleeping 200ms");
961 /* for debugging, assert free list isn't empty, although we
962 * really should try waiting for a running tranasction to finish
963 * instead of this; or better, we should have a transaction
964 * throttler prevent us from entering this situation.
966 osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
968 /* look at all buffers in free list, some of which may temp.
969 * have high refcounts and which then should be skipped,
970 * starting cleaning I/O for those which are dirty. If we find
971 * a clean buffer, we rehash it, lock it and return it.
973 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
974 /* check to see if it really has zero ref count. This
975 * code can bump refcounts, at least, so it may not be
978 if (bp->refCount > 0)
981 /* we don't have to lock buffer itself, since the ref
982 * count is 0 and we know it will stay zero as long as
983 * we hold the global lock.
986 /* Don't recycle a buffer held by the redirector. */
987 if (bp->qFlags & CM_BUF_QREDIR)
990 /* don't recycle someone in our own chunk */
991 if (!cm_FidCmp(&bp->fid, &scp->fid)
992 && (bp->offset.LowPart & (-cm_chunkSize))
993 == (offsetp->LowPart & (-cm_chunkSize)))
996 /* if this page is being filled (!) or cleaned, see if
997 * the I/O has completed. If not, skip it, otherwise
998 * do the final processing for the I/O.
1000 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
1001 /* probably shouldn't do this much work while
1002 * holding the big lock? Watch for contention
1008 if (bp->flags & CM_BUF_DIRTY) {
1009 /* if the buffer is dirty, start cleaning it and
1010 * move on to the next buffer. We do this with
1011 * just the lock required to minimize contention
1015 lock_ReleaseWrite(&buf_globalLock);
1016 lock_ReleaseRead(&scp->bufCreateLock);
1018 /* grab required lock and clean; this only
1019 * starts the I/O. By the time we're back,
1020 * it'll still be marked dirty, but it will also
1021 * have the WRITING flag set, so we won't get
1024 buf_CleanAsync(scp, bp, reqp, 0, NULL);
1026 /* now put it back and go around again */
1031 /* if we get here, we know that the buffer still has a 0
1032 * ref count, and that it is clean and has no currently
1033 * pending I/O. This is the dude to return.
1034 * Remember that as long as the ref count is 0, we know
1035 * that we won't have any lock conflicts, so we can grab
1036 * the buffer lock out of order in the locking hierarchy.
1040 /* now hash in as our new buffer, and give it the
1041 * appropriate label, if requested.
1044 bp->qFlags |= CM_BUF_QINHASH;
1049 bp->offset = *offsetp;
1050 i = BUF_HASH(&scp->fid, offsetp);
1051 bp->hashp = cm_data.buf_scacheHashTablepp[i];
1052 cm_data.buf_scacheHashTablepp[i] = bp;
1053 i = BUF_FILEHASH(&scp->fid);
1054 nextBp = cm_data.buf_fileHashTablepp[i];
1055 bp->fileHashp = nextBp;
1056 bp->fileHashBackp = NULL;
1058 nextBp->fileHashBackp = bp;
1059 cm_data.buf_fileHashTablepp[i] = bp;
1062 /* we should move it from the lru queue. It better still be there,
1063 * since we've held the global (big) lock since we found it there.
1065 osi_assertx(bp->qFlags & CM_BUF_QINLRU,
1066 "buf_GetNewLocked: LRU screwup");
1068 if (cm_data.buf_freeListEndp == bp) {
1069 /* we're the last guy in this queue, so maintain it */
1070 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1072 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
1073 bp->qFlags &= ~CM_BUF_QINLRU;
1075 /* prepare to return it. Give it a refcount */
1077 #ifdef DEBUG_REFCOUNT
1078 osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, 1);
1079 afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, 1);
1081 /* grab the mutex so that people don't use it
1082 * before the caller fills it with data. Again, no one
1083 * should have been able to get to this dude to lock it.
1085 if (!lock_TryMutex(&bp->mx)) {
1086 osi_Log2(afsd_logp, "buf_GetNewLocked bp 0x%p cannot be mutex locked. refCount %d should be 0",
1088 osi_panic("buf_GetNewLocked: TryMutex failed",__FILE__,__LINE__);
1091 lock_ReleaseWrite(&buf_globalLock);
1092 lock_ReleaseRead(&scp->bufCreateLock);
1097 buf_ValidateBufQueues();
1098 #endif /* TESTING */
1100 } /* for all buffers in lru queue */
1101 lock_ReleaseWrite(&buf_globalLock);
1102 lock_ReleaseRead(&scp->bufCreateLock);
1103 osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List has no buffers with a zero refcount - sleeping 100ms");
1104 Sleep(100); /* give some time for a buffer to be freed */
1105 } /* while loop over everything */
1109 /* get a page, returning it held but unlocked. Doesn't fill in the page
1110 * with I/O, since we're going to write the whole thing new.
1112 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp, cm_buf_t **bufpp)
1116 osi_hyper_t pageOffset;
1120 pageOffset.HighPart = offsetp->HighPart;
1121 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1123 bp = buf_Find(scp, &pageOffset);
1125 /* lock it and break out */
1126 lock_ObtainMutex(&bp->mx);
1130 /* otherwise, we have to create a page */
1131 code = buf_GetNewLocked(scp, &pageOffset, reqp, &bp);
1133 /* check if the buffer was created in a race condition branch.
1134 * If so, go around so we can hold a reference to it.
1136 if (code == CM_BUF_EXISTS)
1139 /* something else went wrong */
1143 /* otherwise, we have a locked buffer that we just created */
1146 } /* big while loop */
1148 /* wait for reads */
1149 if (bp->flags & CM_BUF_READING)
1150 buf_WaitIO(scp, bp);
1152 /* once it has been read once, we can unlock it and return it, still
1153 * with its refcount held.
1155 lock_ReleaseMutex(&bp->mx);
1157 osi_Log4(buf_logp, "buf_GetNew returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1158 bp, scp, offsetp->HighPart, offsetp->LowPart);
1162 /* get a page, returning it held but unlocked. Make sure it is complete */
1163 /* The scp must be unlocked when passed to this function */
1164 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp, cm_buf_t **bufpp)
1168 osi_hyper_t pageOffset;
1169 unsigned long tcount;
1173 cm_diskcache_t *dcp;
1174 #endif /* DISKCACHE95 */
1177 pageOffset.HighPart = offsetp->HighPart;
1178 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1182 buf_ValidateBufQueues();
1183 #endif /* TESTING */
1185 bp = buf_Find(scp, &pageOffset);
1187 /* lock it and break out */
1188 lock_ObtainMutex(&bp->mx);
1191 /* touch disk chunk to update LRU info */
1192 diskcache_Touch(bp->dcp);
1193 #endif /* DISKCACHE95 */
1197 /* otherwise, we have to create a page */
1198 code = buf_GetNewLocked(scp, &pageOffset, reqp, &bp);
1199 /* bp->mx is now held */
1201 /* check if the buffer was created in a race condition branch.
1202 * If so, go around so we can hold a reference to it.
1204 if (code == CM_BUF_EXISTS)
1207 /* something else went wrong */
1210 buf_ValidateBufQueues();
1211 #endif /* TESTING */
1215 /* otherwise, we have a locked buffer that we just created */
1218 } /* big while loop */
1220 /* if we get here, we have a locked buffer that may have just been
1221 * created, in which case it needs to be filled with data.
1224 /* load the page; freshly created pages should be idle */
1225 osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)), "incorrect cm_buf_t flags");
1227 /* start the I/O; may drop lock */
1228 bp->flags |= CM_BUF_READING;
1229 code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
1232 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
1233 bp->dcp = dcp; /* pointer to disk cache struct. */
1234 #endif /* DISKCACHE95 */
1237 /* failure or queued */
1238 if (code != ERROR_IO_PENDING) {
1240 bp->flags |= CM_BUF_ERROR;
1241 bp->flags &= ~CM_BUF_READING;
1242 if (bp->flags & CM_BUF_WAITING) {
1243 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1244 osi_Wakeup((LONG_PTR) bp);
1246 lock_ReleaseMutex(&bp->mx);
1249 buf_ValidateBufQueues();
1250 #endif /* TESTING */
1254 /* otherwise, I/O completed instantly and we're done, except
1255 * for padding the xfr out with 0s and checking for EOF
1257 if (tcount < (unsigned long) cm_data.buf_blockSize) {
1258 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
1260 bp->flags |= CM_BUF_EOF;
1262 bp->flags &= ~CM_BUF_READING;
1263 if (bp->flags & CM_BUF_WAITING) {
1264 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1265 osi_Wakeup((LONG_PTR) bp);
1271 /* wait for reads, either that which we started above, or that someone
1272 * else started. We don't care if we return a buffer being cleaned.
1274 if (bp->flags & CM_BUF_READING)
1275 buf_WaitIO(scp, bp);
1277 /* once it has been read once, we can unlock it and return it, still
1278 * with its refcount held.
1280 lock_ReleaseMutex(&bp->mx);
1283 /* now remove from queue; will be put in at the head (farthest from
1284 * being recycled) when we're done in buf_Release.
1286 lock_ObtainWrite(&buf_globalLock);
1287 if (bp->qFlags & CM_BUF_QINLRU) {
1288 if (cm_data.buf_freeListEndp == bp)
1289 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1290 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
1291 bp->qFlags &= ~CM_BUF_QINLRU;
1293 lock_ReleaseWrite(&buf_globalLock);
1295 osi_Log4(buf_logp, "buf_Get returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1296 bp, scp, offsetp->HighPart, offsetp->LowPart);
1298 buf_ValidateBufQueues();
1299 #endif /* TESTING */
1303 /* count # of elements in the free list;
1304 * we don't bother doing the proper locking for accessing dataVersion or flags
1305 * since it is a pain, and this is really just an advisory call. If you need
1306 * to do better at some point, rewrite this function.
1308 long buf_CountFreeList(void)
1314 lock_ObtainRead(&buf_globalLock);
1315 for(bufp = cm_data.buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1316 /* if the buffer doesn't have an identity, or if the buffer
1317 * has been invalidate (by having its DV stomped upon), then
1318 * count it as free, since it isn't really being utilized.
1320 if (!(bufp->qFlags & CM_BUF_QINHASH) || bufp->dataVersion == CM_BUF_VERSION_BAD)
1323 lock_ReleaseRead(&buf_globalLock);
1327 /* clean a buffer synchronously */
1328 afs_uint32 buf_CleanAsync(cm_scache_t *scp, cm_buf_t *bp, cm_req_t *reqp, afs_uint32 flags, afs_uint32 *pisdirty)
1331 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1332 osi_assertx(!(flags & CM_BUF_WRITE_SCP_LOCKED), "scp->rw must not be held when calling buf_CleanAsync");
1334 lock_ObtainMutex(&bp->mx);
1335 code = buf_CleanAsyncLocked(scp, bp, reqp, flags, pisdirty);
1336 lock_ReleaseMutex(&bp->mx);
1341 /* wait for a buffer's cleaning to finish */
1342 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp, afs_uint32 locked)
1344 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1347 lock_ObtainMutex(&bp->mx);
1348 if (bp->flags & CM_BUF_WRITING) {
1349 buf_WaitIO(scp, bp);
1352 lock_ReleaseMutex(&bp->mx);
1355 /* set the dirty flag on a buffer, and set associated write-ahead log,
1356 * if there is one. Allow one to be added to a buffer, but not changed.
1358 * The buffer must be locked before calling this routine.
1360 void buf_SetDirty(cm_buf_t *bp, afs_uint32 offset, afs_uint32 length, cm_user_t *userp)
1362 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1363 osi_assertx(bp->refCount > 0, "cm_buf_t refcount 0");
1365 if (bp->flags & CM_BUF_DIRTY) {
1367 osi_Log1(buf_logp, "buf_SetDirty 0x%p already dirty", bp);
1369 if (bp->dirty_offset <= offset) {
1370 if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1371 /* dirty_length remains the same */
1373 bp->dirty_length = offset + length - bp->dirty_offset;
1375 } else /* bp->dirty_offset > offset */ {
1376 if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1377 bp->dirty_length = bp->dirty_offset + bp->dirty_length - offset;
1379 bp->dirty_length = length;
1381 bp->dirty_offset = offset;
1384 osi_Log1(buf_logp, "buf_SetDirty 0x%p", bp);
1387 bp->flags |= CM_BUF_DIRTY;
1389 /* and turn off EOF flag, since it has associated data now */
1390 bp->flags &= ~CM_BUF_EOF;
1392 bp->dirty_offset = offset;
1393 bp->dirty_length = length;
1395 /* and add to the dirty list.
1396 * we obtain a hold on the buffer for as long as it remains
1397 * in the list. buffers are only removed from the list by
1398 * the buf_IncrSyncer function regardless of when else the
1399 * dirty flag might be cleared.
1401 * This should never happen but just in case there is a bug
1402 * elsewhere, never add to the dirty list if the buffer is
1405 lock_ObtainWrite(&buf_globalLock);
1406 if (!(bp->qFlags & CM_BUF_QINDL)) {
1408 if (!cm_data.buf_dirtyListp) {
1409 cm_data.buf_dirtyListp = cm_data.buf_dirtyListEndp = bp;
1411 cm_data.buf_dirtyListEndp->dirtyp = bp;
1412 cm_data.buf_dirtyListEndp = bp;
1415 bp->qFlags |= CM_BUF_QINDL;
1417 lock_ReleaseWrite(&buf_globalLock);
1420 /* and record the last writer */
1421 if (bp->userp != userp) {
1424 cm_ReleaseUser(bp->userp);
1429 /* clean all buffers, reset log pointers and invalidate all buffers.
1430 * Called with no locks held, and returns with same.
1432 * This function is guaranteed to clean and remove the log ptr of all the
1433 * buffers that were dirty or had non-zero log ptrs before the call was
1434 * made. That's sufficient to clean up any garbage left around by recovery,
1435 * which is all we're counting on this for; there may be newly created buffers
1436 * added while we're running, but that should be OK.
1438 * In an environment where there are no transactions (artificially imposed, for
1439 * example, when switching the database to raw mode), this function is used to
1440 * make sure that all updates have been written to the disk. In that case, we don't
1441 * really require that we forget the log association between pages and logs, but
1442 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1443 * have to worry about invalidating data in the buffers.
1445 * This function is used at the end of recovery as paranoia to get the recovered
1446 * database out to disk. It removes all references to the recovery log and cleans
1449 long buf_CleanAndReset(void)
1455 lock_ObtainRead(&buf_globalLock);
1456 for(i=0; i<cm_data.buf_hashSize; i++) {
1457 for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp = bp->hashp) {
1458 if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1460 lock_ReleaseRead(&buf_globalLock);
1462 /* now no locks are held; clean buffer and go on */
1464 req.flags |= CM_REQ_NORETRY;
1466 buf_CleanAsync(NULL, bp, &req, 0, NULL);
1467 buf_CleanWait(NULL, bp, FALSE);
1469 /* relock and release buffer */
1470 lock_ObtainRead(&buf_globalLock);
1471 buf_ReleaseLocked(bp, FALSE);
1473 } /* over one bucket */
1474 } /* for loop over all hash buckets */
1477 lock_ReleaseRead(&buf_globalLock);
1480 buf_ValidateBufQueues();
1481 #endif /* TESTING */
1483 /* and we're done */
1487 /* called without global lock being held, reserves buffers for callers
1488 * that need more than one held (not locked) at once.
1490 void buf_ReserveBuffers(afs_uint64 nbuffers)
1492 lock_ObtainWrite(&buf_globalLock);
1494 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1495 cm_data.buf_reserveWaiting = 1;
1496 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1497 osi_SleepW((LONG_PTR) &cm_data.buf_reservedBufs, &buf_globalLock);
1498 lock_ObtainWrite(&buf_globalLock);
1501 cm_data.buf_reservedBufs += nbuffers;
1505 lock_ReleaseWrite(&buf_globalLock);
1508 int buf_TryReserveBuffers(afs_uint64 nbuffers)
1512 lock_ObtainWrite(&buf_globalLock);
1513 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1517 cm_data.buf_reservedBufs += nbuffers;
1520 lock_ReleaseWrite(&buf_globalLock);
1524 /* called without global lock held, releases reservation held by
1525 * buf_ReserveBuffers.
1527 void buf_UnreserveBuffers(afs_uint64 nbuffers)
1529 lock_ObtainWrite(&buf_globalLock);
1530 cm_data.buf_reservedBufs -= nbuffers;
1531 if (cm_data.buf_reserveWaiting) {
1532 cm_data.buf_reserveWaiting = 0;
1533 osi_Wakeup((LONG_PTR) &cm_data.buf_reservedBufs);
1535 lock_ReleaseWrite(&buf_globalLock);
1538 /* truncate the buffers past sizep, zeroing out the page, if we don't
1539 * end on a page boundary.
1541 * Requires cm_bufCreateLock to be write locked.
1543 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1547 cm_buf_t *nbufp; /* next buffer, if didRelease */
1553 /* assert that cm_bufCreateLock is held in write mode */
1554 lock_AssertWrite(&scp->bufCreateLock);
1556 i = BUF_FILEHASH(&scp->fid);
1558 lock_ObtainRead(&buf_globalLock);
1559 bufp = cm_data.buf_fileHashTablepp[i];
1561 lock_ReleaseRead(&buf_globalLock);
1565 buf_HoldLocked(bufp);
1566 lock_ReleaseRead(&buf_globalLock);
1568 lock_ObtainMutex(&bufp->mx);
1570 bufEnd.HighPart = 0;
1571 bufEnd.LowPart = cm_data.buf_blockSize;
1572 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1574 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1575 LargeIntegerLessThan(*sizep, bufEnd)) {
1576 buf_WaitIO(scp, bufp);
1578 lock_ObtainWrite(&scp->rw);
1580 /* make sure we have a callback (so we have the right value for
1581 * the length), and wait for it to be safe to do a truncate.
1583 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1584 CM_SCACHESYNC_NEEDCALLBACK
1585 | CM_SCACHESYNC_GETSTATUS
1586 | CM_SCACHESYNC_SETSIZE
1587 | CM_SCACHESYNC_BUFLOCKED);
1590 /* if we succeeded in our locking, and this applies to the right
1591 * file, and the truncate request overlaps the buffer either
1592 * totally or partially, then do something.
1594 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1595 && LargeIntegerLessThan(*sizep, bufEnd)) {
1598 /* destroy the buffer, turning off its dirty bit, if
1599 * we're truncating the whole buffer. Otherwise, set
1600 * the dirty bit, and clear out the tail of the buffer
1601 * if we just overlap some.
1603 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1604 /* truncating the entire page */
1605 bufp->flags &= ~CM_BUF_DIRTY;
1606 bufp->dirty_offset = 0;
1607 bufp->dirty_length = 0;
1608 bufp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
1609 bufp->dirtyCounter++;
1612 /* don't set dirty, since dirty implies
1613 * currently up-to-date. Don't need to do this,
1614 * since we'll update the length anyway.
1616 * Zero out remainder of the page, in case we
1617 * seek and write past EOF, and make this data
1620 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1621 osi_assertx(bufferPos != 0, "non-zero bufferPos");
1622 memset(bufp->datap + bufferPos, 0,
1623 cm_data.buf_blockSize - bufferPos);
1627 cm_SyncOpDone( scp, bufp,
1628 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
1629 | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_BUFLOCKED);
1631 lock_ReleaseWrite(&scp->rw);
1632 lock_ReleaseMutex(&bufp->mx);
1635 nbufp = bufp->fileHashp;
1639 /* This forces the loop to end and the error code
1640 * to be returned. */
1648 buf_ValidateBufQueues();
1649 #endif /* TESTING */
1655 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1658 cm_buf_t *bp; /* buffer we're hacking on */
1662 afs_uint32 stable = 0;
1664 i = BUF_FILEHASH(&scp->fid);
1667 lock_ObtainRead(&buf_globalLock);
1668 bp = cm_data.buf_fileHashTablepp[i];
1671 lock_ReleaseRead(&buf_globalLock);
1673 for (; bp; bp = nbp) {
1674 didRelease = 0; /* haven't released this buffer yet */
1676 /* clean buffer synchronously */
1677 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1679 if (code == 0 && !stable && (bp->flags & CM_BUF_DIRTY)) {
1681 * we must stabilize the object to ensure that buffer
1682 * changes cannot occur while the flush is performed.
1683 * However, we do not want to Stabilize if we do not
1684 * need to because Stabilize obtains a callback.
1686 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1687 stable = (code == 0);
1690 if (code == CM_ERROR_BADFD) {
1691 /* if the scp's FID is bad its because we received VNOVNODE
1692 * when attempting to FetchStatus before the write. This
1693 * page therefore contains data that can no longer be stored.
1695 lock_ObtainMutex(&bp->mx);
1696 bp->flags &= ~CM_BUF_DIRTY;
1697 bp->flags |= CM_BUF_ERROR;
1698 bp->error = CM_ERROR_BADFD;
1699 bp->dirty_offset = 0;
1700 bp->dirty_length = 0;
1701 bp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
1703 lock_ReleaseMutex(&bp->mx);
1704 } else if (!(scp->flags & CM_SCACHEFLAG_RO)) {
1709 lock_ObtainMutex(&bp->mx);
1711 /* start cleaning the buffer, and wait for it to finish */
1712 buf_CleanAsyncLocked(scp, bp, reqp, 0, NULL);
1713 buf_WaitIO(scp, bp);
1715 lock_ReleaseMutex(&bp->mx);
1718 /* actually, we only know that buffer is clean if ref
1719 * count is 1, since we don't have buffer itself locked.
1721 if (!(bp->flags & CM_BUF_DIRTY)) {
1722 lock_ObtainWrite(&buf_globalLock);
1723 if (bp->refCount == 1) { /* bp is held above */
1724 nbp = bp->fileHashp;
1726 buf_HoldLocked(nbp);
1727 buf_ReleaseLocked(bp, TRUE);
1731 lock_ReleaseWrite(&buf_globalLock);
1737 lock_ObtainRead(&buf_globalLock);
1738 nbp = bp->fileHashp;
1740 buf_HoldLocked(nbp);
1741 buf_ReleaseLocked(bp, FALSE);
1742 lock_ReleaseRead(&buf_globalLock);
1744 } /* for loop over a bunch of buffers */
1747 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1750 buf_ValidateBufQueues();
1751 #endif /* TESTING */
1757 /* Must be called with scp->rw held */
1758 long buf_ForceDataVersion(cm_scache_t * scp, afs_uint64 fromVersion, afs_uint64 toVersion)
1764 lock_AssertAny(&scp->rw);
1766 i = BUF_FILEHASH(&scp->fid);
1768 lock_ObtainRead(&buf_globalLock);
1770 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp = bp->fileHashp) {
1771 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1772 if (bp->dataVersion == fromVersion) {
1773 bp->dataVersion = toVersion;
1778 lock_ReleaseRead(&buf_globalLock);
1786 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1790 cm_buf_t *bp; /* buffer we're hacking on */
1791 cm_buf_t *nbp; /* next one */
1794 i = BUF_FILEHASH(&scp->fid);
1796 lock_ObtainRead(&buf_globalLock);
1797 bp = cm_data.buf_fileHashTablepp[i];
1800 lock_ReleaseRead(&buf_globalLock);
1801 for (; bp; bp = nbp) {
1802 /* clean buffer synchronously */
1803 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1804 lock_ObtainMutex(&bp->mx);
1805 if (bp->flags & CM_BUF_DIRTY) {
1806 if (userp && userp != bp->userp) {
1809 cm_ReleaseUser(bp->userp);
1814 case CM_ERROR_NOSUCHFILE:
1815 case CM_ERROR_BADFD:
1816 case CM_ERROR_NOACCESS:
1817 case CM_ERROR_QUOTA:
1818 case CM_ERROR_SPACE:
1819 case CM_ERROR_TOOBIG:
1820 case CM_ERROR_READONLY:
1821 case CM_ERROR_NOSUCHPATH:
1823 * Apply the previous fatal error to this buffer.
1824 * Do not waste the time attempting to store to
1825 * the file server when we know it will fail.
1827 bp->flags &= ~CM_BUF_DIRTY;
1828 bp->flags |= CM_BUF_ERROR;
1829 bp->dirty_offset = 0;
1830 bp->dirty_length = 0;
1832 bp->dataVersion = CM_BUF_VERSION_BAD;
1835 case CM_ERROR_TIMEDOUT:
1836 case CM_ERROR_ALLDOWN:
1837 case CM_ERROR_ALLBUSY:
1838 case CM_ERROR_ALLOFFLINE:
1839 case CM_ERROR_CLOCKSKEW:
1840 /* do not mark the buffer in error state but do
1841 * not attempt to complete the rest either.
1845 code = buf_CleanAsyncLocked(scp, bp, reqp, 0, &wasDirty);
1846 if (bp->flags & CM_BUF_ERROR) {
1852 buf_CleanWait(scp, bp, TRUE);
1854 lock_ReleaseMutex(&bp->mx);
1857 lock_ObtainRead(&buf_globalLock);
1858 nbp = bp->fileHashp;
1860 buf_HoldLocked(nbp);
1861 buf_ReleaseLocked(bp, FALSE);
1862 lock_ReleaseRead(&buf_globalLock);
1863 } /* for loop over a bunch of buffers */
1866 buf_ValidateBufQueues();
1867 #endif /* TESTING */
1875 buf_ValidateBufQueues(void)
1877 cm_buf_t * bp, *bpb, *bpf, *bpa;
1878 afs_uint32 countf=0, countb=0, counta=0;
1880 lock_ObtainRead(&buf_globalLock);
1881 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1882 if (bp->magic != CM_BUF_MAGIC)
1883 osi_panic("buf magic error",__FILE__,__LINE__);
1888 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
1889 if (bp->magic != CM_BUF_MAGIC)
1890 osi_panic("buf magic error",__FILE__,__LINE__);
1895 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
1896 if (bp->magic != CM_BUF_MAGIC)
1897 osi_panic("buf magic error",__FILE__,__LINE__);
1901 lock_ReleaseRead(&buf_globalLock);
1903 if (countb != countf)
1904 osi_panic("buf magic error",__FILE__,__LINE__);
1906 if (counta != cm_data.buf_nbuffers)
1907 osi_panic("buf magic error",__FILE__,__LINE__);
1909 #endif /* TESTING */
1911 /* dump the contents of the buf_scacheHashTablepp. */
1912 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
1919 if (cm_data.buf_scacheHashTablepp == NULL)
1923 lock_ObtainRead(&buf_globalLock);
1925 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\r\n",
1926 cookie, cm_data.buf_hashSize);
1927 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1929 for (i = 0; i < cm_data.buf_hashSize; i++)
1931 for (bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp)
1933 StringCbPrintfA(output, sizeof(output),
1934 "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d, "
1935 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1936 "flags=0x%x, qFlags=0x%x cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
1937 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
1938 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
1939 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
1940 bp->cmFlags, bp->error, bp->refCount);
1941 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1945 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\r\n", cookie);
1946 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1948 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_freeListEndp\r\n", cookie);
1949 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1950 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1951 StringCbPrintfA(output, sizeof(output),
1952 "%s bp=0x%08X, fid (cell=%d, volume=%d, "
1953 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1954 "flags=0x%x, qFlags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
1955 cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
1956 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
1957 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
1958 bp->cmFlags, bp->error, bp->refCount);
1959 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1961 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_FreeListEndp.\r\n", cookie);
1962 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1964 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_dirtyListp\r\n", cookie);
1965 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1966 for(bp = cm_data.buf_dirtyListp; bp; bp=bp->dirtyp) {
1967 StringCbPrintfA(output, sizeof(output),
1968 "%s bp=0x%08X, fid (cell=%d, volume=%d, "
1969 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1970 "flags=0x%x, qFlags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
1971 cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
1972 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
1973 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
1974 bp->cmFlags, bp->error, bp->refCount);
1975 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1977 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_dirtyListp.\r\n", cookie);
1978 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1981 lock_ReleaseRead(&buf_globalLock);
1985 void buf_ForceTrace(BOOL flush)
1994 len = GetTempPath(sizeof(buf)-10, buf);
1995 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
1996 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
1997 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1998 if (handle == INVALID_HANDLE_VALUE) {
1999 osi_panic("Cannot create log file", __FILE__, __LINE__);
2001 osi_LogPrint(buf_logp, handle);
2003 FlushFileBuffers(handle);
2004 CloseHandle(handle);
2007 long buf_DirtyBuffersExist(cm_fid_t *fidp)
2010 afs_uint32 bcount = 0;
2013 i = BUF_FILEHASH(fidp);
2015 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2016 if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY))
2023 long buf_CleanDirtyBuffers(cm_scache_t *scp)
2026 afs_uint32 bcount = 0;
2027 cm_fid_t * fidp = &scp->fid;
2029 for (bp = cm_data.buf_allp; bp; bp=bp->allp, bcount++) {
2030 if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
2032 lock_ObtainMutex(&bp->mx);
2033 bp->cmFlags &= ~CM_BUF_CMSTORING;
2034 bp->flags &= ~CM_BUF_DIRTY;
2035 bp->dirty_offset = 0;
2036 bp->dirty_length = 0;
2037 bp->flags |= CM_BUF_ERROR;
2038 bp->error = VNOVNODE;
2039 bp->dataVersion = CM_BUF_VERSION_BAD; /* bad */
2041 if (bp->flags & CM_BUF_WAITING) {
2042 osi_Log2(buf_logp, "BUF CleanDirtyBuffers Waking [scp 0x%x] bp 0x%x", scp, bp);
2043 osi_Wakeup((long) &bp);
2045 lock_ReleaseMutex(&bp->mx);