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 <afsconfig.h>
13 #include <afs/param.h>
23 #include <hcrypto\md5.h>
26 #include "cm_memmap.h"
29 #define TRACE_BUFFER 1
32 extern void afsi_log(char *pattern, ...);
34 /* This module implements the buffer package used by the local transaction
35 * system (cm). It is initialized by calling cm_Init, which calls buf_Init;
36 * it must be initalized before any of its main routines are called.
38 * Each buffer is hashed into a hash table by file ID and offset, and if its
39 * reference count is zero, it is also in a free list.
41 * There are two locks involved in buffer processing. The global lock
42 * buf_globalLock protects all of the global variables defined in this module,
43 * the reference counts and hash pointers in the actual cm_buf_t structures,
44 * and the LRU queue pointers in the buffer structures.
46 * The mutexes in the buffer structures protect the remaining fields in the
47 * buffers, as well the data itself.
49 * The locking hierarchy here is this:
51 * - resv multiple simul. buffers reservation
52 * - lock buffer I/O flags
53 * - lock buffer's mutex
54 * - lock buf_globalLock
58 /* global debugging log */
59 osi_log_t *buf_logp = NULL;
61 /* Global lock protecting hash tables and free lists */
62 osi_rwlock_t buf_globalLock;
64 /* Global lock used to limit the number of RDR Release
65 * Extents requests to one. */
66 osi_mutex_t buf_rdrReleaseExtentsLock;
68 /* ptr to head of the free list (most recently used) and the
69 * tail (the guy to remove first). We use osi_Q* functions
70 * to put stuff in buf_freeListp, and maintain the end
74 /* a pointer to a list of all buffers, just so that we can find them
75 * easily for debugging, and for the incr syncer. Locked under
79 /* defaults setup; these variables may be manually assigned into
80 * before calling cm_Init, as a way of changing these defaults.
83 /* callouts for reading and writing data, etc */
84 cm_buf_ops_t *cm_buf_opsp;
87 /* for experimental disk caching support in Win95 client */
88 cm_buf_t *buf_diskFreeListp;
89 cm_buf_t *buf_diskFreeListEndp;
90 cm_buf_t *buf_diskAllp;
91 extern int cm_diskCacheEnabled;
92 #endif /* DISKCACHE95 */
94 /* set this to 1 when we are terminating to prevent access attempts */
95 static int buf_ShutdownFlag = 0;
98 void buf_HoldLockedDbg(cm_buf_t *bp, char *file, long line)
100 void buf_HoldLocked(cm_buf_t *bp)
105 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
106 refCount = InterlockedIncrement(&bp->refCount);
107 #ifdef DEBUG_REFCOUNT
108 osi_Log2(afsd_logp,"buf_HoldLocked bp 0x%p ref %d",bp, refCount);
109 afsi_log("%s:%d buf_HoldLocked bp 0x%p, ref %d", file, line, bp, refCount);
113 /* hold a reference to an already held buffer */
114 #ifdef DEBUG_REFCOUNT
115 void buf_HoldDbg(cm_buf_t *bp, char *file, long line)
117 void buf_Hold(cm_buf_t *bp)
122 lock_ObtainRead(&buf_globalLock);
123 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
124 refCount = InterlockedIncrement(&bp->refCount);
125 #ifdef DEBUG_REFCOUNT
126 osi_Log2(afsd_logp,"buf_Hold bp 0x%p ref %d",bp, refCount);
127 afsi_log("%s:%d buf_Hold bp 0x%p, ref %d", file, line, bp, refCount);
129 lock_ReleaseRead(&buf_globalLock);
132 /* code to drop reference count while holding buf_globalLock */
133 #ifdef DEBUG_REFCOUNT
134 void buf_ReleaseLockedDbg(cm_buf_t *bp, afs_uint32 writeLocked, char *file, long line)
136 void buf_ReleaseLocked(cm_buf_t *bp, afs_uint32 writeLocked)
142 lock_AssertWrite(&buf_globalLock);
144 lock_AssertRead(&buf_globalLock);
146 /* ensure that we're in the LRU queue if our ref count is 0 */
147 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
149 refCount = InterlockedDecrement(&bp->refCount);
150 #ifdef DEBUG_REFCOUNT
151 osi_Log3(afsd_logp,"buf_ReleaseLocked %s bp 0x%p ref %d",writeLocked?"write":"read", bp, refCount);
152 afsi_log("%s:%d buf_ReleaseLocked %s bp 0x%p, ref %d", file, line, writeLocked?"write":"read", bp, refCount);
156 osi_panic("buf refcount 0",__FILE__,__LINE__);;
158 osi_assertx(refCount >= 0, "cm_buf_t refCount == 0");
162 * If we are read locked there could be a race condition
163 * with buf_Find() so we must obtain a write lock and
164 * double check that the refCount is actually zero
165 * before we remove the buffer from the LRU queue.
168 lock_ConvertRToW(&buf_globalLock);
170 if (bp->refCount == 0 &&
171 !(bp->qFlags & (CM_BUF_QINLRU|CM_BUF_QREDIR))) {
172 osi_QAddH( (osi_queue_t **) &cm_data.buf_freeListp,
173 (osi_queue_t **) &cm_data.buf_freeListEndp,
175 _InterlockedOr(&bp->qFlags, CM_BUF_QINLRU);
176 buf_IncrementFreeCount();
180 lock_ConvertWToR(&buf_globalLock);
184 /* release a buffer. Buffer must be referenced, but unlocked. */
185 #ifdef DEBUG_REFCOUNT
186 void buf_ReleaseDbg(cm_buf_t *bp, char *file, long line)
188 void buf_Release(cm_buf_t *bp)
191 lock_ObtainRead(&buf_globalLock);
192 buf_ReleaseLocked(bp, FALSE);
193 lock_ReleaseRead(&buf_globalLock);
197 buf_Sync(int quitOnShutdown)
199 cm_buf_t **bpp, *bp, *prevbp;
200 afs_uint32 wasDirty = 0;
203 /* go through all of the dirty buffers */
204 lock_ObtainRead(&buf_globalLock);
205 for (bpp = &cm_data.buf_dirtyListp, prevbp = NULL; bp = *bpp; ) {
206 if (quitOnShutdown && buf_ShutdownFlag)
210 * If the buffer is held be the redirector we must fetch
211 * it back in order to determine whether or not it is in
214 if (bp->qFlags & CM_BUF_QREDIR) {
215 osi_Log1(buf_logp,"buf_Sync buffer held by redirector bp 0x%p", bp);
217 /* Request single buffer from the redirector */
218 buf_RDRShakeAnExtentFree(bp, &req);
221 lock_ReleaseRead(&buf_globalLock);
223 * all dirty buffers are held when they are added to the
224 * dirty list. No need for an additional hold.
226 lock_ObtainMutex(&bp->mx);
228 if ((bp->flags & CM_BUF_DIRTY)) {
229 /* start cleaning the buffer; don't touch log pages since
230 * the log code counts on knowing exactly who is writing
231 * a log page at any given instant.
233 * only attempt to write the buffer if the volume might
239 volp = cm_FindVolumeByFID(&bp->fid, bp->userp, &req);
240 switch (cm_GetVolumeStatus(volp, bp->fid.volume)) {
244 req.flags |= CM_REQ_NORETRY;
245 buf_CleanLocked(NULL, bp, &req, 0, &dirty);
251 /* the buffer may or may not have been dirty
252 * and if dirty may or may not have been cleaned
253 * successfully. check the dirty flag again.
255 if (!(bp->flags & CM_BUF_DIRTY)) {
256 /* remove the buffer from the dirty list */
257 lock_ObtainWrite(&buf_globalLock);
258 #ifdef DEBUG_REFCOUNT
259 if (bp->dirtyp == NULL && bp != cm_data.buf_dirtyListEndp) {
260 osi_Log1(afsd_logp,"buf_Sync bp 0x%p list corruption",bp);
261 afsi_log("buf_Sync bp 0x%p list corruption", bp);
266 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINDL);
267 if (cm_data.buf_dirtyListp == NULL)
268 cm_data.buf_dirtyListEndp = NULL;
269 else if (cm_data.buf_dirtyListEndp == bp)
270 cm_data.buf_dirtyListEndp = prevbp;
271 buf_ReleaseLocked(bp, TRUE);
272 lock_ConvertWToR(&buf_globalLock);
274 if (buf_ShutdownFlag) {
277 char volstr[VL_MAXNAMELEN+12]="";
280 volp = cm_GetVolumeByFID(&bp->fid);
283 if (bp->fid.volume == volp->vol[RWVOL].ID)
285 else if (bp->fid.volume == volp->vol[ROVOL].ID)
287 else if (bp->fid.volume == volp->vol[BACKVOL].ID)
291 snprintf(volstr, sizeof(volstr), "%s%s", volp->namep, ext);
293 cellp = cm_FindCellByID(bp->fid.cell, CM_FLAG_NOPROBE);
294 snprintf(volstr, sizeof(volstr), "%u", bp->fid.volume);
297 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_DIRTY_BUFFER_AT_SHUTDOWN,
298 cellp->name, volstr, bp->fid.vnode, bp->fid.unique,
299 bp->offset.QuadPart+bp->dirty_offset, bp->dirty_length);
302 /* advance the pointer so we don't loop forever */
303 lock_ObtainRead(&buf_globalLock);
307 lock_ReleaseMutex(&bp->mx);
308 } /* for loop over a bunch of buffers */
309 lock_ReleaseRead(&buf_globalLock);
314 /* incremental sync daemon. Writes all dirty buffers every 5000 ms */
316 buf_IncrSyncer(void * parm)
321 while (buf_ShutdownFlag == 0) {
323 i = SleepEx(5000, 1);
330 wasDirty = buf_Sync(1);
331 } /* whole daemon's while loop */
338 buf_ValidateBuffers(void)
340 cm_buf_t * bp, *bpf, *bpa, *bpb;
341 afs_uint64 countb = 0, countf = 0, counta = 0, countr = 0;
343 if (cm_data.buf_freeListp == NULL && cm_data.buf_freeListEndp != NULL ||
344 cm_data.buf_freeListp != NULL && cm_data.buf_freeListEndp == NULL) {
345 afsi_log("cm_ValidateBuffers failure: inconsistent free list pointers");
346 fprintf(stderr, "cm_ValidateBuffers failure: inconsistent free list pointers\n");
350 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
352 if ( bp < (cm_buf_t *)cm_data.bufHeaderBaseAddress ||
353 bp >= (cm_buf_t *)cm_data.bufDataBaseAddress) {
354 afsi_log("cm_ValidateBuffers failure: out of range cm_buf_t pointers");
355 fprintf(stderr, "cm_ValidateBuffers failure: out of range cm_buf_t pointers\n");
359 if (bp->magic != CM_BUF_MAGIC) {
360 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
361 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
367 if (countb > cm_data.buf_nbuffers) {
368 afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
369 fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
374 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
376 if ( bp < (cm_buf_t *)cm_data.bufHeaderBaseAddress ||
377 bp >= (cm_buf_t *)cm_data.bufDataBaseAddress) {
378 afsi_log("cm_ValidateBuffers failure: out of range cm_buf_t pointers");
379 fprintf(stderr, "cm_ValidateBuffers failure: out of range cm_buf_t pointers\n");
383 if (bp->magic != CM_BUF_MAGIC) {
384 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
385 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
391 if (countf > cm_data.buf_nbuffers) {
392 afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
393 fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
398 for ( bp = cm_data.buf_redirListp; bp; bp = (cm_buf_t *) osi_QNext(&bp->q)) {
400 if ( bp < (cm_buf_t *)cm_data.bufHeaderBaseAddress ||
401 bp >= (cm_buf_t *)cm_data.bufDataBaseAddress) {
402 afsi_log("cm_ValidateBuffers failure: out of range cm_buf_t pointers");
403 fprintf(stderr, "cm_ValidateBuffers failure: out of range cm_buf_t pointers\n");
407 if (!(bp->qFlags & CM_BUF_QREDIR)) {
408 afsi_log("CM_BUF_QREDIR not set on cm_buf_t in buf_redirListp");
409 fprintf(stderr, "CM_BUF_QREDIR not set on cm_buf_t in buf_redirListp");
413 if (countr > cm_data.buf_nbuffers) {
414 afsi_log("cm_ValidateBuffers failure: countr > cm_data.buf_nbuffers");
415 fprintf(stderr, "cm_ValidateBuffers failure: countr > cm_data.buf_nbuffers\n");
420 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
422 if ( bp < (cm_buf_t *)cm_data.bufHeaderBaseAddress ||
423 bp >= (cm_buf_t *)cm_data.bufDataBaseAddress) {
424 afsi_log("cm_ValidateBuffers failure: out of range cm_buf_t pointers");
425 fprintf(stderr, "cm_ValidateBuffers failure: out of range cm_buf_t pointers\n");
429 if (bp->magic != CM_BUF_MAGIC) {
430 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
431 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
435 if ( bp->datap < cm_data.bufDataBaseAddress ||
436 bp->datap >= cm_data.bufEndOfData) {
437 afsi_log("cm_ValidateBuffers failure: out of range data pointers");
438 fprintf(stderr, "cm_ValidateBuffers failure: out of range data pointers\n");
445 if (counta > cm_data.buf_nbuffers) {
446 afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
447 fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
452 if (countb != countf) {
453 afsi_log("cm_ValidateBuffers failure: countb != countf");
454 fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
458 if (counta != cm_data.buf_nbuffers) {
459 afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
460 fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
467 void buf_Shutdown(void)
469 /* disable the buf_IncrSyncer() threads */
470 buf_ShutdownFlag = 1;
472 /* then force all dirty buffers to the file servers */
476 /* initialize the buffer package; called with no locks
477 * held during the initialization phase.
479 long buf_Init(int newFile, cm_buf_ops_t *opsp, afs_uint64 nbuffers)
481 static osi_once_t once;
484 pthread_attr_t tattr;
491 cm_data.buf_nbuffers = nbuffers;
493 /* Have to be able to reserve a whole chunk */
494 if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
495 return CM_ERROR_TOOFEWBUFS;
498 /* recall for callouts */
501 if (osi_Once(&once)) {
502 /* initialize global locks */
503 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock", LOCK_HIERARCHY_BUF_GLOBAL);
504 lock_InitializeMutex(&buf_rdrReleaseExtentsLock, "RDR Release Extents lock", LOCK_HIERARCHY_RDR_EXTENTS);
507 /* remember this for those who want to reset it */
508 cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
510 /* lower hash size to a prime number */
511 cm_data.buf_hashSize = cm_NextHighestPowerOf2((afs_uint32)(cm_data.buf_nbuffers/7));
513 /* create hash table */
514 memset((void *)cm_data.buf_scacheHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
516 /* another hash table */
517 memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
519 /* create buffer headers and put in free list */
520 bp = cm_data.bufHeaderBaseAddress;
521 data = cm_data.bufDataBaseAddress;
522 cm_data.buf_allp = NULL;
524 for (i=0; i<cm_data.buf_nbuffers; i++) {
525 osi_assertx(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress,
526 "invalid cm_buf_t address");
527 osi_assertx(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData,
528 "invalid cm_buf_t data address");
530 /* allocate and zero some storage */
531 memset(bp, 0, sizeof(cm_buf_t));
532 bp->magic = CM_BUF_MAGIC;
533 /* thread on list of all buffers */
534 bp->allp = cm_data.buf_allp;
535 cm_data.buf_allp = bp;
537 osi_QAddH( (osi_queue_t **) &cm_data.buf_freeListp,
538 (osi_queue_t **) &cm_data.buf_freeListEndp,
540 _InterlockedOr(&bp->qFlags, CM_BUF_QINLRU);
541 buf_IncrementFreeCount();
542 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
544 /* grab appropriate number of bytes from aligned zone */
549 data += cm_data.buf_blockSize;
552 /* none reserved at first */
553 cm_data.buf_reservedBufs = 0;
555 /* just for safety's sake */
556 cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
558 bp = cm_data.bufHeaderBaseAddress;
559 data = cm_data.bufDataBaseAddress;
561 lock_ObtainWrite(&buf_globalLock);
562 for (i=0; i<cm_data.buf_nbuffers; i++) {
563 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
566 bp->waitRequests = 0;
567 _InterlockedAnd(&bp->flags, ~CM_BUF_WAITING);
569 if (bp->qFlags & CM_BUF_QREDIR) {
571 * extent was not returned by the file system driver.
574 buf_RemoveFromRedirQueue(NULL, bp);
575 bp->dataVersion = CM_BUF_VERSION_BAD;
576 bp->redirq.nextp = bp->redirq.prevp = NULL;
577 bp->redirLastAccess = 0;
578 bp->redirReleaseRequested = 0;
579 buf_ReleaseLocked(bp, TRUE);
580 buf_DecrementUsedCount();
586 * There should be nothing left in cm_data.buf_redirListp
587 * but double check just to be sure.
589 for ( bp = cm_data.buf_redirListp;
591 bp = cm_data.buf_redirListp)
594 * extent was not returned by the file system driver.
597 buf_RemoveFromRedirQueue(NULL, bp);
598 bp->dataVersion = CM_BUF_VERSION_BAD;
599 bp->redirq.nextp = bp->redirq.prevp = NULL;
600 bp->redirLastAccess = 0;
601 bp->redirReleaseRequested = 0;
602 buf_ReleaseLocked(bp, TRUE);
603 buf_DecrementUsedCount();
605 lock_ReleaseWrite(&buf_globalLock);
609 buf_ValidateBufQueues();
613 /* init the buffer trace log */
614 buf_logp = osi_LogCreate("buffer", 1000);
615 osi_LogEnable(buf_logp);
620 /* and create the incr-syncer */
621 pthread_attr_init(&tattr);
622 pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
624 pstatus = pthread_create(&phandle, &tattr, buf_IncrSyncer, 0);
625 osi_assertx(pstatus == 0, "buf: can't create incremental sync proc");
627 pthread_attr_destroy(&tattr);
631 buf_ValidateBufQueues();
636 /* add nbuffers to the buffer pool, if possible.
637 * Called with no locks held.
639 long buf_AddBuffers(afs_uint64 nbuffers)
641 /* The size of a virtual cache cannot be changed after it has
642 * been created. Subsequent calls to MapViewofFile() with
643 * an existing mapping object name would not allow the
644 * object to be resized. Return failure immediately.
646 * A similar problem now occurs with the persistent cache
647 * given that the memory mapped file now contains a complex
650 afsi_log("request to add %d buffers to the existing cache of size %d denied",
651 nbuffers, cm_data.buf_nbuffers);
653 return CM_ERROR_INVAL;
656 /* interface to set the number of buffers to an exact figure.
657 * Called with no locks held.
659 long buf_SetNBuffers(afs_uint64 nbuffers)
662 return CM_ERROR_INVAL;
663 if (nbuffers == cm_data.buf_nbuffers)
665 else if (nbuffers > cm_data.buf_nbuffers)
666 return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
668 return CM_ERROR_INVAL;
671 /* wait for reading or writing to clear; called with write-locked
672 * buffer and unlocked scp and returns with locked buffer.
674 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
679 osi_assertx(scp->magic == CM_SCACHE_MAGIC, "invalid cm_scache_t magic");
680 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
683 /* if no IO is happening, we're done */
684 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
687 /* otherwise I/O is happening, but some other thread is waiting for
688 * the I/O already. Wait for that guy to figure out what happened,
689 * and then check again.
691 if ( bp->flags & CM_BUF_WAITING ) {
694 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%p", bp);
696 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%p", bp);
697 _InterlockedOr(&bp->flags, CM_BUF_WAITING);
698 bp->waitCount = bp->waitRequests = 1;
700 osi_SleepM((LONG_PTR)bp, &bp->mx);
702 cm_UpdateServerPriority();
704 lock_ObtainMutex(&bp->mx);
705 osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%p", bp);
707 if (bp->waitCount == 0) {
708 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%p", bp);
709 _InterlockedAnd(&bp->flags, ~CM_BUF_WAITING);
710 bp->waitRequests = 0;
714 if (scp = cm_FindSCache(&bp->fid))
718 lock_ObtainRead(&scp->rw);
719 if (!osi_QIsEmpty(&scp->waitQueueH)) {
720 osi_Log1(buf_logp, "buf_WaitIO waking scp 0x%p", scp);
721 osi_Wakeup((LONG_PTR)&scp->flags);
723 lock_ReleaseRead(&scp->rw);
727 /* if we get here, the IO is done, but we may have to wakeup people waiting for
728 * the I/O to complete. Do so.
730 if (bp->flags & CM_BUF_WAITING) {
731 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
732 osi_Wakeup((LONG_PTR) bp);
734 osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%p", bp);
737 cm_ReleaseSCache(scp);
740 /* find a buffer, if any, for a particular file ID and offset. Assumes
741 * that buf_globalLock is write locked when called.
743 cm_buf_t *buf_FindLocked(struct cm_fid *fidp, osi_hyper_t *offsetp)
748 lock_AssertAny(&buf_globalLock);
750 i = BUF_HASH(fidp, offsetp);
751 for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp) {
752 if (cm_FidCmp(fidp, &bp->fid) == 0
753 && offsetp->LowPart == bp->offset.LowPart
754 && offsetp->HighPart == bp->offset.HighPart) {
760 /* return whatever we found, if anything */
764 /* find a buffer with offset *offsetp for vnode *scp. Called
765 * with no locks held.
767 cm_buf_t *buf_Find(struct cm_fid *fidp, osi_hyper_t *offsetp)
771 lock_ObtainRead(&buf_globalLock);
772 bp = buf_FindLocked(fidp, offsetp);
773 lock_ReleaseRead(&buf_globalLock);
778 /* find a buffer, if any, for a particular file ID and offset. Assumes
779 * that buf_globalLock is write locked when called. Uses the all buffer
782 cm_buf_t *buf_FindAllLocked(struct cm_fid *fidp, osi_hyper_t *offsetp, afs_uint32 flags)
787 for(bp = cm_data.buf_allp; bp; bp=bp->allp) {
788 if (cm_FidCmp(fidp, &bp->fid) == 0
789 && offsetp->LowPart == bp->offset.LowPart
790 && offsetp->HighPart == bp->offset.HighPart) {
796 for(bp = cm_data.buf_allp; bp; bp=bp->allp) {
797 if (cm_FidCmp(fidp, &bp->fid) == 0) {
800 fileOffset = offsetp->QuadPart + cm_data.baseAddress;
801 if (fileOffset == bp->datap) {
808 /* return whatever we found, if anything */
812 /* find a buffer with offset *offsetp for vnode *scp. Called
813 * with no locks held. Use the all buffer list.
815 cm_buf_t *buf_FindAll(struct cm_fid *fidp, osi_hyper_t *offsetp, afs_uint32 flags)
819 lock_ObtainRead(&buf_globalLock);
820 bp = buf_FindAllLocked(fidp, offsetp, flags);
821 lock_ReleaseRead(&buf_globalLock);
826 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
829 * Makes sure that there's only one person writing this block
830 * at any given time, and also ensures that the log is forced sufficiently far,
831 * if this buffer contains logged data.
833 * Returns non-zero if the buffer was dirty.
835 * 'scp' may or may not be NULL. If it is not NULL, the FID for both cm_scache_t
836 * and cm_buf_t must match.
838 afs_uint32 buf_CleanLocked(cm_scache_t *scp, cm_buf_t *bp, cm_req_t *reqp,
839 afs_uint32 flags, afs_uint32 *pisdirty)
842 afs_uint32 isdirty = 0;
846 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
847 osi_assertx(scp == NULL || cm_FidCmp(&scp->fid, &bp->fid) == 0, "scp fid != bp fid");
850 * If the matching cm_scache_t was not provided as a parameter
851 * we must either find one or allocate a new one. It is possible
852 * that the cm_scache_t was recycled out of the cache even though
853 * a cm_buf_t with the same FID is in the cache.
856 cm_GetSCache(&bp->fid, NULL, &scp,
857 bp->userp ? bp->userp : cm_rootUserp,
862 if (scp->flags & CM_SCACHEFLAG_DELETED) {
863 code = CM_ERROR_NOSUCHFILE;
865 lock_ObtainWrite(&scp->rw);
866 code = cm_SyncOp(scp, NULL, bp->userp ? bp->userp : cm_rootUserp, reqp, 0,
867 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
869 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
871 lock_ReleaseWrite(&scp->rw);
875 if (scp && (scp->flags & CM_SCACHEFLAG_DELETED)) {
876 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
877 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
878 bp->dirty_length = 0;
880 bp->dataVersion = CM_BUF_VERSION_BAD;
882 buf_DecrementUsedCount();
885 while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
887 lock_ReleaseMutex(&bp->mx);
891 * If we didn't find a cm_scache_t object for bp->fid it means
892 * that we no longer have that FID in the cache. It does not
893 * mean that the object does not exist in the cell. That may
894 * in fact be the case but we don't know that until we attempt
895 * a FetchStatus on the FID.
897 osi_Log1(buf_logp, "buf_CleanLocked unable to start I/O - scp not found buf 0x%p", bp);
898 code = CM_ERROR_NOSUCHFILE;
900 osi_Log2(buf_logp, "buf_CleanLocked starts I/O on scp 0x%p buf 0x%p", scp, bp);
903 LargeIntegerAdd(offset, ConvertLongToLargeInteger(bp->dirty_offset));
905 * Only specify the dirty length of the current buffer in the call
906 * to cm_BufWrite(). It is the responsibility of cm_BufWrite()
907 * to determine if it is appropriate to fill a full chunk of data
908 * when storing to the file server.
910 code = (*cm_buf_opsp->Writep)(scp, &offset, bp->dirty_length, flags,
911 bp->userp ? bp->userp : cm_rootUserp, reqp);
912 osi_Log3(buf_logp, "buf_CleanLocked I/O on scp 0x%p buf 0x%p, done=%d", scp, bp, code);
914 lock_ObtainMutex(&bp->mx);
915 /* if the Write routine returns No Such File, clear the dirty flag
916 * because we aren't going to be able to write this data to the file
919 if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BADFD || code == CM_ERROR_NOACCESS ||
920 code == CM_ERROR_QUOTA || code == CM_ERROR_SPACE || code == CM_ERROR_TOOBIG ||
921 code == CM_ERROR_READONLY || code == CM_ERROR_NOSUCHPATH || code == EIO ||
922 code == CM_ERROR_INVAL || code == CM_ERROR_INVAL_NET_RESP || code == CM_ERROR_UNKNOWN){
923 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
924 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
925 bp->dirty_length = 0;
927 bp->dataVersion = CM_BUF_VERSION_BAD;
929 buf_DecrementUsedCount();
934 /* Disk cache support */
935 /* write buffer to disk cache (synchronous for now) */
936 diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
937 #endif /* DISKCACHE95 */
939 /* if we get here and retries are not permitted
940 * then we need to exit this loop regardless of
941 * whether or not we were able to clear the dirty bit
943 if (reqp->flags & CM_REQ_NORETRY)
947 * Ditto if the hardDeadTimeout or idleTimeout was reached
948 * Or a fatal error is received.
950 if (code == CM_ERROR_TIMEDOUT || code == CM_ERROR_ALLDOWN ||
951 code == CM_ERROR_ALLBUSY || code == CM_ERROR_ALLOFFLINE ||
952 code == CM_ERROR_CLOCKSKEW || code == CM_ERROR_INVAL_NET_RESP ||
953 code == CM_ERROR_INVAL || code == CM_ERROR_UNKNOWN || code == EIO) {
959 cm_ReleaseSCache(scp);
961 /* if someone was waiting for the I/O that just completed or failed,
964 if (bp->flags & CM_BUF_WAITING) {
965 /* turn off flags and wakeup users */
966 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
967 osi_Wakeup((LONG_PTR) bp);
976 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
977 * recycles the buffer, and leaves it ready for reuse with a ref count of 0.
978 * The buffer must already be clean, and no I/O should be happening to it.
980 void buf_Recycle(cm_buf_t *bp)
985 cm_buf_t *prevBp, *nextBp;
987 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
989 osi_assertx(!(bp->qFlags & CM_BUF_QREDIR), "can't recycle redir held buffers");
991 /* if we get here, we know that the buffer still has a 0 ref count,
992 * and that it is clean and has no currently pending I/O. This is
993 * the dude to return.
994 * Remember that as long as the ref count is 0, we know that we won't
995 * have any lock conflicts, so we can grab the buffer lock out of
996 * order in the locking hierarchy.
998 osi_Log3( buf_logp, "buf_Recycle recycles 0x%p, off 0x%x:%08x",
999 bp, bp->offset.HighPart, bp->offset.LowPart);
1001 osi_assertx(bp->refCount == 0, "cm_buf_t refcount != 0");
1002 osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)),
1003 "incorrect cm_buf_t flags");
1004 lock_AssertWrite(&buf_globalLock);
1006 if (bp->qFlags & CM_BUF_QINHASH) {
1007 /* Remove from hash */
1009 i = BUF_HASH(&bp->fid, &bp->offset);
1010 lbpp = &(cm_data.buf_scacheHashTablepp[i]);
1011 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = tbp->hashp) {
1016 /* we better find it */
1017 osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
1019 *lbpp = bp->hashp; /* hash out */
1022 /* Remove from file hash */
1024 i = BUF_FILEHASH(&bp->fid);
1025 prevBp = bp->fileHashBackp;
1026 bp->fileHashBackp = NULL;
1027 nextBp = bp->fileHashp;
1028 bp->fileHashp = NULL;
1030 prevBp->fileHashp = nextBp;
1032 cm_data.buf_fileHashTablepp[i] = nextBp;
1034 nextBp->fileHashBackp = prevBp;
1036 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINHASH);
1039 /* make the fid unrecognizable */
1040 memset(&bp->fid, 0, sizeof(cm_fid_t));
1042 /* clean up junk flags */
1043 _InterlockedAnd(&bp->flags, ~(CM_BUF_EOF | CM_BUF_ERROR));
1044 bp->dataVersion = CM_BUF_VERSION_BAD; /* unknown so far */
1049 * buf_RDRShakeAnExtentFree
1050 * called with buf_globalLock read locked
1053 buf_RDRShakeAnExtentFree(cm_buf_t *rbp, cm_req_t *reqp)
1055 afs_uint32 code = 0;
1056 LARGE_INTEGER heldExtents = {0,0};
1057 AFSFileExtentCB extentList[1];
1058 DWORD extentCount = 0;
1059 BOOL locked = FALSE;
1061 if (!(rbp->qFlags & CM_BUF_QREDIR))
1064 lock_ReleaseRead(&buf_globalLock);
1066 if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
1067 osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
1068 if (reqp->flags & CM_REQ_NORETRY) {
1069 code = CM_ERROR_WOULDBLOCK;
1073 lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1076 extentList[0].Flags = 0;
1077 extentList[0].Length = cm_data.blockSize;
1078 extentList[0].FileOffset.QuadPart = rbp->offset.QuadPart;
1079 extentList[0].CacheOffset.QuadPart = rbp->datap - cm_data.baseAddress;
1082 code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1084 lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1087 lock_ObtainRead(&buf_globalLock);
1092 * buf_RDRShakeFileExtentsFree
1093 * requests all extents held by the redirector to be returned for
1094 * the specified cm_scache_t. This function is called with no
1098 buf_RDRShakeFileExtentsFree(cm_scache_t *rscp, cm_req_t *reqp)
1100 afs_uint32 code = 0;
1101 afs_uint64 n_redir = 0;
1103 if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
1104 osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
1105 if (reqp->flags & CM_REQ_NORETRY)
1106 return CM_ERROR_WOULDBLOCK;
1108 lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1111 for ( code = CM_ERROR_RETRY; code == CM_ERROR_RETRY; ) {
1112 LARGE_INTEGER heldExtents = {0,0};
1113 AFSFileExtentCB extentList[1024];
1114 DWORD extentCount = 0;
1118 /* only retry if a call to RDR_RequestExtentRelease says to */
1120 lock_ObtainWrite(&buf_globalLock);
1122 if (rscp->redirBufCount == 0)
1124 lock_ReleaseWrite(&buf_globalLock);
1129 for ( srbp = redirq_to_cm_buf_t(rscp->redirQueueT);
1131 srbp = ((code == 0 && extentCount == 0) ? redirq_to_cm_buf_t(rscp->redirQueueT) :
1132 redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq))))
1134 extentList[extentCount].Flags = 0;
1135 extentList[extentCount].Length = cm_data.blockSize;
1136 extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1137 extentList[extentCount].CacheOffset.QuadPart = srbp->datap - cm_data.baseAddress;
1138 srbp->redirReleaseRequested = now;
1141 if (extentCount == 1024) {
1142 lock_ReleaseWrite(&buf_globalLock);
1143 heldExtents.QuadPart = cm_data.buf_redirCount;
1144 code = RDR_RequestExtentRelease(&rscp->fid, heldExtents, extentCount, extentList);
1146 if (code == CM_ERROR_RETRY) {
1148 * The redirector either is not holding the extents or cannot let them
1149 * go because they are otherwise in use. At the moment, do nothing.
1155 lock_ObtainWrite(&buf_globalLock);
1158 lock_ReleaseWrite(&buf_globalLock);
1160 if (code == 0 && extentCount > 0) {
1161 heldExtents.QuadPart = cm_data.buf_redirCount;
1162 code = RDR_RequestExtentRelease(&rscp->fid, heldExtents, extentCount, extentList);
1165 if ((code == CM_ERROR_RETRY) && (reqp->flags & CM_REQ_NORETRY)) {
1166 code = CM_ERROR_WOULDBLOCK;
1170 lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1175 buf_RDRShakeSomeExtentsFree(cm_req_t *reqp, afs_uint32 oneFid, afs_uint32 minage)
1177 afs_uint32 code = 0;
1179 if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
1180 if (reqp->flags & CM_REQ_NORETRY)
1181 return CM_ERROR_WOULDBLOCK;
1183 osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
1184 lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1187 for ( code = CM_ERROR_RETRY; code == CM_ERROR_RETRY; ) {
1188 LARGE_INTEGER heldExtents;
1189 AFSFileExtentCB extentList[1024];
1190 DWORD extentCount = 0;
1191 cm_buf_t *rbp, *srbp;
1194 BOOL locked = FALSE;
1196 /* only retry if a call to RDR_RequestExtentRelease says to */
1198 lock_ObtainWrite(&buf_globalLock);
1201 for ( rbp = cm_data.buf_redirListEndp;
1202 code == 0 && rbp && (!oneFid || extentCount == 0);
1203 rbp = (cm_buf_t *) osi_QPrev(&rbp->q))
1208 if (rbp->redirLastAccess >= rbp->redirReleaseRequested) {
1209 rscp = cm_FindSCache(&rbp->fid);
1214 for ( srbp = redirq_to_cm_buf_t(rscp->redirQueueT);
1215 srbp && extentCount < 1024;
1216 srbp = redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq)))
1219 * Do not request a release if we have already done so
1220 * or if the extent was delivered to windows less than
1221 * 'minage' seconds ago.
1223 if (srbp->redirLastAccess >= srbp->redirReleaseRequested &&
1224 srbp->redirLastAccess < now - minage) {
1225 extentList[extentCount].Flags = 0;
1226 extentList[extentCount].Length = cm_data.blockSize;
1227 extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1228 extentList[extentCount].CacheOffset.QuadPart = srbp->datap - cm_data.baseAddress;
1229 srbp->redirReleaseRequested = now;
1233 cm_ReleaseSCache(rscp);
1236 if ( !oneFid && extentCount > 0) {
1238 lock_ReleaseWrite(&buf_globalLock);
1241 heldExtents.QuadPart = cm_data.buf_redirCount;
1242 code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1245 lock_ObtainWrite(&buf_globalLock);
1250 lock_ReleaseWrite(&buf_globalLock);
1253 heldExtents.QuadPart = cm_data.buf_redirCount;
1254 if (rbp && extentCount)
1255 code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1257 code = RDR_RequestExtentRelease(NULL, heldExtents, 1024, NULL);
1263 if ((code == CM_ERROR_RETRY) && (reqp->flags & CM_REQ_NORETRY)) {
1264 code = CM_ERROR_WOULDBLOCK;
1268 lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1272 /* returns 0 if the buffer does not exist, and non-0 if it does */
1274 buf_ExistsLocked(struct cm_scache *scp, osi_hyper_t *offsetp)
1278 if (bp = buf_FindLocked(&scp->fid, offsetp)) {
1279 /* Do not call buf_ReleaseLocked() because we
1280 * do not want to allow the buffer to be added
1283 afs_int32 refCount = InterlockedDecrement(&bp->refCount);
1284 #ifdef DEBUG_REFCOUNT
1285 osi_Log2(afsd_logp,"buf_ExistsLocked bp 0x%p ref %d", bp, refCount);
1286 afsi_log("%s:%d buf_ExistsLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, refCount);
1288 return CM_BUF_EXISTS;
1294 /* recycle a buffer, removing it from the free list, hashing in its new identity
1295 * and returning it write-locked so that no one can use it. Called without
1296 * any locks held, and can return an error if it loses the race condition and
1297 * finds that someone else created the desired buffer.
1299 * If success is returned, the buffer is returned write-locked.
1301 * May be called with null scp and offsetp, if we're just trying to reclaim some
1302 * space from the buffer pool. In that case, the buffer will be returned
1303 * without being hashed into the hash table.
1305 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp,
1306 afs_uint32 flags, cm_buf_t **bufpp)
1308 cm_buf_t *bp; /* buffer we're dealing with */
1309 cm_buf_t *nextBp; /* next buffer in file hash chain */
1310 afs_uint32 i; /* temp */
1311 afs_uint64 n_bufs, n_nonzero, n_busy, n_dirty, n_own, n_redir;
1312 int bufCreateLocked = !!(flags & BUF_GET_FLAG_BUFCREATE_LOCKED);
1315 buf_ValidateBufQueues();
1316 #endif /* TESTING */
1327 if (!bufCreateLocked)
1328 lock_ObtainRead(&scp->bufCreateLock);
1329 lock_ObtainWrite(&buf_globalLock);
1330 /* check to see if we lost the race */
1331 if (buf_ExistsLocked(scp, offsetp)) {
1332 lock_ReleaseWrite(&buf_globalLock);
1333 if (!bufCreateLocked)
1334 lock_ReleaseRead(&scp->bufCreateLock);
1335 return CM_BUF_EXISTS;
1338 /* does this fix the problem below? it's a simple solution. */
1339 if (!cm_data.buf_freeListEndp)
1341 lock_ReleaseWrite(&buf_globalLock);
1342 if (!bufCreateLocked)
1343 lock_ReleaseRead(&scp->bufCreateLock);
1345 if ( RDR_Initialized )
1348 osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List is empty - sleeping 200ms");
1353 /* for debugging, assert free list isn't empty, although we
1354 * really should try waiting for a running tranasction to finish
1355 * instead of this; or better, we should have a transaction
1356 * throttler prevent us from entering this situation.
1358 osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
1360 /* look at all buffers in free list, some of which may temp.
1361 * have high refcounts and which then should be skipped,
1362 * starting cleaning I/O for those which are dirty. If we find
1363 * a clean buffer, we rehash it, lock it and return it.
1365 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1371 /* check to see if it really has zero ref count. This
1372 * code can bump refcounts, at least, so it may not be
1375 if (bp->refCount > 0) {
1380 /* we don't have to lock buffer itself, since the ref
1381 * count is 0 and we know it will stay zero as long as
1382 * we hold the global lock.
1385 /* don't recycle someone in our own chunk */
1386 if (!cm_FidCmp(&bp->fid, &scp->fid) &&
1387 bp->dataVersion >= scp->bufDataVersionLow &&
1388 bp->dataVersion <= scp->dataVersion &&
1389 (bp->offset.LowPart & (-cm_chunkSize)) == (offsetp->LowPart & (-cm_chunkSize))) {
1394 /* if this page is being filled (!) or cleaned, see if
1395 * the I/O has completed. If not, skip it, otherwise
1396 * do the final processing for the I/O.
1398 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
1399 /* probably shouldn't do this much work while
1400 * holding the big lock? Watch for contention
1407 /* leave the buffer alone if held by the redirector */
1408 if (bp->qFlags & CM_BUF_QREDIR) {
1413 if (bp->flags & CM_BUF_DIRTY) {
1416 /* protect against cleaning the same buffer more than once. */
1420 /* if the buffer is dirty, start cleaning it and
1421 * move on to the next buffer. We do this with
1422 * just the lock required to minimize contention
1426 lock_ReleaseWrite(&buf_globalLock);
1427 if (!bufCreateLocked)
1428 lock_ReleaseRead(&scp->bufCreateLock);
1431 * grab required lock and clean.
1432 * previously the claim was that the cleaning
1433 * operation was async which it is not. It would
1434 * be a good idea to use an async mechanism here
1435 * but there is none at the moment other than
1436 * the buf_IncrSyncer() thread.
1438 if (cm_FidCmp(&scp->fid, &bp->fid) == 0)
1439 buf_Clean(scp, bp, reqp, 0, NULL);
1441 buf_Clean(NULL, bp, reqp, 0, NULL);
1443 /* now put it back and go around again */
1446 /* but first obtain the locks we gave up
1447 * before the buf_CleanAsync() call */
1448 if (!bufCreateLocked)
1449 lock_ObtainRead(&scp->bufCreateLock);
1450 lock_ObtainWrite(&buf_globalLock);
1453 * Since we dropped the locks we need to verify that
1454 * another thread has not allocated the buffer for us.
1456 if (buf_ExistsLocked(scp, offsetp)) {
1457 lock_ReleaseWrite(&buf_globalLock);
1458 if (!bufCreateLocked)
1459 lock_ReleaseRead(&scp->bufCreateLock);
1460 return CM_BUF_EXISTS;
1464 * We just cleaned this buffer so we need to
1465 * restart the loop with this buffer so it
1466 * can be retested. Set 'cleaned' so we
1467 * do not attempt another call to buf_Clean()
1468 * if the prior attempt failed.
1474 osi_Log3(afsd_logp, "buf_GetNewLocked: scp 0x%p examined %u buffers before recycling bufp 0x%p",
1476 osi_Log4(afsd_logp, "... nonzero %u; own %u; busy %u; dirty %u", n_nonzero, n_own, n_busy, n_dirty);
1478 /* if we get here, we know that the buffer still has a 0
1479 * ref count, and that it is clean and has no currently
1480 * pending I/O. This is the dude to return.
1481 * Remember that as long as the ref count is 0, we know
1482 * that we won't have any lock conflicts, so we can grab
1483 * the buffer lock out of order in the locking hierarchy.
1487 /* now hash in as our new buffer, and give it the
1488 * appropriate label, if requested.
1491 lock_AssertWrite(&buf_globalLock);
1493 _InterlockedOr(&bp->qFlags, CM_BUF_QINHASH);
1498 bp->offset = *offsetp;
1499 i = BUF_HASH(&scp->fid, offsetp);
1500 bp->hashp = cm_data.buf_scacheHashTablepp[i];
1501 cm_data.buf_scacheHashTablepp[i] = bp;
1502 i = BUF_FILEHASH(&scp->fid);
1503 nextBp = cm_data.buf_fileHashTablepp[i];
1504 bp->fileHashp = nextBp;
1505 bp->fileHashBackp = NULL;
1507 nextBp->fileHashBackp = bp;
1508 cm_data.buf_fileHashTablepp[i] = bp;
1511 /* we should remove it from the lru queue. It better still be there,
1512 * since we've held the global (big) lock since we found it there.
1514 osi_assertx(bp->qFlags & CM_BUF_QINLRU,
1515 "buf_GetNewLocked: LRU screwup");
1517 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
1518 (osi_queue_t **) &cm_data.buf_freeListEndp,
1520 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINLRU);
1521 buf_DecrementFreeCount();
1523 /* prepare to return it. Give it a refcount */
1524 InterlockedIncrement(&bp->refCount);
1525 #ifdef DEBUG_REFCOUNT
1526 osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, 1);
1527 afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, 1);
1529 /* grab the mutex so that people don't use it
1530 * before the caller fills it with data. Again, no one
1531 * should have been able to get to this dude to lock it.
1533 if (!lock_TryMutex(&bp->mx)) {
1534 osi_Log2(afsd_logp, "buf_GetNewLocked bp 0x%p cannot be mutex locked. refCount %d should be 0",
1536 osi_panic("buf_GetNewLocked: TryMutex failed",__FILE__,__LINE__);
1539 if ( cm_data.buf_usedCount < cm_data.buf_nbuffers)
1540 buf_IncrementUsedCount();
1542 lock_ReleaseWrite(&buf_globalLock);
1543 if (!bufCreateLocked)
1544 lock_ReleaseRead(&scp->bufCreateLock);
1549 buf_ValidateBufQueues();
1550 #endif /* TESTING */
1552 } /* for all buffers in lru queue */
1553 lock_ReleaseWrite(&buf_globalLock);
1554 if (!bufCreateLocked)
1555 lock_ReleaseRead(&scp->bufCreateLock);
1557 osi_Log2(afsd_logp, "buf_GetNewLocked: Free Buffer List has %u buffers none free; redir %u", n_bufs, n_redir);
1558 osi_Log4(afsd_logp, "... nonzero %u; own %u; busy %u; dirty %u", n_nonzero, n_own, n_busy, n_dirty);
1560 if (RDR_Initialized) {
1563 code = buf_RDRShakeSomeExtentsFree(reqp, TRUE, 2 /* seconds */);
1565 case CM_ERROR_RETRY:
1568 case CM_ERROR_WOULDBLOCK:
1569 return CM_ERROR_WOULDBLOCK;
1573 Sleep(100); /* give some time for a buffer to be freed */
1574 } /* while loop over everything */
1579 * get a page, returning it held but unlocked. the page may or may not
1580 * contain valid data.
1582 * The scp must be unlocked when passed in unlocked.
1584 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp, afs_uint32 flags, cm_buf_t **bufpp)
1588 osi_hyper_t pageOffset;
1589 unsigned long tcount;
1593 cm_diskcache_t *dcp;
1594 #endif /* DISKCACHE95 */
1597 pageOffset.HighPart = offsetp->HighPart;
1598 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1602 buf_ValidateBufQueues();
1603 #endif /* TESTING */
1605 bp = buf_Find(&scp->fid, &pageOffset);
1607 /* lock it and break out */
1608 lock_ObtainMutex(&bp->mx);
1611 /* touch disk chunk to update LRU info */
1612 diskcache_Touch(bp->dcp);
1613 #endif /* DISKCACHE95 */
1617 /* otherwise, we have to create a page */
1618 code = buf_GetNewLocked(scp, &pageOffset, reqp, flags, &bp);
1621 /* the requested buffer was created */
1626 * the requested buffer existed by the time the
1627 * scp->bufCreateLock and buf_globalLock could be obtained.
1628 * loop again and permit buf_Find() to obtain a reference.
1633 * the requested buffer could not be created.
1634 * return the error to the caller.
1637 buf_ValidateBufQueues();
1638 #endif /* TESTING */
1641 } /* big while loop */
1643 /* if we get here, we have a locked buffer that may have just been
1644 * created, in which case it needs to be filled with data.
1647 /* load the page; freshly created pages should be idle */
1648 osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)), "incorrect cm_buf_t flags");
1651 * start the I/O; may drop lock. as of this writing, the only
1652 * implementation of Readp is cm_BufRead() which simply sets
1653 * tcount to 0 and returns success.
1655 _InterlockedOr(&bp->flags, CM_BUF_READING);
1656 code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
1659 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
1660 bp->dcp = dcp; /* pointer to disk cache struct. */
1661 #endif /* DISKCACHE95 */
1664 /* failure or queued */
1666 /* unless cm_BufRead() is altered, this path cannot be hit */
1667 if (code != ERROR_IO_PENDING) {
1669 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
1670 _InterlockedAnd(&bp->flags, ~CM_BUF_READING);
1671 if (bp->flags & CM_BUF_WAITING) {
1672 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1673 osi_Wakeup((LONG_PTR) bp);
1675 lock_ReleaseMutex(&bp->mx);
1678 buf_ValidateBufQueues();
1679 #endif /* TESTING */
1684 * otherwise, I/O completed instantly and we're done, except
1685 * for padding the xfr out with 0s and checking for EOF
1687 if (tcount < (unsigned long) cm_data.buf_blockSize) {
1688 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
1690 _InterlockedOr(&bp->flags, CM_BUF_EOF);
1692 _InterlockedAnd(&bp->flags, ~CM_BUF_READING);
1693 if (bp->flags & CM_BUF_WAITING) {
1694 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1695 osi_Wakeup((LONG_PTR) bp);
1700 /* wait for reads, either that which we started above, or that someone
1701 * else started. We don't care if we return a buffer being cleaned.
1703 if (bp->flags & CM_BUF_READING)
1704 buf_WaitIO(scp, bp);
1706 /* once it has been read once, we can unlock it and return it, still
1707 * with its refcount held.
1709 lock_ReleaseMutex(&bp->mx);
1712 /* now remove from queue; will be put in at the head (farthest from
1713 * being recycled) when we're done in buf_Release.
1715 lock_ObtainWrite(&buf_globalLock);
1716 if (bp->qFlags & CM_BUF_QINLRU) {
1717 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
1718 (osi_queue_t **) &cm_data.buf_freeListEndp,
1720 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINLRU);
1721 buf_DecrementFreeCount();
1723 lock_ReleaseWrite(&buf_globalLock);
1725 osi_Log4(buf_logp, "buf_Get returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1726 bp, scp, offsetp->HighPart, offsetp->LowPart);
1728 buf_ValidateBufQueues();
1729 #endif /* TESTING */
1733 /* clean a buffer synchronously */
1734 afs_uint32 buf_Clean(cm_scache_t *scp, cm_buf_t *bp, cm_req_t *reqp, afs_uint32 flags, afs_uint32 *pisdirty)
1737 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1738 osi_assertx(!(flags & CM_BUF_WRITE_SCP_LOCKED), "scp->rw must not be held when calling buf_CleanAsync");
1740 lock_ObtainMutex(&bp->mx);
1741 code = buf_CleanLocked(scp, bp, reqp, flags, pisdirty);
1742 lock_ReleaseMutex(&bp->mx);
1747 /* wait for a buffer's cleaning to finish */
1748 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp, afs_uint32 locked)
1750 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1753 lock_ObtainMutex(&bp->mx);
1754 if (bp->flags & CM_BUF_WRITING) {
1755 buf_WaitIO(scp, bp);
1758 lock_ReleaseMutex(&bp->mx);
1761 /* set the dirty flag on a buffer, and set associated write-ahead log,
1762 * if there is one. Allow one to be added to a buffer, but not changed.
1764 * The buffer must be locked before calling this routine.
1766 void buf_SetDirty(cm_buf_t *bp, cm_req_t *reqp, afs_uint32 offset, afs_uint32 length, cm_user_t *userp)
1768 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1769 osi_assertx(bp->refCount > 0, "cm_buf_t refcount 0");
1770 osi_assertx(userp != NULL, "userp is NULL");
1775 if (bp->flags & CM_BUF_DIRTY) {
1777 osi_Log1(buf_logp, "buf_SetDirty 0x%p already dirty", bp);
1779 if (bp->dirty_offset <= offset) {
1780 if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1781 /* dirty_length remains the same */
1783 bp->dirty_length = offset + length - bp->dirty_offset;
1785 } else /* bp->dirty_offset > offset */ {
1786 if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1787 bp->dirty_length = bp->dirty_offset + bp->dirty_length - offset;
1789 bp->dirty_length = length;
1791 bp->dirty_offset = offset;
1794 osi_Log1(buf_logp, "buf_SetDirty 0x%p", bp);
1797 _InterlockedOr(&bp->flags, CM_BUF_DIRTY);
1799 /* and turn off EOF flag, since it has associated data now */
1800 _InterlockedAnd(&bp->flags, ~CM_BUF_EOF);
1802 bp->dirty_offset = offset;
1803 bp->dirty_length = length;
1806 * if the request is not from the afs redirector,
1807 * add to the dirty list. The redirector interface ensures
1808 * that a background store operation is queued for each and
1809 * every dirty extent that is released. Therefore, the
1810 * buf_IncrSyncer thread is not required to ensure that
1811 * dirty buffers are written to the file server.
1813 * we obtain a hold on the buffer for as long as it remains
1814 * in the list. buffers are only removed from the list by
1815 * the buf_IncrSyncer function regardless of when else the
1816 * dirty flag might be cleared.
1818 * This should never happen but just in case there is a bug
1819 * elsewhere, never add to the dirty list if the buffer is
1822 if (!(reqp->flags & CM_REQ_SOURCE_REDIR)) {
1823 lock_ObtainWrite(&buf_globalLock);
1824 if (!(bp->qFlags & CM_BUF_QINDL)) {
1826 if (!cm_data.buf_dirtyListp) {
1827 cm_data.buf_dirtyListp = cm_data.buf_dirtyListEndp = bp;
1829 cm_data.buf_dirtyListEndp->dirtyp = bp;
1830 cm_data.buf_dirtyListEndp = bp;
1833 _InterlockedOr(&bp->qFlags, CM_BUF_QINDL);
1835 lock_ReleaseWrite(&buf_globalLock);
1839 /* and record the last writer */
1840 if (bp->userp != userp) {
1843 cm_ReleaseUser(bp->userp);
1848 /* clean all buffers, reset log pointers and invalidate all buffers.
1849 * Called with no locks held, and returns with same.
1851 * This function is guaranteed to clean and remove the log ptr of all the
1852 * buffers that were dirty or had non-zero log ptrs before the call was
1853 * made. That's sufficient to clean up any garbage left around by recovery,
1854 * which is all we're counting on this for; there may be newly created buffers
1855 * added while we're running, but that should be OK.
1857 * In an environment where there are no transactions (artificially imposed, for
1858 * example, when switching the database to raw mode), this function is used to
1859 * make sure that all updates have been written to the disk. In that case, we don't
1860 * really require that we forget the log association between pages and logs, but
1861 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1862 * have to worry about invalidating data in the buffers.
1864 * This function is used at the end of recovery as paranoia to get the recovered
1865 * database out to disk. It removes all references to the recovery log and cleans
1868 long buf_CleanAndReset(void)
1874 lock_ObtainRead(&buf_globalLock);
1875 for(i=0; i<cm_data.buf_hashSize; i++) {
1876 for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp = bp->hashp) {
1877 if (bp->qFlags & CM_BUF_QREDIR) {
1878 osi_Log1(buf_logp,"buf_CleanAndReset buffer held by redirector bp 0x%p", bp);
1880 /* Request single extent from the redirector */
1881 buf_RDRShakeAnExtentFree(bp, &req);
1884 if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1886 lock_ReleaseRead(&buf_globalLock);
1888 /* now no locks are held; clean buffer and go on */
1890 req.flags |= CM_REQ_NORETRY;
1892 buf_Clean(NULL, bp, &req, 0, NULL);
1893 buf_CleanWait(NULL, bp, FALSE);
1895 /* relock and release buffer */
1896 lock_ObtainRead(&buf_globalLock);
1897 buf_ReleaseLocked(bp, FALSE);
1899 } /* over one bucket */
1900 } /* for loop over all hash buckets */
1903 lock_ReleaseRead(&buf_globalLock);
1906 buf_ValidateBufQueues();
1907 #endif /* TESTING */
1909 /* and we're done */
1913 /* called without global lock being held, reserves buffers for callers
1914 * that need more than one held (not locked) at once.
1916 void buf_ReserveBuffers(afs_uint64 nbuffers)
1918 lock_ObtainWrite(&buf_globalLock);
1920 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1921 cm_data.buf_reserveWaiting = 1;
1922 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1923 osi_SleepW((LONG_PTR) &cm_data.buf_reservedBufs, &buf_globalLock);
1924 lock_ObtainWrite(&buf_globalLock);
1927 cm_data.buf_reservedBufs += nbuffers;
1931 lock_ReleaseWrite(&buf_globalLock);
1935 buf_TryReserveBuffers(afs_uint64 nbuffers)
1937 afs_uint64 reserved;
1939 lock_ObtainWrite(&buf_globalLock);
1940 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1944 cm_data.buf_reservedBufs += nbuffers;
1945 reserved = nbuffers;
1947 lock_ReleaseWrite(&buf_globalLock);
1951 /* called without global lock held, releases reservation held by
1952 * buf_ReserveBuffers.
1954 void buf_UnreserveBuffers(afs_uint64 nbuffers)
1956 lock_ObtainWrite(&buf_globalLock);
1957 cm_data.buf_reservedBufs -= nbuffers;
1958 if (cm_data.buf_reserveWaiting) {
1959 cm_data.buf_reserveWaiting = 0;
1960 osi_Wakeup((LONG_PTR) &cm_data.buf_reservedBufs);
1962 lock_ReleaseWrite(&buf_globalLock);
1965 /* truncate the buffers past sizep, zeroing out the page, if we don't
1966 * end on a page boundary.
1968 * Requires cm_bufCreateLock to be write locked.
1970 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1974 cm_buf_t *nbufp; /* next buffer, if didRelease */
1979 afs_uint32 invalidate = 0;
1981 /* assert that cm_bufCreateLock is held in write mode */
1982 lock_AssertWrite(&scp->bufCreateLock);
1984 i = BUF_FILEHASH(&scp->fid);
1986 lock_ObtainRead(&buf_globalLock);
1987 bufp = cm_data.buf_fileHashTablepp[i];
1989 lock_ReleaseRead(&buf_globalLock);
1993 buf_HoldLocked(bufp);
1994 lock_ReleaseRead(&buf_globalLock);
1997 lock_ObtainMutex(&bufp->mx);
1999 bufEnd.HighPart = 0;
2000 bufEnd.LowPart = cm_data.buf_blockSize;
2001 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
2003 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
2004 LargeIntegerLessThan(*sizep, bufEnd)) {
2005 buf_WaitIO(scp, bufp);
2007 lock_ObtainWrite(&scp->rw);
2009 /* make sure we have a callback (so we have the right value for
2010 * the length), and wait for it to be safe to do a truncate.
2012 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
2013 CM_SCACHESYNC_NEEDCALLBACK
2014 | CM_SCACHESYNC_GETSTATUS
2015 | CM_SCACHESYNC_SETSIZE
2016 | CM_SCACHESYNC_BUFLOCKED);
2019 /* if we succeeded in our locking, and this applies to the right
2020 * file, and the truncate request overlaps the buffer either
2021 * totally or partially, then do something.
2023 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
2024 && LargeIntegerLessThan(*sizep, bufEnd)) {
2027 /* destroy the buffer, turning off its dirty bit, if
2028 * we're truncating the whole buffer. Otherwise, set
2029 * the dirty bit, and clear out the tail of the buffer
2030 * if we just overlap some.
2032 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
2033 /* truncating the entire page */
2034 if (reqp->flags & CM_REQ_SOURCE_REDIR) {
2036 * Implicitly clear the redirector flag
2037 * and release the matching hold.
2039 if (bufp->qFlags & CM_BUF_QREDIR) {
2040 osi_Log4(buf_logp,"buf_Truncate taking from file system bufp 0x%p vno 0x%x foffset 0x%x:%x",
2041 bufp, bufp->fid.vnode, bufp->offset.HighPart, bufp->offset.LowPart);
2042 lock_ObtainWrite(&buf_globalLock);
2043 if (bufp->qFlags & CM_BUF_QREDIR) {
2044 buf_RemoveFromRedirQueue(scp, bufp);
2045 buf_ReleaseLocked(bufp, TRUE);
2047 lock_ReleaseWrite(&buf_globalLock);
2052 _InterlockedAnd(&bufp->flags, ~CM_BUF_DIRTY);
2054 bufp->dirty_length = 0;
2055 bufp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
2056 bufp->dirtyCounter++;
2057 buf_DecrementUsedCount();
2060 /* don't set dirty, since dirty implies
2061 * currently up-to-date. Don't need to do this,
2062 * since we'll update the length anyway.
2064 * Zero out remainder of the page, in case we
2065 * seek and write past EOF, and make this data
2068 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
2069 osi_assertx(bufferPos != 0, "non-zero bufferPos");
2070 memset(bufp->datap + bufferPos, 0,
2071 cm_data.buf_blockSize - bufferPos);
2075 cm_SyncOpDone( scp, bufp,
2076 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2077 | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_BUFLOCKED);
2079 lock_ReleaseWrite(&scp->rw);
2080 lock_ReleaseMutex(&bufp->mx);
2083 nbufp = bufp->fileHashp;
2087 /* This forces the loop to end and the error code
2088 * to be returned. */
2096 buf_ValidateBufQueues();
2097 #endif /* TESTING */
2099 if (invalidate && RDR_Initialized)
2100 RDR_InvalidateObject(scp->fid.cell, scp->fid.volume, scp->fid.vnode,
2101 scp->fid.unique, scp->fid.hash,
2102 scp->fileType, AFS_INVALIDATE_SMB);
2108 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
2111 cm_buf_t *bp; /* buffer we're hacking on */
2115 afs_uint32 stable = 0;
2117 i = BUF_FILEHASH(&scp->fid);
2120 lock_ObtainRead(&buf_globalLock);
2121 bp = cm_data.buf_fileHashTablepp[i];
2124 lock_ReleaseRead(&buf_globalLock);
2126 for (; bp; bp = nbp) {
2127 didRelease = 0; /* haven't released this buffer yet */
2129 /* clean buffer synchronously */
2130 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2132 if (code == 0 && !stable && (bp->flags & CM_BUF_DIRTY)) {
2134 * we must stabilize the object to ensure that buffer
2135 * changes cannot occur while the flush is performed.
2136 * However, we do not want to Stabilize if we do not
2137 * need to because Stabilize obtains a callback.
2139 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
2140 stable = (code == 0);
2143 if (code == CM_ERROR_BADFD) {
2144 /* if the scp's FID is bad its because we received VNOVNODE
2145 * when attempting to FetchStatus before the write. This
2146 * page therefore contains data that can no longer be stored.
2148 lock_ObtainMutex(&bp->mx);
2149 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
2150 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
2151 bp->error = CM_ERROR_BADFD;
2152 bp->dirty_length = 0;
2153 bp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
2155 lock_ReleaseMutex(&bp->mx);
2156 buf_DecrementUsedCount();
2157 } else if (!(scp->flags & CM_SCACHEFLAG_RO)) {
2162 lock_ObtainMutex(&bp->mx);
2164 /* start cleaning the buffer, and wait for it to finish */
2165 buf_CleanLocked(scp, bp, reqp, 0, NULL);
2166 buf_WaitIO(scp, bp);
2168 lock_ReleaseMutex(&bp->mx);
2171 /* actually, we only know that buffer is clean if ref
2172 * count is 1, since we don't have buffer itself locked.
2174 if (!(bp->flags & CM_BUF_DIRTY) && !(bp->qFlags & CM_BUF_QREDIR)) {
2175 lock_ObtainWrite(&buf_globalLock);
2176 if (!(bp->flags & CM_BUF_DIRTY) && !(bp->qFlags & CM_BUF_QREDIR)) {
2177 if (bp->refCount == 1) { /* bp is held above */
2178 nbp = bp->fileHashp;
2180 buf_HoldLocked(nbp);
2181 buf_ReleaseLocked(bp, TRUE);
2183 if (bp->dataVersion != CM_BUF_VERSION_BAD)
2184 buf_DecrementUsedCount();
2188 lock_ReleaseWrite(&buf_globalLock);
2194 lock_ObtainRead(&buf_globalLock);
2195 nbp = bp->fileHashp;
2197 buf_HoldLocked(nbp);
2198 buf_ReleaseLocked(bp, FALSE);
2199 lock_ReleaseRead(&buf_globalLock);
2201 } /* for loop over a bunch of buffers */
2204 (*cm_buf_opsp->Unstabilizep)(scp, userp);
2207 buf_ValidateBufQueues();
2208 #endif /* TESTING */
2214 /* Must be called with scp->rw held */
2215 long buf_InvalidateBuffers(cm_scache_t * scp)
2221 lock_AssertAny(&scp->rw);
2223 i = BUF_FILEHASH(&scp->fid);
2225 lock_ObtainRead(&buf_globalLock);
2227 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp = bp->fileHashp) {
2228 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2229 bp->dataVersion = CM_BUF_VERSION_BAD;
2230 buf_DecrementUsedCount();
2234 lock_ReleaseRead(&buf_globalLock);
2242 /* Must be called with scp->rw held */
2243 long buf_ForceDataVersion(cm_scache_t * scp, afs_uint64 fromVersion, afs_uint64 toVersion)
2249 lock_AssertAny(&scp->rw);
2251 i = BUF_FILEHASH(&scp->fid);
2253 lock_ObtainRead(&buf_globalLock);
2255 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp = bp->fileHashp) {
2256 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2257 if (bp->dataVersion == fromVersion) {
2258 bp->dataVersion = toVersion;
2263 lock_ReleaseRead(&buf_globalLock);
2271 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
2275 cm_buf_t *bp; /* buffer we're hacking on */
2276 cm_buf_t *nbp; /* next one */
2279 if (RDR_Initialized && scp->redirBufCount > 0) {
2280 /* Retrieve all extents for this file from the redirector */
2281 buf_RDRShakeFileExtentsFree(scp, reqp);
2284 i = BUF_FILEHASH(&scp->fid);
2286 lock_ObtainRead(&buf_globalLock);
2287 bp = cm_data.buf_fileHashTablepp[i];
2290 lock_ReleaseRead(&buf_globalLock);
2291 for (; bp; bp = nbp) {
2292 /* clean buffer synchronously */
2293 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2295 * If the buffer is held by the redirector we must fetch
2296 * it back in order to determine whether or not it is in
2299 if (bp->qFlags & CM_BUF_QREDIR) {
2300 lock_ObtainRead(&buf_globalLock);
2301 if (bp->qFlags & CM_BUF_QREDIR) {
2302 osi_Log1(buf_logp,"buf_CleanVnode buffer held by redirector bp 0x%p", bp);
2304 /* Retrieve single extent from the redirector */
2305 buf_RDRShakeAnExtentFree(bp, reqp);
2307 lock_ReleaseRead(&buf_globalLock);
2310 lock_ObtainMutex(&bp->mx);
2311 if ((bp->flags & CM_BUF_DIRTY)) {
2312 if (userp && userp != bp->userp) {
2315 cm_ReleaseUser(bp->userp);
2320 case CM_ERROR_NOSUCHFILE:
2321 case CM_ERROR_INVAL:
2322 case CM_ERROR_BADFD:
2323 case CM_ERROR_NOACCESS:
2324 case CM_ERROR_QUOTA:
2325 case CM_ERROR_SPACE:
2326 case CM_ERROR_TOOBIG:
2327 case CM_ERROR_READONLY:
2328 case CM_ERROR_NOSUCHPATH:
2330 case CM_ERROR_INVAL_NET_RESP:
2331 case CM_ERROR_UNKNOWN:
2333 * Apply the previous fatal error to this buffer.
2334 * Do not waste the time attempting to store to
2335 * the file server when we know it will fail.
2337 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
2338 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
2339 bp->dirty_length = 0;
2341 bp->dataVersion = CM_BUF_VERSION_BAD;
2343 buf_DecrementUsedCount();
2345 case CM_ERROR_TIMEDOUT:
2346 case CM_ERROR_ALLDOWN:
2347 case CM_ERROR_ALLBUSY:
2348 case CM_ERROR_ALLOFFLINE:
2349 case CM_ERROR_CLOCKSKEW:
2350 /* do not mark the buffer in error state but do
2351 * not attempt to complete the rest either.
2355 code = buf_CleanLocked(scp, bp, reqp, 0, &wasDirty);
2356 if (bp->flags & CM_BUF_ERROR) {
2362 buf_CleanWait(scp, bp, TRUE);
2364 lock_ReleaseMutex(&bp->mx);
2367 lock_ObtainRead(&buf_globalLock);
2368 nbp = bp->fileHashp;
2370 buf_HoldLocked(nbp);
2371 buf_ReleaseLocked(bp, FALSE);
2372 lock_ReleaseRead(&buf_globalLock);
2373 } /* for loop over a bunch of buffers */
2376 buf_ValidateBufQueues();
2377 #endif /* TESTING */
2385 buf_ValidateBufQueues(void)
2387 cm_buf_t * bp, *bpb, *bpf, *bpa;
2388 afs_uint32 countf=0, countb=0, counta=0;
2390 lock_ObtainRead(&buf_globalLock);
2391 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
2392 if (bp->magic != CM_BUF_MAGIC)
2393 osi_panic("buf magic error",__FILE__,__LINE__);
2398 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
2399 if (bp->magic != CM_BUF_MAGIC)
2400 osi_panic("buf magic error",__FILE__,__LINE__);
2405 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
2406 if (bp->magic != CM_BUF_MAGIC)
2407 osi_panic("buf magic error",__FILE__,__LINE__);
2411 lock_ReleaseRead(&buf_globalLock);
2413 if (countb != countf)
2414 osi_panic("buf magic error",__FILE__,__LINE__);
2416 if (counta != cm_data.buf_nbuffers)
2417 osi_panic("buf magic error",__FILE__,__LINE__);
2419 #endif /* TESTING */
2421 /* dump the contents of the buf_scacheHashTablepp. */
2422 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
2429 if (cm_data.buf_scacheHashTablepp == NULL)
2433 lock_ObtainRead(&buf_globalLock);
2435 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\r\n",
2436 cookie, cm_data.buf_hashSize);
2437 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2439 for (i = 0; i < cm_data.buf_hashSize; i++)
2441 for (bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp)
2443 StringCbPrintfA(output, sizeof(output),
2444 "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d, "
2445 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2446 "flags=0x%x, qFlags=0x%x cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2447 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
2448 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2449 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2450 bp->cmFlags, bp->error, bp->refCount);
2451 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2455 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\r\n", cookie);
2456 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2458 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_freeListEndp\r\n", cookie);
2459 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2460 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
2461 StringCbPrintfA(output, sizeof(output),
2462 "%s bp=0x%08X, fid (cell=%d, volume=%d, "
2463 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2464 "flags=0x%x, qFlags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2465 cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
2466 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2467 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2468 bp->cmFlags, bp->error, bp->refCount);
2469 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2471 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_FreeListEndp.\r\n", cookie);
2472 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2474 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_dirtyListp\r\n", cookie);
2475 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2476 for(bp = cm_data.buf_dirtyListp; bp; bp=bp->dirtyp) {
2477 StringCbPrintfA(output, sizeof(output),
2478 "%s bp=0x%08X, fid (cell=%d, volume=%d, "
2479 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2480 "flags=0x%x, qFlags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2481 cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
2482 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2483 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2484 bp->cmFlags, bp->error, bp->refCount);
2485 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2487 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_dirtyListp.\r\n", cookie);
2488 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2491 lock_ReleaseRead(&buf_globalLock);
2495 void buf_ForceTrace(BOOL flush)
2504 len = GetTempPath(sizeof(buf)-10, buf);
2505 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
2506 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
2507 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2508 if (handle == INVALID_HANDLE_VALUE) {
2509 osi_panic("Cannot create log file", __FILE__, __LINE__);
2511 osi_LogPrint(buf_logp, handle);
2513 FlushFileBuffers(handle);
2514 CloseHandle(handle);
2517 long buf_DirtyBuffersExist(cm_fid_t *fidp)
2520 afs_uint32 bcount = 0;
2524 i = BUF_FILEHASH(fidp);
2526 lock_ObtainRead(&buf_globalLock);
2527 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2528 if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
2533 lock_ReleaseRead(&buf_globalLock);
2537 long buf_RDRBuffersExist(cm_fid_t *fidp)
2540 afs_uint32 bcount = 0;
2544 if (!RDR_Initialized || cm_directIO)
2547 i = BUF_FILEHASH(fidp);
2549 lock_ObtainRead(&buf_globalLock);
2550 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2551 if (!cm_FidCmp(fidp, &bp->fid) && (bp->qFlags & CM_BUF_QREDIR)) {
2556 lock_ReleaseRead(&buf_globalLock);
2560 long buf_ClearRDRFlag(cm_scache_t *scp, char *reason)
2562 cm_fid_t *fidp = &scp->fid;
2564 afs_uint32 bcount = 0;
2567 if (!RDR_Initialized || cm_directIO)
2570 i = BUF_FILEHASH(fidp);
2572 lock_ObtainWrite(&scp->rw);
2573 lock_ObtainRead(&buf_globalLock);
2574 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2575 if (!cm_FidCmp(fidp, &bp->fid) && (bp->qFlags & CM_BUF_QREDIR)) {
2576 lock_ConvertRToW(&buf_globalLock);
2577 if (bp->qFlags & CM_BUF_QREDIR) {
2578 osi_Log4(buf_logp,"buf_ClearRDRFlag taking from file system bp 0x%p vno 0x%x foffset 0x%x:%x",
2579 bp, bp->fid.vnode, bp->offset.HighPart, bp->offset.LowPart);
2580 buf_RemoveFromRedirQueue(scp, bp);
2581 buf_ReleaseLocked(bp, TRUE);
2583 lock_ConvertWToR(&buf_globalLock);
2587 /* Confirm that there are none left */
2588 lock_ConvertRToW(&buf_globalLock);
2589 for ( bp = redirq_to_cm_buf_t(scp->redirQueueT);
2591 bp = redirq_to_cm_buf_t(scp->redirQueueT))
2593 if (bp->qFlags & CM_BUF_QREDIR) {
2594 osi_Log4(buf_logp,"buf_ClearRDRFlag taking from file system bufp 0x%p vno 0x%x foffset 0x%x:%x",
2595 bp, bp->fid.vnode, bp->offset.HighPart, bp->offset.LowPart);
2596 buf_RemoveFromRedirQueue(scp, bp);
2597 buf_ReleaseLocked(bp, TRUE);
2601 lock_ReleaseWrite(&buf_globalLock);
2602 lock_ReleaseWrite(&scp->rw);
2607 * The following routines will not be used on a
2608 * regular basis but are very useful in a variety
2609 * of scenarios when debugging data corruption.
2612 buf_HexCheckSum(cm_buf_t * bp)
2615 static char buf[33];
2616 static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
2618 for (i=0;i<16;i++) {
2619 k = bp->md5cksum[i];
2621 buf[i*2] = tr[k / 16];
2622 buf[i*2+1] = tr[k % 16];
2630 buf_ComputeCheckSum(cm_buf_t * bp)
2635 MD5_Update(&md5, bp->datap, cm_data.blockSize);
2636 MD5_Final(bp->md5cksum, &md5);
2638 osi_Log4(buf_logp, "CheckSum bp 0x%p md5 %s, dirty: offset %u length %u",
2639 bp, osi_LogSaveString(buf_logp, buf_HexCheckSum(bp)),
2640 bp->dirty_offset, bp->dirty_length);
2644 buf_ValidateCheckSum(cm_buf_t * bp)
2647 unsigned char tmp[16];
2650 MD5_Update(&md5, bp->datap, cm_data.blockSize);
2651 MD5_Final(tmp, &md5);
2653 if (memcmp(tmp, bp->md5cksum, 16) == 0)
2659 buf_InsertToRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2661 lock_AssertWrite(&buf_globalLock);
2664 lock_ObtainMutex(&scp->redirMx);
2667 if (bufp->qFlags & CM_BUF_QINLRU) {
2668 _InterlockedAnd(&bufp->qFlags, ~CM_BUF_QINLRU);
2669 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
2670 (osi_queue_t **) &cm_data.buf_freeListEndp,
2672 buf_DecrementFreeCount();
2674 _InterlockedOr(&bufp->qFlags, CM_BUF_QREDIR);
2675 osi_QAddH( (osi_queue_t **) &cm_data.buf_redirListp,
2676 (osi_queue_t **) &cm_data.buf_redirListEndp,
2678 buf_IncrementRedirCount();
2679 bufp->redirLastAccess = time(NULL);
2681 osi_QAddH( (osi_queue_t **) &scp->redirQueueH,
2682 (osi_queue_t **) &scp->redirQueueT,
2684 scp->redirLastAccess = bufp->redirLastAccess;
2685 InterlockedIncrement(&scp->redirBufCount);
2687 lock_ReleaseMutex(&scp->redirMx);
2692 buf_RemoveFromRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2694 lock_AssertWrite(&buf_globalLock);
2696 if (!(bufp->qFlags & CM_BUF_QREDIR))
2700 lock_ObtainMutex(&scp->redirMx);
2703 _InterlockedAnd(&bufp->qFlags, ~CM_BUF_QREDIR);
2704 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_redirListp,
2705 (osi_queue_t **) &cm_data.buf_redirListEndp,
2707 buf_DecrementRedirCount();
2710 osi_QRemoveHT( (osi_queue_t **) &scp->redirQueueH,
2711 (osi_queue_t **) &scp->redirQueueT,
2714 InterlockedDecrement(&scp->redirBufCount);
2715 lock_ReleaseMutex(&scp->redirMx);
2720 buf_MoveToHeadOfRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2722 lock_AssertWrite(&buf_globalLock);
2723 if (!(bufp->qFlags & CM_BUF_QREDIR))
2727 lock_ObtainMutex(&scp->redirMx);
2730 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_redirListp,
2731 (osi_queue_t **) &cm_data.buf_redirListEndp,
2733 osi_QAddH( (osi_queue_t **) &cm_data.buf_redirListp,
2734 (osi_queue_t **) &cm_data.buf_redirListEndp,
2736 bufp->redirLastAccess = time(NULL);
2738 osi_QRemoveHT( (osi_queue_t **) &scp->redirQueueH,
2739 (osi_queue_t **) &scp->redirQueueT,
2741 osi_QAddH( (osi_queue_t **) &scp->redirQueueH,
2742 (osi_queue_t **) &scp->redirQueueT,
2744 scp->redirLastAccess = bufp->redirLastAccess;
2746 lock_ReleaseMutex(&scp->redirMx);