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_GetVolumeByFID(&bp->fid);
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)) {
351 if (bp->magic != CM_BUF_MAGIC) {
352 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
353 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
359 if (countb > cm_data.buf_nbuffers) {
360 afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
361 fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
366 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
367 if (bp->magic != CM_BUF_MAGIC) {
368 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
369 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
375 if (countf > cm_data.buf_nbuffers) {
376 afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
377 fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
382 for ( bp = cm_data.buf_redirListp; bp; bp = (cm_buf_t *) osi_QNext(&bp->q)) {
383 if (!(bp->qFlags & CM_BUF_QREDIR)) {
384 afsi_log("CM_BUF_QREDIR not set on cm_buf_t in buf_redirListp");
385 fprintf(stderr, "CM_BUF_QREDIR not set on cm_buf_t in buf_redirListp");
389 if (countr > cm_data.buf_nbuffers) {
390 afsi_log("cm_ValidateBuffers failure: countr > cm_data.buf_nbuffers");
391 fprintf(stderr, "cm_ValidateBuffers failure: countr > cm_data.buf_nbuffers\n");
396 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
397 if (bp->magic != CM_BUF_MAGIC) {
398 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
399 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
405 if (counta > cm_data.buf_nbuffers) {
406 afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
407 fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
412 if (countb != countf) {
413 afsi_log("cm_ValidateBuffers failure: countb != countf");
414 fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
418 if (counta != cm_data.buf_nbuffers) {
419 afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
420 fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
427 void buf_Shutdown(void)
429 /* disable the buf_IncrSyncer() threads */
430 buf_ShutdownFlag = 1;
432 /* then force all dirty buffers to the file servers */
436 /* initialize the buffer package; called with no locks
437 * held during the initialization phase.
439 long buf_Init(int newFile, cm_buf_ops_t *opsp, afs_uint64 nbuffers)
441 static osi_once_t once;
444 pthread_attr_t tattr;
451 cm_data.buf_nbuffers = nbuffers;
453 /* Have to be able to reserve a whole chunk */
454 if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
455 return CM_ERROR_TOOFEWBUFS;
458 /* recall for callouts */
461 if (osi_Once(&once)) {
462 /* initialize global locks */
463 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock", LOCK_HIERARCHY_BUF_GLOBAL);
464 lock_InitializeMutex(&buf_rdrReleaseExtentsLock, "RDR Release Extents lock", LOCK_HIERARCHY_RDR_EXTENTS);
467 /* remember this for those who want to reset it */
468 cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
470 /* lower hash size to a prime number */
471 cm_data.buf_hashSize = cm_NextHighestPowerOf2((afs_uint32)(cm_data.buf_nbuffers/7));
473 /* create hash table */
474 memset((void *)cm_data.buf_scacheHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
476 /* another hash table */
477 memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
479 /* create buffer headers and put in free list */
480 bp = cm_data.bufHeaderBaseAddress;
481 data = cm_data.bufDataBaseAddress;
482 cm_data.buf_allp = NULL;
484 for (i=0; i<cm_data.buf_nbuffers; i++) {
485 osi_assertx(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress,
486 "invalid cm_buf_t address");
487 osi_assertx(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData,
488 "invalid cm_buf_t data address");
490 /* allocate and zero some storage */
491 memset(bp, 0, sizeof(cm_buf_t));
492 bp->magic = CM_BUF_MAGIC;
493 /* thread on list of all buffers */
494 bp->allp = cm_data.buf_allp;
495 cm_data.buf_allp = bp;
497 osi_QAddH( (osi_queue_t **) &cm_data.buf_freeListp,
498 (osi_queue_t **) &cm_data.buf_freeListEndp,
500 _InterlockedOr(&bp->qFlags, CM_BUF_QINLRU);
501 buf_IncrementFreeCount();
502 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
504 /* grab appropriate number of bytes from aligned zone */
509 data += cm_data.buf_blockSize;
512 /* none reserved at first */
513 cm_data.buf_reservedBufs = 0;
515 /* just for safety's sake */
516 cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
518 bp = cm_data.bufHeaderBaseAddress;
519 data = cm_data.bufDataBaseAddress;
521 for (i=0; i<cm_data.buf_nbuffers; i++) {
522 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
525 bp->waitRequests = 0;
526 _InterlockedAnd(&bp->flags, ~CM_BUF_WAITING);
528 if (bp->qFlags & CM_BUF_QREDIR) {
530 * extent was not returned by the file system driver.
533 bp->dataVersion = CM_BUF_VERSION_BAD;
534 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QREDIR);
535 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_redirListp,
536 (osi_queue_t **) &cm_data.buf_redirListEndp,
538 buf_DecrementRedirCount();
539 bp->redirq.nextp = bp->redirq.prevp = NULL;
540 bp->redirLastAccess = 0;
541 bp->redirReleaseRequested = 0;
548 * There should be nothing left in cm_data.buf_redirListp
549 * but double check just to be sure.
551 for ( bp = cm_data.buf_redirListp;
553 bp = cm_data.buf_redirListp)
556 * extent was not returned by the file system driver.
559 bp->dataVersion = CM_BUF_VERSION_BAD;
560 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QREDIR);
561 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_redirListp,
562 (osi_queue_t **) &cm_data.buf_redirListEndp,
564 buf_DecrementRedirCount();
565 bp->redirq.nextp = bp->redirq.prevp = NULL;
566 bp->redirLastAccess = 0;
567 bp->redirReleaseRequested = 0;
573 buf_ValidateBufQueues();
577 /* init the buffer trace log */
578 buf_logp = osi_LogCreate("buffer", 1000);
579 osi_LogEnable(buf_logp);
584 /* and create the incr-syncer */
585 pthread_attr_init(&tattr);
586 pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
588 pstatus = pthread_create(&phandle, &tattr, buf_IncrSyncer, 0);
589 osi_assertx(pstatus == 0, "buf: can't create incremental sync proc");
591 pthread_attr_destroy(&tattr);
595 buf_ValidateBufQueues();
600 /* add nbuffers to the buffer pool, if possible.
601 * Called with no locks held.
603 long buf_AddBuffers(afs_uint64 nbuffers)
605 /* The size of a virtual cache cannot be changed after it has
606 * been created. Subsequent calls to MapViewofFile() with
607 * an existing mapping object name would not allow the
608 * object to be resized. Return failure immediately.
610 * A similar problem now occurs with the persistent cache
611 * given that the memory mapped file now contains a complex
614 afsi_log("request to add %d buffers to the existing cache of size %d denied",
615 nbuffers, cm_data.buf_nbuffers);
617 return CM_ERROR_INVAL;
620 /* interface to set the number of buffers to an exact figure.
621 * Called with no locks held.
623 long buf_SetNBuffers(afs_uint64 nbuffers)
626 return CM_ERROR_INVAL;
627 if (nbuffers == cm_data.buf_nbuffers)
629 else if (nbuffers > cm_data.buf_nbuffers)
630 return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
632 return CM_ERROR_INVAL;
635 /* wait for reading or writing to clear; called with write-locked
636 * buffer and unlocked scp and returns with locked buffer.
638 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
643 osi_assertx(scp->magic == CM_SCACHE_MAGIC, "invalid cm_scache_t magic");
644 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
647 /* if no IO is happening, we're done */
648 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
651 /* otherwise I/O is happening, but some other thread is waiting for
652 * the I/O already. Wait for that guy to figure out what happened,
653 * and then check again.
655 if ( bp->flags & CM_BUF_WAITING ) {
658 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%p", bp);
660 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%p", bp);
661 _InterlockedOr(&bp->flags, CM_BUF_WAITING);
662 bp->waitCount = bp->waitRequests = 1;
664 osi_SleepM((LONG_PTR)bp, &bp->mx);
666 cm_UpdateServerPriority();
668 lock_ObtainMutex(&bp->mx);
669 osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%p", bp);
671 if (bp->waitCount == 0) {
672 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%p", bp);
673 _InterlockedAnd(&bp->flags, ~CM_BUF_WAITING);
674 bp->waitRequests = 0;
678 if (scp = cm_FindSCache(&bp->fid))
682 lock_ObtainRead(&scp->rw);
683 if (scp->flags & CM_SCACHEFLAG_WAITING) {
684 osi_Log1(buf_logp, "buf_WaitIO waking scp 0x%p", scp);
685 osi_Wakeup((LONG_PTR)&scp->flags);
687 lock_ReleaseRead(&scp->rw);
691 /* if we get here, the IO is done, but we may have to wakeup people waiting for
692 * the I/O to complete. Do so.
694 if (bp->flags & CM_BUF_WAITING) {
695 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
696 osi_Wakeup((LONG_PTR) bp);
698 osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%p", bp);
701 cm_ReleaseSCache(scp);
704 /* find a buffer, if any, for a particular file ID and offset. Assumes
705 * that buf_globalLock is write locked when called.
707 cm_buf_t *buf_FindLocked(struct cm_fid *fidp, osi_hyper_t *offsetp)
712 lock_AssertAny(&buf_globalLock);
714 i = BUF_HASH(fidp, offsetp);
715 for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp) {
716 if (cm_FidCmp(fidp, &bp->fid) == 0
717 && offsetp->LowPart == bp->offset.LowPart
718 && offsetp->HighPart == bp->offset.HighPart) {
724 /* return whatever we found, if anything */
728 /* find a buffer with offset *offsetp for vnode *scp. Called
729 * with no locks held.
731 cm_buf_t *buf_Find(struct cm_fid *fidp, osi_hyper_t *offsetp)
735 lock_ObtainRead(&buf_globalLock);
736 bp = buf_FindLocked(fidp, offsetp);
737 lock_ReleaseRead(&buf_globalLock);
742 /* find a buffer, if any, for a particular file ID and offset. Assumes
743 * that buf_globalLock is write locked when called. Uses the all buffer
746 cm_buf_t *buf_FindAllLocked(struct cm_fid *fidp, osi_hyper_t *offsetp, afs_uint32 flags)
751 for(bp = cm_data.buf_allp; bp; bp=bp->allp) {
752 if (cm_FidCmp(fidp, &bp->fid) == 0
753 && offsetp->LowPart == bp->offset.LowPart
754 && offsetp->HighPart == bp->offset.HighPart) {
760 for(bp = cm_data.buf_allp; bp; bp=bp->allp) {
761 if (cm_FidCmp(fidp, &bp->fid) == 0) {
764 fileOffset = offsetp->QuadPart + cm_data.baseAddress;
765 if (fileOffset == bp->datap) {
772 /* return whatever we found, if anything */
776 /* find a buffer with offset *offsetp for vnode *scp. Called
777 * with no locks held. Use the all buffer list.
779 cm_buf_t *buf_FindAll(struct cm_fid *fidp, osi_hyper_t *offsetp, afs_uint32 flags)
783 lock_ObtainRead(&buf_globalLock);
784 bp = buf_FindAllLocked(fidp, offsetp, flags);
785 lock_ReleaseRead(&buf_globalLock);
790 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
793 * Makes sure that there's only one person writing this block
794 * at any given time, and also ensures that the log is forced sufficiently far,
795 * if this buffer contains logged data.
797 * Returns non-zero if the buffer was dirty.
799 * 'scp' may or may not be NULL. If it is not NULL, the FID for both cm_scache_t
800 * and cm_buf_t must match.
802 afs_uint32 buf_CleanLocked(cm_scache_t *scp, cm_buf_t *bp, cm_req_t *reqp,
803 afs_uint32 flags, afs_uint32 *pisdirty)
806 afs_uint32 isdirty = 0;
810 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
811 osi_assertx(scp == NULL || cm_FidCmp(&scp->fid, &bp->fid) == 0, "scp fid != bp fid");
814 * If the matching cm_scache_t was not provided as a parameter
815 * we must either find one or allocate a new one. It is possible
816 * that the cm_scache_t was recycled out of the cache even though
817 * a cm_buf_t with the same FID is in the cache.
820 if ((scp = cm_FindSCache(&bp->fid)) ||
821 (cm_GetSCache(&bp->fid, &scp,
822 bp->userp ? bp->userp : cm_rootUserp,
828 while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
830 lock_ReleaseMutex(&bp->mx);
834 * If we didn't find a cm_scache_t object for bp->fid it means
835 * that we no longer have that FID in the cache. It does not
836 * mean that the object does not exist in the cell. That may
837 * in fact be the case but we don't know that until we attempt
838 * a FetchStatus on the FID.
840 osi_Log1(buf_logp, "buf_CleanLocked unable to start I/O - scp not found buf 0x%p", bp);
841 code = CM_ERROR_NOSUCHFILE;
843 osi_Log2(buf_logp, "buf_CleanLocked starts I/O on scp 0x%p buf 0x%p", scp, bp);
846 LargeIntegerAdd(offset, ConvertLongToLargeInteger(bp->dirty_offset));
848 * Only specify the dirty length of the current buffer in the call
849 * to cm_BufWrite(). It is the responsibility of cm_BufWrite()
850 * to determine if it is appropriate to fill a full chunk of data
851 * when storing to the file server.
853 code = (*cm_buf_opsp->Writep)(scp, &offset,
855 flags, bp->userp, reqp);
856 osi_Log3(buf_logp, "buf_CleanLocked I/O on scp 0x%p buf 0x%p, done=%d", scp, bp, code);
858 lock_ObtainMutex(&bp->mx);
859 /* if the Write routine returns No Such File, clear the dirty flag
860 * because we aren't going to be able to write this data to the file
863 if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BADFD || code == CM_ERROR_NOACCESS ||
864 code == CM_ERROR_QUOTA || code == CM_ERROR_SPACE || code == CM_ERROR_TOOBIG ||
865 code == CM_ERROR_READONLY || code == CM_ERROR_NOSUCHPATH){
866 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
867 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
868 bp->dirty_offset = 0;
869 bp->dirty_length = 0;
871 bp->dataVersion = CM_BUF_VERSION_BAD;
877 /* Disk cache support */
878 /* write buffer to disk cache (synchronous for now) */
879 diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
880 #endif /* DISKCACHE95 */
882 /* if we get here and retries are not permitted
883 * then we need to exit this loop regardless of
884 * whether or not we were able to clear the dirty bit
886 if (reqp->flags & CM_REQ_NORETRY)
889 /* Ditto if the hardDeadTimeout or idleTimeout was reached */
890 if (code == CM_ERROR_TIMEDOUT || code == CM_ERROR_ALLDOWN ||
891 code == CM_ERROR_ALLBUSY || code == CM_ERROR_ALLOFFLINE ||
892 code == CM_ERROR_CLOCKSKEW) {
898 cm_ReleaseSCache(scp);
900 /* if someone was waiting for the I/O that just completed or failed,
903 if (bp->flags & CM_BUF_WAITING) {
904 /* turn off flags and wakeup users */
905 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
906 osi_Wakeup((LONG_PTR) bp);
915 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
916 * recycles the buffer, and leaves it ready for reuse with a ref count of 0.
917 * The buffer must already be clean, and no I/O should be happening to it.
919 void buf_Recycle(cm_buf_t *bp)
924 cm_buf_t *prevBp, *nextBp;
926 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
928 osi_assertx(!(bp->qFlags & CM_BUF_QREDIR), "can't recycle redir held buffers");
930 /* if we get here, we know that the buffer still has a 0 ref count,
931 * and that it is clean and has no currently pending I/O. This is
932 * the dude to return.
933 * Remember that as long as the ref count is 0, we know that we won't
934 * have any lock conflicts, so we can grab the buffer lock out of
935 * order in the locking hierarchy.
937 osi_Log3( buf_logp, "buf_Recycle recycles 0x%p, off 0x%x:%08x",
938 bp, bp->offset.HighPart, bp->offset.LowPart);
940 osi_assertx(bp->refCount == 0, "cm_buf_t refcount != 0");
941 osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)),
942 "incorrect cm_buf_t flags");
943 lock_AssertWrite(&buf_globalLock);
945 if (bp->qFlags & CM_BUF_QINHASH) {
946 /* Remove from hash */
948 i = BUF_HASH(&bp->fid, &bp->offset);
949 lbpp = &(cm_data.buf_scacheHashTablepp[i]);
950 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = tbp->hashp) {
955 /* we better find it */
956 osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
958 *lbpp = bp->hashp; /* hash out */
961 /* Remove from file hash */
963 i = BUF_FILEHASH(&bp->fid);
964 prevBp = bp->fileHashBackp;
965 bp->fileHashBackp = NULL;
966 nextBp = bp->fileHashp;
967 bp->fileHashp = NULL;
969 prevBp->fileHashp = nextBp;
971 cm_data.buf_fileHashTablepp[i] = nextBp;
973 nextBp->fileHashBackp = prevBp;
975 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINHASH);
978 /* make the fid unrecognizable */
979 memset(&bp->fid, 0, sizeof(cm_fid_t));
981 /* clean up junk flags */
982 _InterlockedAnd(&bp->flags, ~(CM_BUF_EOF | CM_BUF_ERROR));
983 bp->dataVersion = CM_BUF_VERSION_BAD; /* unknown so far */
988 * buf_RDRShakeAnExtentFree
989 * called with buf_globalLock read locked
992 buf_RDRShakeAnExtentFree(cm_buf_t *rbp, cm_req_t *reqp)
995 LARGE_INTEGER heldExtents = {0,0};
996 AFSFileExtentCB extentList[1];
997 DWORD extentCount = 0;
1000 if (!(rbp->qFlags & CM_BUF_QREDIR))
1003 lock_ReleaseRead(&buf_globalLock);
1005 if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
1006 osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
1007 if (reqp->flags & CM_REQ_NORETRY) {
1008 code = CM_ERROR_WOULDBLOCK;
1012 lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1015 extentList[0].Flags = 0;
1016 extentList[0].Length = cm_data.blockSize;
1017 extentList[0].FileOffset.QuadPart = rbp->offset.QuadPart;
1018 extentList[0].CacheOffset.QuadPart = rbp->datap - cm_data.baseAddress;
1021 code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1023 lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1026 lock_ObtainRead(&buf_globalLock);
1031 * buf_RDRShakeFileExtentsFree
1032 * requests all extents held by the redirector to be returned for
1033 * the specified cm_scache_t. This function is called with no
1037 buf_RDRShakeFileExtentsFree(cm_scache_t *rscp, cm_req_t *reqp)
1039 afs_uint32 code = 0;
1040 afs_uint64 n_redir = 0;
1042 if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
1043 osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
1044 if (reqp->flags & CM_REQ_NORETRY)
1045 return CM_ERROR_WOULDBLOCK;
1047 lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1050 for ( code = CM_ERROR_RETRY; code == CM_ERROR_RETRY; ) {
1051 LARGE_INTEGER heldExtents = {0,0};
1052 AFSFileExtentCB extentList[1024];
1053 DWORD extentCount = 0;
1057 /* only retry if a call to RDR_RequestExtentRelease says to */
1059 lock_ObtainWrite(&buf_globalLock);
1061 if (rscp->redirBufCount == 0)
1063 lock_ReleaseWrite(&buf_globalLock);
1068 for ( srbp = redirq_to_cm_buf_t(rscp->redirQueueT);
1070 srbp = ((code == 0 && extentCount == 0) ? redirq_to_cm_buf_t(rscp->redirQueueT) :
1071 redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq))))
1073 extentList[extentCount].Flags = 0;
1074 extentList[extentCount].Length = cm_data.blockSize;
1075 extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1076 extentList[extentCount].CacheOffset.QuadPart = srbp->datap - cm_data.baseAddress;
1077 srbp->redirReleaseRequested = now;
1080 if (extentCount == 1024) {
1081 lock_ReleaseWrite(&buf_globalLock);
1082 heldExtents.QuadPart = cm_data.buf_redirCount;
1083 code = RDR_RequestExtentRelease(&rscp->fid, heldExtents, extentCount, extentList);
1085 if (code == CM_ERROR_RETRY) {
1087 * The redirector either is not holding the extents or cannot let them
1088 * go because they are otherwise in use. At the moment, do nothing.
1094 lock_ObtainWrite(&buf_globalLock);
1097 lock_ReleaseWrite(&buf_globalLock);
1099 if (code == 0 && extentCount > 0) {
1100 heldExtents.QuadPart = cm_data.buf_redirCount;
1101 code = RDR_RequestExtentRelease(&rscp->fid, heldExtents, extentCount, extentList);
1104 if ((code == CM_ERROR_RETRY) && (reqp->flags & CM_REQ_NORETRY)) {
1105 code = CM_ERROR_WOULDBLOCK;
1109 lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1114 buf_RDRShakeSomeExtentsFree(cm_req_t *reqp, afs_uint32 oneFid, afs_uint32 minage)
1116 afs_uint32 code = 0;
1118 if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
1119 if (reqp->flags & CM_REQ_NORETRY)
1120 return CM_ERROR_WOULDBLOCK;
1122 osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
1123 lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1126 for ( code = CM_ERROR_RETRY; code == CM_ERROR_RETRY; ) {
1127 LARGE_INTEGER heldExtents;
1128 AFSFileExtentCB extentList[1024];
1129 DWORD extentCount = 0;
1130 cm_buf_t *rbp, *srbp;
1133 BOOL locked = FALSE;
1135 /* only retry if a call to RDR_RequestExtentRelease says to */
1137 lock_ObtainWrite(&buf_globalLock);
1140 for ( rbp = cm_data.buf_redirListEndp;
1141 code == 0 && rbp && (!oneFid || extentCount == 0);
1142 rbp = (cm_buf_t *) osi_QPrev(&rbp->q))
1147 if (rbp->redirLastAccess >= rbp->redirReleaseRequested) {
1148 rscp = cm_FindSCache(&rbp->fid);
1153 for ( srbp = redirq_to_cm_buf_t(rscp->redirQueueT);
1154 srbp && extentCount < 1024;
1155 srbp = redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq)))
1158 * Do not request a release if we have already done so
1159 * or if the extent was delivered to windows less than
1160 * 'minage' seconds ago.
1162 if (srbp->redirLastAccess >= srbp->redirReleaseRequested &&
1163 srbp->redirLastAccess < now - minage) {
1164 extentList[extentCount].Flags = 0;
1165 extentList[extentCount].Length = cm_data.blockSize;
1166 extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1167 extentList[extentCount].CacheOffset.QuadPart = srbp->datap - cm_data.baseAddress;
1168 srbp->redirReleaseRequested = now;
1172 cm_ReleaseSCache(rscp);
1175 if ( !oneFid && extentCount > 0) {
1177 lock_ReleaseWrite(&buf_globalLock);
1180 heldExtents.QuadPart = cm_data.buf_redirCount;
1181 code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1184 lock_ObtainWrite(&buf_globalLock);
1189 lock_ReleaseWrite(&buf_globalLock);
1192 heldExtents.QuadPart = cm_data.buf_redirCount;
1193 if (rbp && extentCount)
1194 code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1196 code = RDR_RequestExtentRelease(NULL, heldExtents, 1024, NULL);
1202 if ((code == CM_ERROR_RETRY) && (reqp->flags & CM_REQ_NORETRY)) {
1203 code = CM_ERROR_WOULDBLOCK;
1207 lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1211 /* returns 0 if the buffer does not exist, and non-0 if it does */
1213 buf_ExistsLocked(struct cm_scache *scp, osi_hyper_t *offsetp)
1217 if (bp = buf_FindLocked(&scp->fid, offsetp)) {
1218 /* Do not call buf_ReleaseLocked() because we
1219 * do not want to allow the buffer to be added
1222 afs_int32 refCount = InterlockedDecrement(&bp->refCount);
1223 #ifdef DEBUG_REFCOUNT
1224 osi_Log2(afsd_logp,"buf_ExistsLocked bp 0x%p ref %d", bp, refCount);
1225 afsi_log("%s:%d buf_ExistsLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, refCount);
1227 return CM_BUF_EXISTS;
1233 /* recycle a buffer, removing it from the free list, hashing in its new identity
1234 * and returning it write-locked so that no one can use it. Called without
1235 * any locks held, and can return an error if it loses the race condition and
1236 * finds that someone else created the desired buffer.
1238 * If success is returned, the buffer is returned write-locked.
1240 * May be called with null scp and offsetp, if we're just trying to reclaim some
1241 * space from the buffer pool. In that case, the buffer will be returned
1242 * without being hashed into the hash table.
1244 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp, cm_buf_t **bufpp)
1246 cm_buf_t *bp; /* buffer we're dealing with */
1247 cm_buf_t *nextBp; /* next buffer in file hash chain */
1248 afs_uint32 i; /* temp */
1249 afs_uint64 n_bufs, n_nonzero, n_busy, n_dirty, n_own;
1252 buf_ValidateBufQueues();
1253 #endif /* TESTING */
1263 lock_ObtainRead(&scp->bufCreateLock);
1264 lock_ObtainWrite(&buf_globalLock);
1265 /* check to see if we lost the race */
1266 if (buf_ExistsLocked(scp, offsetp)) {
1267 lock_ReleaseWrite(&buf_globalLock);
1268 lock_ReleaseRead(&scp->bufCreateLock);
1269 return CM_BUF_EXISTS;
1272 /* does this fix the problem below? it's a simple solution. */
1273 if (!cm_data.buf_freeListEndp)
1275 lock_ReleaseWrite(&buf_globalLock);
1276 lock_ReleaseRead(&scp->bufCreateLock);
1278 if ( RDR_Initialized )
1281 osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List is empty - sleeping 200ms");
1286 /* for debugging, assert free list isn't empty, although we
1287 * really should try waiting for a running tranasction to finish
1288 * instead of this; or better, we should have a transaction
1289 * throttler prevent us from entering this situation.
1291 osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
1293 /* look at all buffers in free list, some of which may temp.
1294 * have high refcounts and which then should be skipped,
1295 * starting cleaning I/O for those which are dirty. If we find
1296 * a clean buffer, we rehash it, lock it and return it.
1298 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1304 /* check to see if it really has zero ref count. This
1305 * code can bump refcounts, at least, so it may not be
1308 if (bp->refCount > 0) {
1313 /* we don't have to lock buffer itself, since the ref
1314 * count is 0 and we know it will stay zero as long as
1315 * we hold the global lock.
1318 /* don't recycle someone in our own chunk */
1319 if (!cm_FidCmp(&bp->fid, &scp->fid) &&
1320 bp->dataVersion >= scp->bufDataVersionLow &&
1321 bp->dataVersion <= scp->dataVersion &&
1322 (bp->offset.LowPart & (-cm_chunkSize)) == (offsetp->LowPart & (-cm_chunkSize))) {
1327 /* if this page is being filled (!) or cleaned, see if
1328 * the I/O has completed. If not, skip it, otherwise
1329 * do the final processing for the I/O.
1331 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
1332 /* probably shouldn't do this much work while
1333 * holding the big lock? Watch for contention
1340 if (bp->flags & CM_BUF_DIRTY) {
1343 /* leave the buffer alone if held by the redirector */
1344 if (bp->qFlags & CM_BUF_QREDIR)
1347 /* protect against cleaning the same buffer more than once. */
1351 /* if the buffer is dirty, start cleaning it and
1352 * move on to the next buffer. We do this with
1353 * just the lock required to minimize contention
1357 lock_ReleaseWrite(&buf_globalLock);
1358 lock_ReleaseRead(&scp->bufCreateLock);
1361 * grab required lock and clean.
1362 * previously the claim was that the cleaning
1363 * operation was async which it is not. It would
1364 * be a good idea to use an async mechanism here
1365 * but there is none at the moment other than
1366 * the buf_IncrSyncer() thread.
1368 if (cm_FidCmp(&scp->fid, &bp->fid) == 0)
1369 buf_Clean(scp, bp, reqp, 0, NULL);
1371 buf_Clean(NULL, bp, reqp, 0, NULL);
1373 /* now put it back and go around again */
1376 /* but first obtain the locks we gave up
1377 * before the buf_CleanAsync() call */
1378 lock_ObtainRead(&scp->bufCreateLock);
1379 lock_ObtainWrite(&buf_globalLock);
1382 * Since we dropped the locks we need to verify that
1383 * another thread has not allocated the buffer for us.
1385 if (buf_ExistsLocked(scp, offsetp)) {
1386 lock_ReleaseWrite(&buf_globalLock);
1387 lock_ReleaseRead(&scp->bufCreateLock);
1388 return CM_BUF_EXISTS;
1392 * We just cleaned this buffer so we need to
1393 * restart the loop with this buffer so it
1394 * can be retested. Set 'cleaned' so we
1395 * do not attempt another call to buf_Clean()
1396 * if the prior attempt failed.
1402 osi_Log3(afsd_logp, "buf_GetNewLocked: scp 0x%p examined %u buffers before recycling bufp 0x%p",
1404 osi_Log4(afsd_logp, "... nonzero %u; own %u; busy %u; dirty %u", n_nonzero, n_own, n_busy, n_dirty);
1406 /* if we get here, we know that the buffer still has a 0
1407 * ref count, and that it is clean and has no currently
1408 * pending I/O. This is the dude to return.
1409 * Remember that as long as the ref count is 0, we know
1410 * that we won't have any lock conflicts, so we can grab
1411 * the buffer lock out of order in the locking hierarchy.
1415 /* now hash in as our new buffer, and give it the
1416 * appropriate label, if requested.
1419 lock_AssertWrite(&buf_globalLock);
1421 _InterlockedOr(&bp->qFlags, CM_BUF_QINHASH);
1426 bp->offset = *offsetp;
1427 i = BUF_HASH(&scp->fid, offsetp);
1428 bp->hashp = cm_data.buf_scacheHashTablepp[i];
1429 cm_data.buf_scacheHashTablepp[i] = bp;
1430 i = BUF_FILEHASH(&scp->fid);
1431 nextBp = cm_data.buf_fileHashTablepp[i];
1432 bp->fileHashp = nextBp;
1433 bp->fileHashBackp = NULL;
1435 nextBp->fileHashBackp = bp;
1436 cm_data.buf_fileHashTablepp[i] = bp;
1439 /* we should remove it from the lru queue. It better still be there,
1440 * since we've held the global (big) lock since we found it there.
1442 osi_assertx(bp->qFlags & CM_BUF_QINLRU,
1443 "buf_GetNewLocked: LRU screwup");
1445 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
1446 (osi_queue_t **) &cm_data.buf_freeListEndp,
1448 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINLRU);
1449 buf_DecrementFreeCount();
1451 /* prepare to return it. Give it a refcount */
1452 InterlockedIncrement(&bp->refCount);
1453 #ifdef DEBUG_REFCOUNT
1454 osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, 1);
1455 afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, 1);
1457 /* grab the mutex so that people don't use it
1458 * before the caller fills it with data. Again, no one
1459 * should have been able to get to this dude to lock it.
1461 if (!lock_TryMutex(&bp->mx)) {
1462 osi_Log2(afsd_logp, "buf_GetNewLocked bp 0x%p cannot be mutex locked. refCount %d should be 0",
1464 osi_panic("buf_GetNewLocked: TryMutex failed",__FILE__,__LINE__);
1467 lock_ReleaseWrite(&buf_globalLock);
1468 lock_ReleaseRead(&scp->bufCreateLock);
1473 buf_ValidateBufQueues();
1474 #endif /* TESTING */
1476 } /* for all buffers in lru queue */
1477 lock_ReleaseWrite(&buf_globalLock);
1478 lock_ReleaseRead(&scp->bufCreateLock);
1480 osi_Log1(afsd_logp, "buf_GetNewLocked: Free Buffer List has %u buffers none free", n_bufs);
1481 osi_Log4(afsd_logp, "... nonzero %u; own %u; busy %u; dirty %u", n_nonzero, n_own, n_busy, n_dirty);
1483 if (RDR_Initialized) {
1486 code = buf_RDRShakeSomeExtentsFree(reqp, TRUE, 2 /* seconds */);
1488 case CM_ERROR_RETRY:
1491 case CM_ERROR_WOULDBLOCK:
1492 return CM_ERROR_WOULDBLOCK;
1496 Sleep(100); /* give some time for a buffer to be freed */
1497 } /* while loop over everything */
1502 * get a page, returning it held but unlocked. the page may or may not
1503 * contain valid data.
1505 * The scp must be unlocked when passed in unlocked.
1507 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp, cm_buf_t **bufpp)
1511 osi_hyper_t pageOffset;
1512 unsigned long tcount;
1516 cm_diskcache_t *dcp;
1517 #endif /* DISKCACHE95 */
1520 pageOffset.HighPart = offsetp->HighPart;
1521 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1525 buf_ValidateBufQueues();
1526 #endif /* TESTING */
1528 bp = buf_Find(&scp->fid, &pageOffset);
1530 /* lock it and break out */
1531 lock_ObtainMutex(&bp->mx);
1534 /* touch disk chunk to update LRU info */
1535 diskcache_Touch(bp->dcp);
1536 #endif /* DISKCACHE95 */
1540 /* otherwise, we have to create a page */
1541 code = buf_GetNewLocked(scp, &pageOffset, reqp, &bp);
1544 /* the requested buffer was created */
1549 * the requested buffer existed by the time the
1550 * scp->bufCreateLock and buf_globalLock could be obtained.
1551 * loop again and permit buf_Find() to obtain a reference.
1556 * the requested buffer could not be created.
1557 * return the error to the caller.
1560 buf_ValidateBufQueues();
1561 #endif /* TESTING */
1564 } /* big while loop */
1566 /* if we get here, we have a locked buffer that may have just been
1567 * created, in which case it needs to be filled with data.
1570 /* load the page; freshly created pages should be idle */
1571 osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)), "incorrect cm_buf_t flags");
1574 * start the I/O; may drop lock. as of this writing, the only
1575 * implementation of Readp is cm_BufRead() which simply sets
1576 * tcount to 0 and returns success.
1578 _InterlockedOr(&bp->flags, CM_BUF_READING);
1579 code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
1582 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
1583 bp->dcp = dcp; /* pointer to disk cache struct. */
1584 #endif /* DISKCACHE95 */
1587 /* failure or queued */
1589 /* unless cm_BufRead() is altered, this path cannot be hit */
1590 if (code != ERROR_IO_PENDING) {
1592 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
1593 _InterlockedAnd(&bp->flags, ~CM_BUF_READING);
1594 if (bp->flags & CM_BUF_WAITING) {
1595 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1596 osi_Wakeup((LONG_PTR) bp);
1598 lock_ReleaseMutex(&bp->mx);
1601 buf_ValidateBufQueues();
1602 #endif /* TESTING */
1607 * otherwise, I/O completed instantly and we're done, except
1608 * for padding the xfr out with 0s and checking for EOF
1610 if (tcount < (unsigned long) cm_data.buf_blockSize) {
1611 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
1613 _InterlockedOr(&bp->flags, CM_BUF_EOF);
1615 _InterlockedAnd(&bp->flags, ~CM_BUF_READING);
1616 if (bp->flags & CM_BUF_WAITING) {
1617 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1618 osi_Wakeup((LONG_PTR) bp);
1623 /* wait for reads, either that which we started above, or that someone
1624 * else started. We don't care if we return a buffer being cleaned.
1626 if (bp->flags & CM_BUF_READING)
1627 buf_WaitIO(scp, bp);
1629 /* once it has been read once, we can unlock it and return it, still
1630 * with its refcount held.
1632 lock_ReleaseMutex(&bp->mx);
1635 /* now remove from queue; will be put in at the head (farthest from
1636 * being recycled) when we're done in buf_Release.
1638 lock_ObtainWrite(&buf_globalLock);
1639 if (bp->qFlags & CM_BUF_QINLRU) {
1640 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
1641 (osi_queue_t **) &cm_data.buf_freeListEndp,
1643 _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINLRU);
1644 buf_DecrementFreeCount();
1646 lock_ReleaseWrite(&buf_globalLock);
1648 osi_Log4(buf_logp, "buf_Get returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1649 bp, scp, offsetp->HighPart, offsetp->LowPart);
1651 buf_ValidateBufQueues();
1652 #endif /* TESTING */
1656 /* clean a buffer synchronously */
1657 afs_uint32 buf_Clean(cm_scache_t *scp, cm_buf_t *bp, cm_req_t *reqp, afs_uint32 flags, afs_uint32 *pisdirty)
1660 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1661 osi_assertx(!(flags & CM_BUF_WRITE_SCP_LOCKED), "scp->rw must not be held when calling buf_CleanAsync");
1663 lock_ObtainMutex(&bp->mx);
1664 code = buf_CleanLocked(scp, bp, reqp, flags, pisdirty);
1665 lock_ReleaseMutex(&bp->mx);
1670 /* wait for a buffer's cleaning to finish */
1671 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp, afs_uint32 locked)
1673 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1676 lock_ObtainMutex(&bp->mx);
1677 if (bp->flags & CM_BUF_WRITING) {
1678 buf_WaitIO(scp, bp);
1681 lock_ReleaseMutex(&bp->mx);
1684 /* set the dirty flag on a buffer, and set associated write-ahead log,
1685 * if there is one. Allow one to be added to a buffer, but not changed.
1687 * The buffer must be locked before calling this routine.
1689 void buf_SetDirty(cm_buf_t *bp, cm_req_t *reqp, afs_uint32 offset, afs_uint32 length, cm_user_t *userp)
1691 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1692 osi_assertx(bp->refCount > 0, "cm_buf_t refcount 0");
1697 if (bp->flags & CM_BUF_DIRTY) {
1699 osi_Log1(buf_logp, "buf_SetDirty 0x%p already dirty", bp);
1701 if (bp->dirty_offset <= offset) {
1702 if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1703 /* dirty_length remains the same */
1705 bp->dirty_length = offset + length - bp->dirty_offset;
1707 } else /* bp->dirty_offset > offset */ {
1708 if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1709 bp->dirty_length = bp->dirty_offset + bp->dirty_length - offset;
1711 bp->dirty_length = length;
1713 bp->dirty_offset = offset;
1716 osi_Log1(buf_logp, "buf_SetDirty 0x%p", bp);
1719 _InterlockedOr(&bp->flags, CM_BUF_DIRTY);
1721 /* and turn off EOF flag, since it has associated data now */
1722 _InterlockedAnd(&bp->flags, ~CM_BUF_EOF);
1724 bp->dirty_offset = offset;
1725 bp->dirty_length = length;
1728 * if the request is not from the afs redirector,
1729 * add to the dirty list. The redirector interface ensures
1730 * that a background store operation is queued for each and
1731 * every dirty extent that is released. Therefore, the
1732 * buf_IncrSyncer thread is not required to ensure that
1733 * dirty buffers are written to the file server.
1735 * we obtain a hold on the buffer for as long as it remains
1736 * in the list. buffers are only removed from the list by
1737 * the buf_IncrSyncer function regardless of when else the
1738 * dirty flag might be cleared.
1740 * This should never happen but just in case there is a bug
1741 * elsewhere, never add to the dirty list if the buffer is
1744 if (!(reqp->flags & CM_REQ_SOURCE_REDIR)) {
1745 lock_ObtainWrite(&buf_globalLock);
1746 if (!(bp->qFlags & CM_BUF_QINDL)) {
1748 if (!cm_data.buf_dirtyListp) {
1749 cm_data.buf_dirtyListp = cm_data.buf_dirtyListEndp = bp;
1751 cm_data.buf_dirtyListEndp->dirtyp = bp;
1752 cm_data.buf_dirtyListEndp = bp;
1755 _InterlockedOr(&bp->qFlags, CM_BUF_QINDL);
1757 lock_ReleaseWrite(&buf_globalLock);
1761 /* and record the last writer */
1762 if (bp->userp != userp) {
1765 cm_ReleaseUser(bp->userp);
1770 /* clean all buffers, reset log pointers and invalidate all buffers.
1771 * Called with no locks held, and returns with same.
1773 * This function is guaranteed to clean and remove the log ptr of all the
1774 * buffers that were dirty or had non-zero log ptrs before the call was
1775 * made. That's sufficient to clean up any garbage left around by recovery,
1776 * which is all we're counting on this for; there may be newly created buffers
1777 * added while we're running, but that should be OK.
1779 * In an environment where there are no transactions (artificially imposed, for
1780 * example, when switching the database to raw mode), this function is used to
1781 * make sure that all updates have been written to the disk. In that case, we don't
1782 * really require that we forget the log association between pages and logs, but
1783 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1784 * have to worry about invalidating data in the buffers.
1786 * This function is used at the end of recovery as paranoia to get the recovered
1787 * database out to disk. It removes all references to the recovery log and cleans
1790 long buf_CleanAndReset(void)
1796 lock_ObtainRead(&buf_globalLock);
1797 for(i=0; i<cm_data.buf_hashSize; i++) {
1798 for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp = bp->hashp) {
1799 if (bp->qFlags & CM_BUF_QREDIR) {
1800 osi_Log1(buf_logp,"buf_CleanAndReset buffer held by redirector bp 0x%p", bp);
1802 /* Request single extent from the redirector */
1803 buf_RDRShakeAnExtentFree(bp, &req);
1806 if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1808 lock_ReleaseRead(&buf_globalLock);
1810 /* now no locks are held; clean buffer and go on */
1812 req.flags |= CM_REQ_NORETRY;
1814 buf_Clean(NULL, bp, &req, 0, NULL);
1815 buf_CleanWait(NULL, bp, FALSE);
1817 /* relock and release buffer */
1818 lock_ObtainRead(&buf_globalLock);
1819 buf_ReleaseLocked(bp, FALSE);
1821 } /* over one bucket */
1822 } /* for loop over all hash buckets */
1825 lock_ReleaseRead(&buf_globalLock);
1828 buf_ValidateBufQueues();
1829 #endif /* TESTING */
1831 /* and we're done */
1835 /* called without global lock being held, reserves buffers for callers
1836 * that need more than one held (not locked) at once.
1838 void buf_ReserveBuffers(afs_uint64 nbuffers)
1840 lock_ObtainWrite(&buf_globalLock);
1842 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1843 cm_data.buf_reserveWaiting = 1;
1844 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1845 osi_SleepW((LONG_PTR) &cm_data.buf_reservedBufs, &buf_globalLock);
1846 lock_ObtainWrite(&buf_globalLock);
1849 cm_data.buf_reservedBufs += nbuffers;
1853 lock_ReleaseWrite(&buf_globalLock);
1856 int buf_TryReserveBuffers(afs_uint64 nbuffers)
1860 lock_ObtainWrite(&buf_globalLock);
1861 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1865 cm_data.buf_reservedBufs += nbuffers;
1868 lock_ReleaseWrite(&buf_globalLock);
1872 /* called without global lock held, releases reservation held by
1873 * buf_ReserveBuffers.
1875 void buf_UnreserveBuffers(afs_uint64 nbuffers)
1877 lock_ObtainWrite(&buf_globalLock);
1878 cm_data.buf_reservedBufs -= nbuffers;
1879 if (cm_data.buf_reserveWaiting) {
1880 cm_data.buf_reserveWaiting = 0;
1881 osi_Wakeup((LONG_PTR) &cm_data.buf_reservedBufs);
1883 lock_ReleaseWrite(&buf_globalLock);
1886 /* truncate the buffers past sizep, zeroing out the page, if we don't
1887 * end on a page boundary.
1889 * Requires cm_bufCreateLock to be write locked.
1891 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1895 cm_buf_t *nbufp; /* next buffer, if didRelease */
1900 afs_uint32 invalidate = 0;
1902 /* assert that cm_bufCreateLock is held in write mode */
1903 lock_AssertWrite(&scp->bufCreateLock);
1905 i = BUF_FILEHASH(&scp->fid);
1907 lock_ObtainRead(&buf_globalLock);
1908 bufp = cm_data.buf_fileHashTablepp[i];
1910 lock_ReleaseRead(&buf_globalLock);
1914 buf_HoldLocked(bufp);
1915 lock_ReleaseRead(&buf_globalLock);
1918 lock_ObtainMutex(&bufp->mx);
1920 bufEnd.HighPart = 0;
1921 bufEnd.LowPart = cm_data.buf_blockSize;
1922 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1924 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1925 LargeIntegerLessThan(*sizep, bufEnd)) {
1926 buf_WaitIO(scp, bufp);
1928 lock_ObtainWrite(&scp->rw);
1930 /* make sure we have a callback (so we have the right value for
1931 * the length), and wait for it to be safe to do a truncate.
1933 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1934 CM_SCACHESYNC_NEEDCALLBACK
1935 | CM_SCACHESYNC_GETSTATUS
1936 | CM_SCACHESYNC_SETSIZE
1937 | CM_SCACHESYNC_BUFLOCKED);
1940 /* if we succeeded in our locking, and this applies to the right
1941 * file, and the truncate request overlaps the buffer either
1942 * totally or partially, then do something.
1944 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1945 && LargeIntegerLessThan(*sizep, bufEnd)) {
1948 /* destroy the buffer, turning off its dirty bit, if
1949 * we're truncating the whole buffer. Otherwise, set
1950 * the dirty bit, and clear out the tail of the buffer
1951 * if we just overlap some.
1953 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1954 /* truncating the entire page */
1955 if (reqp->flags & CM_REQ_SOURCE_REDIR) {
1957 * Implicitly clear the redirector flag
1958 * and release the matching hold.
1960 if (bufp->qFlags & CM_BUF_QREDIR) {
1961 osi_Log4(buf_logp,"buf_Truncate taking from file system bufp 0x%p vno 0x%x foffset 0x%x:%x",
1962 bufp, bufp->fid.vnode, bufp->offset.HighPart, bufp->offset.LowPart);
1963 lock_ObtainWrite(&buf_globalLock);
1964 if (bufp->qFlags & CM_BUF_QREDIR) {
1965 buf_RemoveFromRedirQueue(scp, bufp);
1966 buf_ReleaseLocked(bufp, TRUE);
1968 lock_ReleaseWrite(&buf_globalLock);
1973 _InterlockedAnd(&bufp->flags, ~CM_BUF_DIRTY);
1975 bufp->dirty_offset = 0;
1976 bufp->dirty_length = 0;
1977 bufp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
1978 bufp->dirtyCounter++;
1981 /* don't set dirty, since dirty implies
1982 * currently up-to-date. Don't need to do this,
1983 * since we'll update the length anyway.
1985 * Zero out remainder of the page, in case we
1986 * seek and write past EOF, and make this data
1989 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1990 osi_assertx(bufferPos != 0, "non-zero bufferPos");
1991 memset(bufp->datap + bufferPos, 0,
1992 cm_data.buf_blockSize - bufferPos);
1996 cm_SyncOpDone( scp, bufp,
1997 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
1998 | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_BUFLOCKED);
2000 lock_ReleaseWrite(&scp->rw);
2001 lock_ReleaseMutex(&bufp->mx);
2004 nbufp = bufp->fileHashp;
2008 /* This forces the loop to end and the error code
2009 * to be returned. */
2017 buf_ValidateBufQueues();
2018 #endif /* TESTING */
2020 if (invalidate && RDR_Initialized)
2021 RDR_InvalidateObject(scp->fid.cell, scp->fid.volume, scp->fid.vnode,
2022 scp->fid.unique, scp->fid.hash,
2023 scp->fileType, AFS_INVALIDATE_SMB);
2029 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
2032 cm_buf_t *bp; /* buffer we're hacking on */
2036 afs_uint32 stable = 0;
2038 i = BUF_FILEHASH(&scp->fid);
2041 lock_ObtainRead(&buf_globalLock);
2042 bp = cm_data.buf_fileHashTablepp[i];
2045 lock_ReleaseRead(&buf_globalLock);
2047 for (; bp; bp = nbp) {
2048 didRelease = 0; /* haven't released this buffer yet */
2050 /* clean buffer synchronously */
2051 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2053 if (code == 0 && !stable && (bp->flags & CM_BUF_DIRTY)) {
2055 * we must stabilize the object to ensure that buffer
2056 * changes cannot occur while the flush is performed.
2057 * However, we do not want to Stabilize if we do not
2058 * need to because Stabilize obtains a callback.
2060 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
2061 stable = (code == 0);
2064 if (code == CM_ERROR_BADFD) {
2065 /* if the scp's FID is bad its because we received VNOVNODE
2066 * when attempting to FetchStatus before the write. This
2067 * page therefore contains data that can no longer be stored.
2069 lock_ObtainMutex(&bp->mx);
2070 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
2071 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
2072 bp->error = CM_ERROR_BADFD;
2073 bp->dirty_offset = 0;
2074 bp->dirty_length = 0;
2075 bp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
2077 lock_ReleaseMutex(&bp->mx);
2078 } else if (!(scp->flags & CM_SCACHEFLAG_RO)) {
2083 lock_ObtainMutex(&bp->mx);
2085 /* start cleaning the buffer, and wait for it to finish */
2086 buf_CleanLocked(scp, bp, reqp, 0, NULL);
2087 buf_WaitIO(scp, bp);
2089 lock_ReleaseMutex(&bp->mx);
2092 /* actually, we only know that buffer is clean if ref
2093 * count is 1, since we don't have buffer itself locked.
2095 if (!(bp->flags & CM_BUF_DIRTY) && !(bp->qFlags & CM_BUF_QREDIR)) {
2096 lock_ObtainWrite(&buf_globalLock);
2097 if (!(bp->flags & CM_BUF_DIRTY) && !(bp->qFlags & CM_BUF_QREDIR)) {
2098 if (bp->refCount == 1) { /* bp is held above */
2099 nbp = bp->fileHashp;
2101 buf_HoldLocked(nbp);
2102 buf_ReleaseLocked(bp, TRUE);
2107 lock_ReleaseWrite(&buf_globalLock);
2113 lock_ObtainRead(&buf_globalLock);
2114 nbp = bp->fileHashp;
2116 buf_HoldLocked(nbp);
2117 buf_ReleaseLocked(bp, FALSE);
2118 lock_ReleaseRead(&buf_globalLock);
2120 } /* for loop over a bunch of buffers */
2123 (*cm_buf_opsp->Unstabilizep)(scp, userp);
2126 buf_ValidateBufQueues();
2127 #endif /* TESTING */
2133 /* Must be called with scp->rw held */
2134 long buf_ForceDataVersion(cm_scache_t * scp, afs_uint64 fromVersion, afs_uint64 toVersion)
2140 lock_AssertAny(&scp->rw);
2142 i = BUF_FILEHASH(&scp->fid);
2144 lock_ObtainRead(&buf_globalLock);
2146 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp = bp->fileHashp) {
2147 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2148 if (bp->dataVersion == fromVersion) {
2149 bp->dataVersion = toVersion;
2154 lock_ReleaseRead(&buf_globalLock);
2162 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
2166 cm_buf_t *bp; /* buffer we're hacking on */
2167 cm_buf_t *nbp; /* next one */
2170 if (RDR_Initialized && scp->redirBufCount > 0) {
2171 /* Retrieve all extents for this file from the redirector */
2172 buf_RDRShakeFileExtentsFree(scp, reqp);
2175 i = BUF_FILEHASH(&scp->fid);
2177 lock_ObtainRead(&buf_globalLock);
2178 bp = cm_data.buf_fileHashTablepp[i];
2181 lock_ReleaseRead(&buf_globalLock);
2182 for (; bp; bp = nbp) {
2183 /* clean buffer synchronously */
2184 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2186 * If the buffer is held by the redirector we must fetch
2187 * it back in order to determine whether or not it is in
2190 lock_ObtainRead(&buf_globalLock);
2191 if (bp->qFlags & CM_BUF_QREDIR) {
2192 osi_Log1(buf_logp,"buf_CleanVnode buffer held by redirector bp 0x%p", bp);
2194 /* Retrieve single extent from the redirector */
2195 buf_RDRShakeAnExtentFree(bp, reqp);
2197 lock_ReleaseRead(&buf_globalLock);
2199 lock_ObtainMutex(&bp->mx);
2200 if ((bp->flags & CM_BUF_DIRTY)) {
2201 if (userp && userp != bp->userp) {
2204 cm_ReleaseUser(bp->userp);
2209 case CM_ERROR_NOSUCHFILE:
2210 case CM_ERROR_BADFD:
2211 case CM_ERROR_NOACCESS:
2212 case CM_ERROR_QUOTA:
2213 case CM_ERROR_SPACE:
2214 case CM_ERROR_TOOBIG:
2215 case CM_ERROR_READONLY:
2216 case CM_ERROR_NOSUCHPATH:
2218 * Apply the previous fatal error to this buffer.
2219 * Do not waste the time attempting to store to
2220 * the file server when we know it will fail.
2222 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
2223 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
2224 bp->dirty_offset = 0;
2225 bp->dirty_length = 0;
2227 bp->dataVersion = CM_BUF_VERSION_BAD;
2230 case CM_ERROR_TIMEDOUT:
2231 case CM_ERROR_ALLDOWN:
2232 case CM_ERROR_ALLBUSY:
2233 case CM_ERROR_ALLOFFLINE:
2234 case CM_ERROR_CLOCKSKEW:
2235 /* do not mark the buffer in error state but do
2236 * not attempt to complete the rest either.
2240 code = buf_CleanLocked(scp, bp, reqp, 0, &wasDirty);
2241 if (bp->flags & CM_BUF_ERROR) {
2247 buf_CleanWait(scp, bp, TRUE);
2249 lock_ReleaseMutex(&bp->mx);
2252 lock_ObtainRead(&buf_globalLock);
2253 nbp = bp->fileHashp;
2255 buf_HoldLocked(nbp);
2256 buf_ReleaseLocked(bp, FALSE);
2257 lock_ReleaseRead(&buf_globalLock);
2258 } /* for loop over a bunch of buffers */
2261 buf_ValidateBufQueues();
2262 #endif /* TESTING */
2270 buf_ValidateBufQueues(void)
2272 cm_buf_t * bp, *bpb, *bpf, *bpa;
2273 afs_uint32 countf=0, countb=0, counta=0;
2275 lock_ObtainRead(&buf_globalLock);
2276 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
2277 if (bp->magic != CM_BUF_MAGIC)
2278 osi_panic("buf magic error",__FILE__,__LINE__);
2283 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
2284 if (bp->magic != CM_BUF_MAGIC)
2285 osi_panic("buf magic error",__FILE__,__LINE__);
2290 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
2291 if (bp->magic != CM_BUF_MAGIC)
2292 osi_panic("buf magic error",__FILE__,__LINE__);
2296 lock_ReleaseRead(&buf_globalLock);
2298 if (countb != countf)
2299 osi_panic("buf magic error",__FILE__,__LINE__);
2301 if (counta != cm_data.buf_nbuffers)
2302 osi_panic("buf magic error",__FILE__,__LINE__);
2304 #endif /* TESTING */
2306 /* dump the contents of the buf_scacheHashTablepp. */
2307 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
2314 if (cm_data.buf_scacheHashTablepp == NULL)
2318 lock_ObtainRead(&buf_globalLock);
2320 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\r\n",
2321 cookie, cm_data.buf_hashSize);
2322 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2324 for (i = 0; i < cm_data.buf_hashSize; i++)
2326 for (bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp)
2328 StringCbPrintfA(output, sizeof(output),
2329 "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d, "
2330 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2331 "flags=0x%x, qFlags=0x%x cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2332 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
2333 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2334 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2335 bp->cmFlags, bp->error, bp->refCount);
2336 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2340 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\r\n", cookie);
2341 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2343 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_freeListEndp\r\n", cookie);
2344 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2345 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
2346 StringCbPrintfA(output, sizeof(output),
2347 "%s bp=0x%08X, fid (cell=%d, volume=%d, "
2348 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2349 "flags=0x%x, qFlags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2350 cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
2351 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2352 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2353 bp->cmFlags, bp->error, bp->refCount);
2354 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2356 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_FreeListEndp.\r\n", cookie);
2357 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2359 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_dirtyListp\r\n", cookie);
2360 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2361 for(bp = cm_data.buf_dirtyListp; bp; bp=bp->dirtyp) {
2362 StringCbPrintfA(output, sizeof(output),
2363 "%s bp=0x%08X, fid (cell=%d, volume=%d, "
2364 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2365 "flags=0x%x, qFlags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2366 cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
2367 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2368 bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2369 bp->cmFlags, bp->error, bp->refCount);
2370 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2372 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_dirtyListp.\r\n", cookie);
2373 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2376 lock_ReleaseRead(&buf_globalLock);
2380 void buf_ForceTrace(BOOL flush)
2389 len = GetTempPath(sizeof(buf)-10, buf);
2390 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
2391 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
2392 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2393 if (handle == INVALID_HANDLE_VALUE) {
2394 osi_panic("Cannot create log file", __FILE__, __LINE__);
2396 osi_LogPrint(buf_logp, handle);
2398 FlushFileBuffers(handle);
2399 CloseHandle(handle);
2402 long buf_DirtyBuffersExist(cm_fid_t *fidp)
2405 afs_uint32 bcount = 0;
2409 i = BUF_FILEHASH(fidp);
2411 lock_ObtainRead(&buf_globalLock);
2412 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2413 if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
2418 lock_ReleaseRead(&buf_globalLock);
2422 long buf_RDRBuffersExist(cm_fid_t *fidp)
2425 afs_uint32 bcount = 0;
2429 if (!RDR_Initialized)
2432 i = BUF_FILEHASH(fidp);
2434 lock_ObtainRead(&buf_globalLock);
2435 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2436 if (!cm_FidCmp(fidp, &bp->fid) && (bp->qFlags & CM_BUF_QREDIR)) {
2441 lock_ReleaseRead(&buf_globalLock);
2445 long buf_ClearRDRFlag(cm_scache_t *scp, char *reason)
2447 cm_fid_t *fidp = &scp->fid;
2449 afs_uint32 bcount = 0;
2452 i = BUF_FILEHASH(fidp);
2454 lock_ObtainWrite(&scp->rw);
2455 lock_ObtainRead(&buf_globalLock);
2456 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2457 if (!cm_FidCmp(fidp, &bp->fid) && (bp->qFlags & CM_BUF_QREDIR)) {
2458 lock_ConvertRToW(&buf_globalLock);
2459 if (bp->qFlags & CM_BUF_QREDIR) {
2460 osi_Log4(buf_logp,"buf_ClearRDRFlag taking from file system bp 0x%p vno 0x%x foffset 0x%x:%x",
2461 bp, bp->fid.vnode, bp->offset.HighPart, bp->offset.LowPart);
2462 buf_RemoveFromRedirQueue(scp, bp);
2463 buf_ReleaseLocked(bp, TRUE);
2465 lock_ConvertWToR(&buf_globalLock);
2469 /* Confirm that there are none left */
2470 lock_ConvertRToW(&buf_globalLock);
2471 for ( bp = redirq_to_cm_buf_t(scp->redirQueueT);
2473 bp = redirq_to_cm_buf_t(scp->redirQueueT))
2475 if (bp->qFlags & CM_BUF_QREDIR) {
2476 osi_Log4(buf_logp,"buf_ClearRDRFlag taking from file system bufp 0x%p vno 0x%x foffset 0x%x:%x",
2477 bp, bp->fid.vnode, bp->offset.HighPart, bp->offset.LowPart);
2478 buf_RemoveFromRedirQueue(scp, bp);
2479 buf_ReleaseLocked(bp, TRUE);
2483 lock_ReleaseWrite(&buf_globalLock);
2484 lock_ReleaseWrite(&scp->rw);
2489 long buf_CleanDirtyBuffers(cm_scache_t *scp)
2492 afs_uint32 bcount = 0;
2493 cm_fid_t * fidp = &scp->fid;
2495 for (bp = cm_data.buf_allp; bp; bp=bp->allp, bcount++) {
2496 if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
2498 lock_ObtainMutex(&bp->mx);
2499 _InterlockedAnd(&bp->cmFlags, ~CM_BUF_CMSTORING);
2500 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
2501 bp->dirty_offset = 0;
2502 bp->dirty_length = 0;
2503 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
2504 bp->error = VNOVNODE;
2505 bp->dataVersion = CM_BUF_VERSION_BAD; /* bad */
2507 if (bp->flags & CM_BUF_WAITING) {
2508 osi_Log2(buf_logp, "BUF CleanDirtyBuffers Waking [scp 0x%x] bp 0x%x", scp, bp);
2509 osi_Wakeup((long) &bp);
2511 lock_ReleaseMutex(&bp->mx);
2520 * The following routines will not be used on a
2521 * regular basis but are very useful in a variety
2522 * of scenarios when debugging data corruption.
2525 buf_HexCheckSum(cm_buf_t * bp)
2528 static char buf[33];
2529 static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
2531 for (i=0;i<16;i++) {
2532 k = bp->md5cksum[i];
2534 buf[i*2] = tr[k / 16];
2535 buf[i*2+1] = tr[k % 16];
2543 buf_ComputeCheckSum(cm_buf_t * bp)
2548 MD5_Update(&md5, bp->datap, cm_data.blockSize);
2549 MD5_Final(bp->md5cksum, &md5);
2551 osi_Log4(buf_logp, "CheckSum bp 0x%p md5 %s, dirty: offset %u length %u",
2552 bp, osi_LogSaveString(buf_logp, buf_HexCheckSum(bp)),
2553 bp->dirty_offset, bp->dirty_length);
2557 buf_ValidateCheckSum(cm_buf_t * bp)
2560 unsigned char tmp[16];
2563 MD5_Update(&md5, bp->datap, cm_data.blockSize);
2564 MD5_Final(tmp, &md5);
2566 if (memcmp(tmp, bp->md5cksum, 16) == 0)
2572 buf_InsertToRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2574 lock_AssertWrite(&buf_globalLock);
2576 lock_ObtainMutex(&scp->redirMx);
2578 if (bufp->qFlags & CM_BUF_QINLRU) {
2579 _InterlockedAnd(&bufp->qFlags, ~CM_BUF_QINLRU);
2580 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
2581 (osi_queue_t **) &cm_data.buf_freeListEndp,
2583 buf_DecrementFreeCount();
2585 _InterlockedOr(&bufp->qFlags, CM_BUF_QREDIR);
2586 osi_QAddH( (osi_queue_t **) &cm_data.buf_redirListp,
2587 (osi_queue_t **) &cm_data.buf_redirListEndp,
2589 buf_IncrementRedirCount();
2590 bufp->redirLastAccess = time(NULL);
2592 osi_QAddH( (osi_queue_t **) &scp->redirQueueH,
2593 (osi_queue_t **) &scp->redirQueueT,
2595 scp->redirLastAccess = bufp->redirLastAccess;
2596 InterlockedIncrement(&scp->redirBufCount);
2599 lock_ReleaseMutex(&scp->redirMx);
2603 buf_RemoveFromRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2605 lock_AssertWrite(&buf_globalLock);
2607 if (!(bufp->qFlags & CM_BUF_QREDIR))
2610 lock_ObtainMutex(&scp->redirMx);
2612 _InterlockedAnd(&bufp->qFlags, ~CM_BUF_QREDIR);
2613 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_redirListp,
2614 (osi_queue_t **) &cm_data.buf_redirListEndp,
2616 buf_DecrementRedirCount();
2618 osi_QRemoveHT( (osi_queue_t **) &scp->redirQueueH,
2619 (osi_queue_t **) &scp->redirQueueT,
2621 InterlockedDecrement(&scp->redirBufCount);
2624 lock_ReleaseMutex(&scp->redirMx);
2628 buf_MoveToHeadOfRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2630 lock_AssertWrite(&buf_globalLock);
2631 if (!(bufp->qFlags & CM_BUF_QREDIR))
2634 lock_ObtainMutex(&scp->redirMx);
2636 osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_redirListp,
2637 (osi_queue_t **) &cm_data.buf_redirListEndp,
2639 osi_QAddH( (osi_queue_t **) &cm_data.buf_redirListp,
2640 (osi_queue_t **) &cm_data.buf_redirListEndp,
2642 bufp->redirLastAccess = time(NULL);
2644 osi_QRemoveHT( (osi_queue_t **) &scp->redirQueueH,
2645 (osi_queue_t **) &scp->redirQueueT,
2647 osi_QAddH( (osi_queue_t **) &scp->redirQueueH,
2648 (osi_queue_t **) &scp->redirQueueT,
2650 scp->redirLastAccess = bufp->redirLastAccess;
2653 lock_ReleaseMutex(&scp->redirMx);