2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* Copyright (C) 1994 Cazamar Systems, Inc. */
12 #include <afs/param.h>
23 #include "cm_memmap.h"
26 #define TRACE_BUFFER 1
29 extern void afsi_log(char *pattern, ...);
31 /* This module implements the buffer package used by the local transaction
32 * system (cm). It is initialized by calling cm_Init, which calls buf_Init;
33 * it must be initalized before any of its main routines are called.
35 * Each buffer is hashed into a hash table by file ID and offset, and if its
36 * reference count is zero, it is also in a free list.
38 * There are two locks involved in buffer processing. The global lock
39 * buf_globalLock protects all of the global variables defined in this module,
40 * the reference counts and hash pointers in the actual cm_buf_t structures,
41 * and the LRU queue pointers in the buffer structures.
43 * The mutexes in the buffer structures protect the remaining fields in the
44 * buffers, as well the data itself.
46 * The locking hierarchy here is this:
48 * - resv multiple simul. buffers reservation
49 * - lock buffer I/O flags
50 * - lock buffer's mutex
51 * - lock buf_globalLock
55 /* global debugging log */
56 osi_log_t *buf_logp = NULL;
58 /* Global lock protecting hash tables and free lists */
59 osi_rwlock_t buf_globalLock;
61 /* ptr to head of the free list (most recently used) and the
62 * tail (the guy to remove first). We use osi_Q* functions
63 * to put stuff in buf_freeListp, and maintain the end
67 /* a pointer to a list of all buffers, just so that we can find them
68 * easily for debugging, and for the incr syncer. Locked under
72 /* defaults setup; these variables may be manually assigned into
73 * before calling cm_Init, as a way of changing these defaults.
76 /* callouts for reading and writing data, etc */
77 cm_buf_ops_t *cm_buf_opsp;
80 /* for experimental disk caching support in Win95 client */
81 cm_buf_t *buf_diskFreeListp;
82 cm_buf_t *buf_diskFreeListEndp;
83 cm_buf_t *buf_diskAllp;
84 extern int cm_diskCacheEnabled;
85 #endif /* DISKCACHE95 */
87 /* set this to 1 when we are terminating to prevent access attempts */
88 static int buf_ShutdownFlag = 0;
91 void buf_HoldLockedDbg(cm_buf_t *bp, char *file, long line)
93 void buf_HoldLocked(cm_buf_t *bp)
98 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
99 refCount = InterlockedIncrement(&bp->refCount);
100 #ifdef DEBUG_REFCOUNT
101 osi_Log2(afsd_logp,"buf_HoldLocked bp 0x%p ref %d",bp, refCount);
102 afsi_log("%s:%d buf_HoldLocked bp 0x%p, ref %d", file, line, bp, refCount);
106 /* hold a reference to an already held buffer */
107 #ifdef DEBUG_REFCOUNT
108 void buf_HoldDbg(cm_buf_t *bp, char *file, long line)
110 void buf_Hold(cm_buf_t *bp)
115 lock_ObtainRead(&buf_globalLock);
116 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
117 refCount = InterlockedIncrement(&bp->refCount);
118 #ifdef DEBUG_REFCOUNT
119 osi_Log2(afsd_logp,"buf_Hold bp 0x%p ref %d",bp, refCount);
120 afsi_log("%s:%d buf_Hold bp 0x%p, ref %d", file, line, bp, refCount);
122 lock_ReleaseRead(&buf_globalLock);
125 /* code to drop reference count while holding buf_globalLock */
126 #ifdef DEBUG_REFCOUNT
127 void buf_ReleaseLockedDbg(cm_buf_t *bp, afs_uint32 writeLocked, char *file, long line)
129 void buf_ReleaseLocked(cm_buf_t *bp, afs_uint32 writeLocked)
135 lock_AssertWrite(&buf_globalLock);
137 lock_AssertRead(&buf_globalLock);
139 /* ensure that we're in the LRU queue if our ref count is 0 */
140 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
142 refCount = InterlockedDecrement(&bp->refCount);
143 #ifdef DEBUG_REFCOUNT
144 osi_Log3(afsd_logp,"buf_ReleaseLocked %s bp 0x%p ref %d",writeLocked?"write":"read", bp, refCount);
145 afsi_log("%s:%d buf_ReleaseLocked %s bp 0x%p, ref %d", file, line, writeLocked?"write":"read", bp, refCount);
149 osi_panic("buf refcount 0",__FILE__,__LINE__);;
151 osi_assertx(refCount >= 0, "cm_buf_t refCount == 0");
155 * If we are read locked there could be a race condition
156 * with buf_Find() so we must obtain a write lock and
157 * double check that the refCount is actually zero
158 * before we remove the buffer from the LRU queue.
161 lock_ConvertRToW(&buf_globalLock);
163 if (bp->refCount == 0 &&
164 !(bp->flags & CM_BUF_INLRU)) {
165 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
167 /* watch for transition from empty to one element */
168 if (!cm_data.buf_freeListEndp)
169 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
170 bp->flags |= CM_BUF_INLRU;
174 lock_ConvertWToR(&buf_globalLock);
178 /* release a buffer. Buffer must be referenced, but unlocked. */
179 #ifdef DEBUG_REFCOUNT
180 void buf_ReleaseDbg(cm_buf_t *bp, char *file, long line)
182 void buf_Release(cm_buf_t *bp)
187 /* ensure that we're in the LRU queue if our ref count is 0 */
188 osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
190 refCount = InterlockedDecrement(&bp->refCount);
191 #ifdef DEBUG_REFCOUNT
192 osi_Log2(afsd_logp,"buf_Release bp 0x%p ref %d", bp, refCount);
193 afsi_log("%s:%d buf_ReleaseLocked bp 0x%p, ref %d", file, line, bp, refCount);
197 osi_panic("buf refcount 0",__FILE__,__LINE__);;
199 osi_assertx(refCount >= 0, "cm_buf_t refCount == 0");
202 lock_ObtainWrite(&buf_globalLock);
203 if (bp->refCount == 0 &&
204 !(bp->flags & CM_BUF_INLRU)) {
205 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
207 /* watch for transition from empty to one element */
208 if (!cm_data.buf_freeListEndp)
209 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
210 bp->flags |= CM_BUF_INLRU;
212 lock_ReleaseWrite(&buf_globalLock);
217 buf_Sync(int quitOnShutdown)
219 cm_buf_t **bpp, *bp, *prevbp;
220 afs_uint32 wasDirty = 0;
223 /* go through all of the dirty buffers */
224 lock_ObtainRead(&buf_globalLock);
225 for (bpp = &cm_data.buf_dirtyListp, prevbp = NULL; bp = *bpp; ) {
226 if (quitOnShutdown && buf_ShutdownFlag)
229 lock_ReleaseRead(&buf_globalLock);
230 /* all dirty buffers are held when they are added to the
231 * dirty list. No need for an additional hold.
233 lock_ObtainMutex(&bp->mx);
235 if (bp->flags & CM_BUF_DIRTY && !(bp->flags & CM_BUF_REDIR)) {
236 /* start cleaning the buffer; don't touch log pages since
237 * the log code counts on knowing exactly who is writing
238 * a log page at any given instant.
243 req.flags |= CM_REQ_NORETRY;
244 buf_CleanAsyncLocked(bp, &req, &dirty);
248 /* the buffer may or may not have been dirty
249 * and if dirty may or may not have been cleaned
250 * successfully. check the dirty flag again.
252 if (!(bp->flags & CM_BUF_DIRTY)) {
253 /* remove the buffer from the dirty list */
254 lock_ObtainWrite(&buf_globalLock);
255 #ifdef DEBUG_REFCOUNT
256 if (bp->dirtyp == NULL && bp != cm_data.buf_dirtyListEndp) {
257 osi_Log1(afsd_logp,"buf_IncrSyncer bp 0x%p list corruption",bp);
258 afsi_log("buf_IncrSyncer bp 0x%p list corruption", bp);
263 bp->flags &= ~CM_BUF_INDL;
264 if (cm_data.buf_dirtyListp == NULL)
265 cm_data.buf_dirtyListEndp = NULL;
266 else if (cm_data.buf_dirtyListEndp == bp)
267 cm_data.buf_dirtyListEndp = prevbp;
268 buf_ReleaseLocked(bp, TRUE);
269 lock_ConvertWToR(&buf_globalLock);
271 /* advance the pointer so we don't loop forever */
272 lock_ObtainRead(&buf_globalLock);
276 lock_ReleaseMutex(&bp->mx);
277 } /* for loop over a bunch of buffers */
278 lock_ReleaseRead(&buf_globalLock);
283 /* incremental sync daemon. Writes all dirty buffers every 5000 ms */
284 void buf_IncrSyncer(long parm)
289 while (buf_ShutdownFlag == 0) {
292 i = SleepEx(5000, 1);
299 wasDirty = buf_Sync(1);
300 } /* whole daemon's while loop */
304 buf_ValidateBuffers(void)
306 cm_buf_t * bp, *bpf, *bpa, *bpb;
307 afs_uint64 countb = 0, countf = 0, counta = 0;
309 if (cm_data.buf_freeListp == NULL && cm_data.buf_freeListEndp != NULL ||
310 cm_data.buf_freeListp != NULL && cm_data.buf_freeListEndp == NULL) {
311 afsi_log("cm_ValidateBuffers failure: inconsistent free list pointers");
312 fprintf(stderr, "cm_ValidateBuffers failure: inconsistent free list pointers\n");
316 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
317 if (bp->magic != CM_BUF_MAGIC) {
318 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
319 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
325 if (countb > cm_data.buf_nbuffers) {
326 afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
327 fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
332 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
333 if (bp->magic != CM_BUF_MAGIC) {
334 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
335 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
341 if (countf > cm_data.buf_nbuffers) {
342 afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
343 fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
348 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
349 if (bp->magic != CM_BUF_MAGIC) {
350 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
351 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
357 if (counta > cm_data.buf_nbuffers) {
358 afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
359 fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
364 if (countb != countf) {
365 afsi_log("cm_ValidateBuffers failure: countb != countf");
366 fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
370 if (counta != cm_data.buf_nbuffers) {
371 afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
372 fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
379 void buf_Shutdown(void)
381 /* disable the buf_IncrSyncer() threads */
382 buf_ShutdownFlag = 1;
384 /* then force all dirty buffers to the file servers */
388 /* initialize the buffer package; called with no locks
389 * held during the initialization phase.
391 long buf_Init(int newFile, cm_buf_ops_t *opsp, afs_uint64 nbuffers)
393 static osi_once_t once;
402 cm_data.buf_nbuffers = nbuffers;
404 /* Have to be able to reserve a whole chunk */
405 if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
406 return CM_ERROR_TOOFEWBUFS;
409 /* recall for callouts */
412 if (osi_Once(&once)) {
413 /* initialize global locks */
414 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock", LOCK_HIERARCHY_BUF_GLOBAL);
417 /* remember this for those who want to reset it */
418 cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
420 /* lower hash size to a prime number */
421 cm_data.buf_hashSize = osi_PrimeLessThan((afs_uint32)(cm_data.buf_nbuffers/7 + 1));
423 /* create hash table */
424 memset((void *)cm_data.buf_scacheHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
426 /* another hash table */
427 memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
429 /* create buffer headers and put in free list */
430 bp = cm_data.bufHeaderBaseAddress;
431 data = cm_data.bufDataBaseAddress;
432 cm_data.buf_allp = NULL;
434 for (i=0; i<cm_data.buf_nbuffers; i++) {
435 osi_assertx(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress,
436 "invalid cm_buf_t address");
437 osi_assertx(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData,
438 "invalid cm_buf_t data address");
440 /* allocate and zero some storage */
441 memset(bp, 0, sizeof(cm_buf_t));
442 bp->magic = CM_BUF_MAGIC;
443 /* thread on list of all buffers */
444 bp->allp = cm_data.buf_allp;
445 cm_data.buf_allp = bp;
447 osi_QAdd((osi_queue_t **)&cm_data.buf_freeListp, &bp->q);
448 bp->flags |= CM_BUF_INLRU;
449 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
451 /* grab appropriate number of bytes from aligned zone */
454 /* setup last buffer pointer */
456 cm_data.buf_freeListEndp = bp;
460 data += cm_data.buf_blockSize;
463 /* none reserved at first */
464 cm_data.buf_reservedBufs = 0;
466 /* just for safety's sake */
467 cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
469 bp = cm_data.bufHeaderBaseAddress;
470 data = cm_data.bufDataBaseAddress;
472 for (i=0; i<cm_data.buf_nbuffers; i++) {
473 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
476 bp->waitRequests = 0;
477 bp->flags &= ~CM_BUF_WAITING;
483 buf_ValidateBufQueues();
487 /* init the buffer trace log */
488 buf_logp = osi_LogCreate("buffer", 1000);
489 osi_LogEnable(buf_logp);
494 /* and create the incr-syncer */
495 phandle = thrd_Create(0, 0,
496 (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
499 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
500 CloseHandle(phandle);
504 buf_ValidateBufQueues();
509 /* add nbuffers to the buffer pool, if possible.
510 * Called with no locks held.
512 long buf_AddBuffers(afs_uint64 nbuffers)
515 /* The size of a virtual cache cannot be changed after it has
516 * been created. Subsequent calls to MapViewofFile() with
517 * an existing mapping object name would not allow the
518 * object to be resized. Return failure immediately.
520 * A similar problem now occurs with the persistent cache
521 * given that the memory mapped file now contains a complex
524 afsi_log("request to add %d buffers to the existing cache of size %d denied",
525 nbuffers, cm_data.buf_nbuffers);
527 return CM_ERROR_INVAL;
533 data = malloc(buf_nbuffers * cm_data.buf_blockSize);
535 /* Create buffer headers and put in free list */
536 bp = malloc(nbuffers * sizeof(*bp));
538 for (i=0; i<nbuffers; i++) {
539 memset(bp, 0, sizeof(*bp));
541 lock_InitializeMutex(&bp->mx, "cm_buf_t", LOCK_HIERARCHY_BUFFER);
543 /* grab appropriate number of bytes from aligned zone */
546 bp->flags |= CM_BUF_INLRU;
548 lock_ObtainWrite(&buf_globalLock);
549 /* note that buf_allp chain is covered by buf_globalLock now */
550 bp->allp = cm_data.buf_allp;
551 cm_data.buf_allp = bp;
552 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
553 if (!cm_data.buf_freeListEndp)
554 cm_data.buf_freeListEndp = bp;
555 cm_data.buf_nbuffers++;
556 lock_ReleaseWrite(&buf_globalLock);
559 data += cm_data.buf_blockSize;
561 } /* for loop over all buffers */
567 /* interface to set the number of buffers to an exact figure.
568 * Called with no locks held.
570 long buf_SetNBuffers(afs_uint64 nbuffers)
573 return CM_ERROR_INVAL;
574 if (nbuffers == cm_data.buf_nbuffers)
576 else if (nbuffers > cm_data.buf_nbuffers)
577 return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
579 return CM_ERROR_INVAL;
582 /* wait for reading or writing to clear; called with write-locked
583 * buffer and unlocked scp and returns with locked buffer.
585 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
590 osi_assertx(scp->magic == CM_SCACHE_MAGIC, "invalid cm_scache_t magic");
591 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
594 /* if no IO is happening, we're done */
595 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
598 /* otherwise I/O is happening, but some other thread is waiting for
599 * the I/O already. Wait for that guy to figure out what happened,
600 * and then check again.
602 if ( bp->flags & CM_BUF_WAITING ) {
605 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%p", bp);
607 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%p", bp);
608 bp->flags |= CM_BUF_WAITING;
609 bp->waitCount = bp->waitRequests = 1;
611 osi_SleepM((LONG_PTR)bp, &bp->mx);
613 smb_UpdateServerPriority();
615 lock_ObtainMutex(&bp->mx);
616 osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%p", bp);
618 if (bp->waitCount == 0) {
619 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%p", bp);
620 bp->flags &= ~CM_BUF_WAITING;
621 bp->waitRequests = 0;
625 if (scp = cm_FindSCache(&bp->fid))
629 lock_ObtainRead(&scp->rw);
630 if (scp->flags & CM_SCACHEFLAG_WAITING) {
631 osi_Log1(buf_logp, "buf_WaitIO waking scp 0x%p", scp);
632 osi_Wakeup((LONG_PTR)&scp->flags);
634 lock_ReleaseRead(&scp->rw);
638 /* if we get here, the IO is done, but we may have to wakeup people waiting for
639 * the I/O to complete. Do so.
641 if (bp->flags & CM_BUF_WAITING) {
642 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
643 osi_Wakeup((LONG_PTR) bp);
645 osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%p", bp);
648 cm_ReleaseSCache(scp);
651 /* find a buffer, if any, for a particular file ID and offset. Assumes
652 * that buf_globalLock is write locked when called.
654 cm_buf_t *buf_FindLocked(struct cm_scache *scp, osi_hyper_t *offsetp)
659 i = BUF_HASH(&scp->fid, offsetp);
660 for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp) {
661 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
662 && offsetp->LowPart == bp->offset.LowPart
663 && offsetp->HighPart == bp->offset.HighPart) {
669 /* return whatever we found, if anything */
673 /* find a buffer with offset *offsetp for vnode *scp. Called
674 * with no locks held.
676 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
680 lock_ObtainRead(&buf_globalLock);
681 bp = buf_FindLocked(scp, offsetp);
682 lock_ReleaseRead(&buf_globalLock);
687 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
690 * Makes sure that there's only one person writing this block
691 * at any given time, and also ensures that the log is forced sufficiently far,
692 * if this buffer contains logged data.
694 * Returns non-zero if the buffer was dirty.
696 afs_uint32 buf_CleanAsyncLocked(cm_buf_t *bp, cm_req_t *reqp, afs_uint32 *pisdirty)
699 afs_uint32 isdirty = 0;
700 cm_scache_t * scp = NULL;
703 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
705 while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
707 lock_ReleaseMutex(&bp->mx);
709 scp = cm_FindSCache(&bp->fid);
711 osi_Log2(buf_logp, "buf_CleanAsyncLocked starts I/O on scp 0x%p buf 0x%p", scp, bp);
714 LargeIntegerAdd(offset, ConvertLongToLargeInteger(bp->dirty_offset));
715 code = (*cm_buf_opsp->Writep)(scp, &offset,
717 /* we might as well try to write all of the contiguous
718 * dirty buffers in one RPC
725 osi_Log3(buf_logp, "buf_CleanAsyncLocked I/O on scp 0x%p buf 0x%p, done=%d", scp, bp, code);
727 cm_ReleaseSCache(scp);
730 osi_Log1(buf_logp, "buf_CleanAsyncLocked unable to start I/O - scp not found buf 0x%p", bp);
731 code = CM_ERROR_NOSUCHFILE;
734 lock_ObtainMutex(&bp->mx);
735 /* if the Write routine returns No Such File, clear the dirty flag
736 * because we aren't going to be able to write this data to the file
739 if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BADFD || code == CM_ERROR_NOACCESS ||
740 code == CM_ERROR_QUOTA || code == CM_ERROR_SPACE || code == CM_ERROR_TOOBIG ||
741 code == CM_ERROR_READONLY || code == CM_ERROR_NOSUCHPATH){
742 bp->flags &= ~CM_BUF_DIRTY;
743 bp->flags |= CM_BUF_ERROR;
744 bp->dirty_offset = 0;
745 bp->dirty_length = 0;
747 bp->dataVersion = CM_BUF_VERSION_BAD;
753 /* Disk cache support */
754 /* write buffer to disk cache (synchronous for now) */
755 diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
756 #endif /* DISKCACHE95 */
758 /* if we get here and retries are not permitted
759 * then we need to exit this loop regardless of
760 * whether or not we were able to clear the dirty bit
762 if (reqp->flags & CM_REQ_NORETRY)
765 /* Ditto if the hardDeadTimeout or idleTimeout was reached */
766 if (code == CM_ERROR_TIMEDOUT || code == CM_ERROR_ALLDOWN ||
767 code == CM_ERROR_ALLBUSY || code == CM_ERROR_ALLOFFLINE ||
768 code == CM_ERROR_CLOCKSKEW) {
773 /* if someone was waiting for the I/O that just completed or failed,
776 if (bp->flags & CM_BUF_WAITING) {
777 /* turn off flags and wakeup users */
778 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
779 osi_Wakeup((LONG_PTR) bp);
788 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
789 * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
790 * The buffer must already be clean, and no I/O should be happening to it.
792 void buf_Recycle(cm_buf_t *bp)
797 cm_buf_t *prevBp, *nextBp;
799 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
801 /* if we get here, we know that the buffer still has a 0 ref count,
802 * and that it is clean and has no currently pending I/O. This is
803 * the dude to return.
804 * Remember that as long as the ref count is 0, we know that we won't
805 * have any lock conflicts, so we can grab the buffer lock out of
806 * order in the locking hierarchy.
808 osi_Log3( buf_logp, "buf_Recycle recycles 0x%p, off 0x%x:%08x",
809 bp, bp->offset.HighPart, bp->offset.LowPart);
811 osi_assertx(bp->refCount == 0, "cm_buf_t refcount != 0");
812 osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)),
813 "incorrect cm_buf_t flags");
814 lock_AssertWrite(&buf_globalLock);
816 if (bp->flags & CM_BUF_INHASH) {
817 /* Remove from hash */
819 i = BUF_HASH(&bp->fid, &bp->offset);
820 lbpp = &(cm_data.buf_scacheHashTablepp[i]);
821 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
826 /* we better find it */
827 osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
829 *lbpp = bp->hashp; /* hash out */
832 /* Remove from file hash */
834 i = BUF_FILEHASH(&bp->fid);
835 prevBp = bp->fileHashBackp;
836 bp->fileHashBackp = NULL;
837 nextBp = bp->fileHashp;
838 bp->fileHashp = NULL;
840 prevBp->fileHashp = nextBp;
842 cm_data.buf_fileHashTablepp[i] = nextBp;
844 nextBp->fileHashBackp = prevBp;
846 bp->flags &= ~CM_BUF_INHASH;
849 /* make the fid unrecognizable */
850 memset(&bp->fid, 0, sizeof(cm_fid_t));
853 /* recycle a buffer, removing it from the free list, hashing in its new identity
854 * and returning it write-locked so that no one can use it. Called without
855 * any locks held, and can return an error if it loses the race condition and
856 * finds that someone else created the desired buffer.
858 * If success is returned, the buffer is returned write-locked.
860 * May be called with null scp and offsetp, if we're just trying to reclaim some
861 * space from the buffer pool. In that case, the buffer will be returned
862 * without being hashed into the hash table.
864 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
866 cm_buf_t *bp; /* buffer we're dealing with */
867 cm_buf_t *nextBp; /* next buffer in file hash chain */
868 afs_uint32 i; /* temp */
871 cm_InitReq(&req); /* just in case */
874 buf_ValidateBufQueues();
879 lock_ObtainRead(&scp->bufCreateLock);
880 lock_ObtainWrite(&buf_globalLock);
881 /* check to see if we lost the race */
883 if (bp = buf_FindLocked(scp, offsetp)) {
884 /* Do not call buf_ReleaseLocked() because we
885 * do not want to allow the buffer to be added
888 afs_int32 refCount = InterlockedDecrement(&bp->refCount);
889 #ifdef DEBUG_REFCOUNT
890 osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, refCount);
891 afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, refCount);
893 lock_ReleaseWrite(&buf_globalLock);
894 lock_ReleaseRead(&scp->bufCreateLock);
895 return CM_BUF_EXISTS;
899 /* does this fix the problem below? it's a simple solution. */
900 if (!cm_data.buf_freeListEndp)
902 lock_ReleaseWrite(&buf_globalLock);
903 lock_ReleaseRead(&scp->bufCreateLock);
904 osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List is empty - sleeping 200ms");
909 /* for debugging, assert free list isn't empty, although we
910 * really should try waiting for a running tranasction to finish
911 * instead of this; or better, we should have a transaction
912 * throttler prevent us from entering this situation.
914 osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
916 /* look at all buffers in free list, some of which may temp.
917 * have high refcounts and which then should be skipped,
918 * starting cleaning I/O for those which are dirty. If we find
919 * a clean buffer, we rehash it, lock it and return it.
921 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
922 /* check to see if it really has zero ref count. This
923 * code can bump refcounts, at least, so it may not be
926 if (bp->refCount > 0)
929 /* we don't have to lock buffer itself, since the ref
930 * count is 0 and we know it will stay zero as long as
931 * we hold the global lock.
934 /* Don't recycle a buffer held by the redirector. */
935 if (bp->flags & CM_BUF_REDIR)
938 /* don't recycle someone in our own chunk */
939 if (!cm_FidCmp(&bp->fid, &scp->fid)
940 && (bp->offset.LowPart & (-cm_chunkSize))
941 == (offsetp->LowPart & (-cm_chunkSize)))
944 /* if this page is being filled (!) or cleaned, see if
945 * the I/O has completed. If not, skip it, otherwise
946 * do the final processing for the I/O.
948 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
949 /* probably shouldn't do this much work while
950 * holding the big lock? Watch for contention
956 if (bp->flags & CM_BUF_DIRTY) {
957 /* if the buffer is dirty, start cleaning it and
958 * move on to the next buffer. We do this with
959 * just the lock required to minimize contention
963 lock_ReleaseWrite(&buf_globalLock);
964 lock_ReleaseRead(&scp->bufCreateLock);
966 /* grab required lock and clean; this only
967 * starts the I/O. By the time we're back,
968 * it'll still be marked dirty, but it will also
969 * have the WRITING flag set, so we won't get
972 buf_CleanAsync(bp, &req, NULL);
974 /* now put it back and go around again */
979 /* if we get here, we know that the buffer still has a 0
980 * ref count, and that it is clean and has no currently
981 * pending I/O. This is the dude to return.
982 * Remember that as long as the ref count is 0, we know
983 * that we won't have any lock conflicts, so we can grab
984 * the buffer lock out of order in the locking hierarchy.
988 /* clean up junk flags */
989 bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
990 bp->dataVersion = CM_BUF_VERSION_BAD; /* unknown so far */
992 /* now hash in as our new buffer, and give it the
993 * appropriate label, if requested.
996 bp->flags |= CM_BUF_INHASH;
1001 bp->offset = *offsetp;
1002 i = BUF_HASH(&scp->fid, offsetp);
1003 bp->hashp = cm_data.buf_scacheHashTablepp[i];
1004 cm_data.buf_scacheHashTablepp[i] = bp;
1005 i = BUF_FILEHASH(&scp->fid);
1006 nextBp = cm_data.buf_fileHashTablepp[i];
1007 bp->fileHashp = nextBp;
1008 bp->fileHashBackp = NULL;
1010 nextBp->fileHashBackp = bp;
1011 cm_data.buf_fileHashTablepp[i] = bp;
1014 /* we should move it from the lru queue. It better still be there,
1015 * since we've held the global (big) lock since we found it there.
1017 osi_assertx(bp->flags & CM_BUF_INLRU,
1018 "buf_GetNewLocked: LRU screwup");
1020 if (cm_data.buf_freeListEndp == bp) {
1021 /* we're the last guy in this queue, so maintain it */
1022 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1024 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
1025 bp->flags &= ~CM_BUF_INLRU;
1027 /* prepare to return it. Give it a refcount */
1029 #ifdef DEBUG_REFCOUNT
1030 osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, 1);
1031 afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, 1);
1033 /* grab the mutex so that people don't use it
1034 * before the caller fills it with data. Again, no one
1035 * should have been able to get to this dude to lock it.
1037 if (!lock_TryMutex(&bp->mx)) {
1038 osi_Log2(afsd_logp, "buf_GetNewLocked bp 0x%p cannot be mutex locked. refCount %d should be 0",
1040 osi_panic("buf_GetNewLocked: TryMutex failed",__FILE__,__LINE__);
1043 lock_ReleaseWrite(&buf_globalLock);
1044 lock_ReleaseRead(&scp->bufCreateLock);
1049 buf_ValidateBufQueues();
1050 #endif /* TESTING */
1052 } /* for all buffers in lru queue */
1053 lock_ReleaseWrite(&buf_globalLock);
1054 lock_ReleaseRead(&scp->bufCreateLock);
1055 osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List has no buffers with a zero refcount - sleeping 100ms");
1056 Sleep(100); /* give some time for a buffer to be freed */
1057 } /* while loop over everything */
1061 /* get a page, returning it held but unlocked. Doesn't fill in the page
1062 * with I/O, since we're going to write the whole thing new.
1064 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
1068 osi_hyper_t pageOffset;
1072 pageOffset.HighPart = offsetp->HighPart;
1073 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1075 bp = buf_Find(scp, &pageOffset);
1077 /* lock it and break out */
1078 lock_ObtainMutex(&bp->mx);
1082 /* otherwise, we have to create a page */
1083 code = buf_GetNewLocked(scp, &pageOffset, &bp);
1085 /* check if the buffer was created in a race condition branch.
1086 * If so, go around so we can hold a reference to it.
1088 if (code == CM_BUF_EXISTS)
1091 /* something else went wrong */
1095 /* otherwise, we have a locked buffer that we just created */
1098 } /* big while loop */
1100 /* wait for reads */
1101 if (bp->flags & CM_BUF_READING)
1102 buf_WaitIO(scp, bp);
1104 /* once it has been read once, we can unlock it and return it, still
1105 * with its refcount held.
1107 lock_ReleaseMutex(&bp->mx);
1109 osi_Log4(buf_logp, "buf_GetNew returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1110 bp, scp, offsetp->HighPart, offsetp->LowPart);
1114 /* get a page, returning it held but unlocked. Make sure it is complete */
1115 /* The scp must be unlocked when passed to this function */
1116 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
1120 osi_hyper_t pageOffset;
1121 unsigned long tcount;
1125 cm_diskcache_t *dcp;
1126 #endif /* DISKCACHE95 */
1129 pageOffset.HighPart = offsetp->HighPart;
1130 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1134 buf_ValidateBufQueues();
1135 #endif /* TESTING */
1137 bp = buf_Find(scp, &pageOffset);
1139 /* lock it and break out */
1140 lock_ObtainMutex(&bp->mx);
1143 /* touch disk chunk to update LRU info */
1144 diskcache_Touch(bp->dcp);
1145 #endif /* DISKCACHE95 */
1149 /* otherwise, we have to create a page */
1150 code = buf_GetNewLocked(scp, &pageOffset, &bp);
1151 /* bp->mx is now held */
1153 /* check if the buffer was created in a race condition branch.
1154 * If so, go around so we can hold a reference to it.
1156 if (code == CM_BUF_EXISTS)
1159 /* something else went wrong */
1162 buf_ValidateBufQueues();
1163 #endif /* TESTING */
1167 /* otherwise, we have a locked buffer that we just created */
1170 } /* big while loop */
1172 /* if we get here, we have a locked buffer that may have just been
1173 * created, in which case it needs to be filled with data.
1176 /* load the page; freshly created pages should be idle */
1177 osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)), "incorrect cm_buf_t flags");
1179 /* start the I/O; may drop lock */
1180 bp->flags |= CM_BUF_READING;
1181 code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
1184 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
1185 bp->dcp = dcp; /* pointer to disk cache struct. */
1186 #endif /* DISKCACHE95 */
1189 /* failure or queued */
1190 #ifndef DJGPP /* cm_bufRead always returns 0 */
1191 if (code != ERROR_IO_PENDING) {
1194 bp->flags |= CM_BUF_ERROR;
1195 bp->flags &= ~CM_BUF_READING;
1196 if (bp->flags & CM_BUF_WAITING) {
1197 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1198 osi_Wakeup((LONG_PTR) bp);
1200 lock_ReleaseMutex(&bp->mx);
1203 buf_ValidateBufQueues();
1204 #endif /* TESTING */
1210 /* otherwise, I/O completed instantly and we're done, except
1211 * for padding the xfr out with 0s and checking for EOF
1213 if (tcount < (unsigned long) cm_data.buf_blockSize) {
1214 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
1216 bp->flags |= CM_BUF_EOF;
1218 bp->flags &= ~CM_BUF_READING;
1219 if (bp->flags & CM_BUF_WAITING) {
1220 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1221 osi_Wakeup((LONG_PTR) bp);
1227 /* wait for reads, either that which we started above, or that someone
1228 * else started. We don't care if we return a buffer being cleaned.
1230 if (bp->flags & CM_BUF_READING)
1231 buf_WaitIO(scp, bp);
1233 /* once it has been read once, we can unlock it and return it, still
1234 * with its refcount held.
1236 lock_ReleaseMutex(&bp->mx);
1239 /* now remove from queue; will be put in at the head (farthest from
1240 * being recycled) when we're done in buf_Release.
1242 lock_ObtainWrite(&buf_globalLock);
1243 if (bp->flags & CM_BUF_INLRU) {
1244 if (cm_data.buf_freeListEndp == bp)
1245 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1246 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
1247 bp->flags &= ~CM_BUF_INLRU;
1249 lock_ReleaseWrite(&buf_globalLock);
1251 osi_Log4(buf_logp, "buf_Get returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1252 bp, scp, offsetp->HighPart, offsetp->LowPart);
1254 buf_ValidateBufQueues();
1255 #endif /* TESTING */
1259 /* count # of elements in the free list;
1260 * we don't bother doing the proper locking for accessing dataVersion or flags
1261 * since it is a pain, and this is really just an advisory call. If you need
1262 * to do better at some point, rewrite this function.
1264 long buf_CountFreeList(void)
1270 lock_ObtainRead(&buf_globalLock);
1271 for(bufp = cm_data.buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1272 /* if the buffer doesn't have an identity, or if the buffer
1273 * has been invalidate (by having its DV stomped upon), then
1274 * count it as free, since it isn't really being utilized.
1276 if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion == CM_BUF_VERSION_BAD)
1279 lock_ReleaseRead(&buf_globalLock);
1283 /* clean a buffer synchronously */
1284 afs_uint32 buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp, afs_uint32 *pisdirty)
1287 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1289 lock_ObtainMutex(&bp->mx);
1290 code = buf_CleanAsyncLocked(bp, reqp, pisdirty);
1291 lock_ReleaseMutex(&bp->mx);
1296 /* wait for a buffer's cleaning to finish */
1297 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp, afs_uint32 locked)
1299 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1302 lock_ObtainMutex(&bp->mx);
1303 if (bp->flags & CM_BUF_WRITING) {
1304 buf_WaitIO(scp, bp);
1307 lock_ReleaseMutex(&bp->mx);
1310 /* set the dirty flag on a buffer, and set associated write-ahead log,
1311 * if there is one. Allow one to be added to a buffer, but not changed.
1313 * The buffer must be locked before calling this routine.
1315 void buf_SetDirty(cm_buf_t *bp, afs_uint32 offset, afs_uint32 length, cm_user_t *userp)
1317 osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1318 osi_assertx(bp->refCount > 0, "cm_buf_t refcount 0");
1320 if (bp->flags & CM_BUF_DIRTY) {
1322 osi_Log1(buf_logp, "buf_SetDirty 0x%p already dirty", bp);
1324 if (bp->dirty_offset <= offset) {
1325 if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1326 /* dirty_length remains the same */
1328 bp->dirty_length = offset + length - bp->dirty_offset;
1330 } else /* bp->dirty_offset > offset */ {
1331 if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1332 bp->dirty_length = bp->dirty_offset + bp->dirty_length - offset;
1334 bp->dirty_length = length;
1336 bp->dirty_offset = offset;
1339 osi_Log1(buf_logp, "buf_SetDirty 0x%p", bp);
1342 bp->flags |= CM_BUF_DIRTY;
1344 /* and turn off EOF flag, since it has associated data now */
1345 bp->flags &= ~CM_BUF_EOF;
1347 bp->dirty_offset = offset;
1348 bp->dirty_length = length;
1350 /* and add to the dirty list.
1351 * we obtain a hold on the buffer for as long as it remains
1352 * in the list. buffers are only removed from the list by
1353 * the buf_IncrSyncer function regardless of when else the
1354 * dirty flag might be cleared.
1356 * This should never happen but just in case there is a bug
1357 * elsewhere, never add to the dirty list if the buffer is
1360 lock_ObtainWrite(&buf_globalLock);
1361 if (!(bp->flags & CM_BUF_INDL)) {
1363 if (!cm_data.buf_dirtyListp) {
1364 cm_data.buf_dirtyListp = cm_data.buf_dirtyListEndp = bp;
1366 cm_data.buf_dirtyListEndp->dirtyp = bp;
1367 cm_data.buf_dirtyListEndp = bp;
1370 bp->flags |= CM_BUF_INDL;
1372 lock_ReleaseWrite(&buf_globalLock);
1375 /* and record the last writer */
1376 if (bp->userp != userp) {
1379 cm_ReleaseUser(bp->userp);
1384 /* clean all buffers, reset log pointers and invalidate all buffers.
1385 * Called with no locks held, and returns with same.
1387 * This function is guaranteed to clean and remove the log ptr of all the
1388 * buffers that were dirty or had non-zero log ptrs before the call was
1389 * made. That's sufficient to clean up any garbage left around by recovery,
1390 * which is all we're counting on this for; there may be newly created buffers
1391 * added while we're running, but that should be OK.
1393 * In an environment where there are no transactions (artificially imposed, for
1394 * example, when switching the database to raw mode), this function is used to
1395 * make sure that all updates have been written to the disk. In that case, we don't
1396 * really require that we forget the log association between pages and logs, but
1397 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1398 * have to worry about invalidating data in the buffers.
1400 * This function is used at the end of recovery as paranoia to get the recovered
1401 * database out to disk. It removes all references to the recovery log and cleans
1404 long buf_CleanAndReset(void)
1410 lock_ObtainRead(&buf_globalLock);
1411 for(i=0; i<cm_data.buf_hashSize; i++) {
1412 for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp = bp->hashp) {
1413 if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1415 lock_ReleaseRead(&buf_globalLock);
1417 /* now no locks are held; clean buffer and go on */
1419 req.flags |= CM_REQ_NORETRY;
1421 buf_CleanAsync(bp, &req, NULL);
1422 buf_CleanWait(NULL, bp, FALSE);
1424 /* relock and release buffer */
1425 lock_ObtainRead(&buf_globalLock);
1426 buf_ReleaseLocked(bp, FALSE);
1428 } /* over one bucket */
1429 } /* for loop over all hash buckets */
1432 lock_ReleaseRead(&buf_globalLock);
1435 buf_ValidateBufQueues();
1436 #endif /* TESTING */
1438 /* and we're done */
1442 /* called without global lock being held, reserves buffers for callers
1443 * that need more than one held (not locked) at once.
1445 void buf_ReserveBuffers(afs_uint64 nbuffers)
1447 lock_ObtainWrite(&buf_globalLock);
1449 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1450 cm_data.buf_reserveWaiting = 1;
1451 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1452 osi_SleepW((LONG_PTR) &cm_data.buf_reservedBufs, &buf_globalLock);
1453 lock_ObtainWrite(&buf_globalLock);
1456 cm_data.buf_reservedBufs += nbuffers;
1460 lock_ReleaseWrite(&buf_globalLock);
1463 int buf_TryReserveBuffers(afs_uint64 nbuffers)
1467 lock_ObtainWrite(&buf_globalLock);
1468 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1472 cm_data.buf_reservedBufs += nbuffers;
1475 lock_ReleaseWrite(&buf_globalLock);
1479 /* called without global lock held, releases reservation held by
1480 * buf_ReserveBuffers.
1482 void buf_UnreserveBuffers(afs_uint64 nbuffers)
1484 lock_ObtainWrite(&buf_globalLock);
1485 cm_data.buf_reservedBufs -= nbuffers;
1486 if (cm_data.buf_reserveWaiting) {
1487 cm_data.buf_reserveWaiting = 0;
1488 osi_Wakeup((LONG_PTR) &cm_data.buf_reservedBufs);
1490 lock_ReleaseWrite(&buf_globalLock);
1493 /* truncate the buffers past sizep, zeroing out the page, if we don't
1494 * end on a page boundary.
1496 * Requires cm_bufCreateLock to be write locked.
1498 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1502 cm_buf_t *nbufp; /* next buffer, if didRelease */
1508 /* assert that cm_bufCreateLock is held in write mode */
1509 lock_AssertWrite(&scp->bufCreateLock);
1511 i = BUF_FILEHASH(&scp->fid);
1513 lock_ObtainRead(&buf_globalLock);
1514 bufp = cm_data.buf_fileHashTablepp[i];
1516 lock_ReleaseRead(&buf_globalLock);
1520 buf_HoldLocked(bufp);
1521 lock_ReleaseRead(&buf_globalLock);
1523 lock_ObtainMutex(&bufp->mx);
1525 bufEnd.HighPart = 0;
1526 bufEnd.LowPart = cm_data.buf_blockSize;
1527 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1529 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1530 LargeIntegerLessThan(*sizep, bufEnd)) {
1531 buf_WaitIO(scp, bufp);
1533 lock_ObtainWrite(&scp->rw);
1535 /* make sure we have a callback (so we have the right value for
1536 * the length), and wait for it to be safe to do a truncate.
1538 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1539 CM_SCACHESYNC_NEEDCALLBACK
1540 | CM_SCACHESYNC_GETSTATUS
1541 | CM_SCACHESYNC_SETSIZE
1542 | CM_SCACHESYNC_BUFLOCKED);
1545 /* if we succeeded in our locking, and this applies to the right
1546 * file, and the truncate request overlaps the buffer either
1547 * totally or partially, then do something.
1549 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1550 && LargeIntegerLessThan(*sizep, bufEnd)) {
1553 /* destroy the buffer, turning off its dirty bit, if
1554 * we're truncating the whole buffer. Otherwise, set
1555 * the dirty bit, and clear out the tail of the buffer
1556 * if we just overlap some.
1558 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1559 /* truncating the entire page */
1560 bufp->flags &= ~CM_BUF_DIRTY;
1561 bufp->dirty_offset = 0;
1562 bufp->dirty_length = 0;
1563 bufp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
1564 bufp->dirtyCounter++;
1567 /* don't set dirty, since dirty implies
1568 * currently up-to-date. Don't need to do this,
1569 * since we'll update the length anyway.
1571 * Zero out remainder of the page, in case we
1572 * seek and write past EOF, and make this data
1575 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1576 osi_assertx(bufferPos != 0, "non-zero bufferPos");
1577 memset(bufp->datap + bufferPos, 0,
1578 cm_data.buf_blockSize - bufferPos);
1582 cm_SyncOpDone( scp, bufp,
1583 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
1584 | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_BUFLOCKED);
1586 lock_ReleaseWrite(&scp->rw);
1587 lock_ReleaseMutex(&bufp->mx);
1590 nbufp = bufp->fileHashp;
1594 /* This forces the loop to end and the error code
1595 * to be returned. */
1603 buf_ValidateBufQueues();
1604 #endif /* TESTING */
1610 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1613 cm_buf_t *bp; /* buffer we're hacking on */
1618 i = BUF_FILEHASH(&scp->fid);
1621 lock_ObtainRead(&buf_globalLock);
1622 bp = cm_data.buf_fileHashTablepp[i];
1625 lock_ReleaseRead(&buf_globalLock);
1627 for (; bp; bp = nbp) {
1628 didRelease = 0; /* haven't released this buffer yet */
1630 /* clean buffer synchronously */
1631 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1632 lock_ObtainMutex(&bp->mx);
1634 /* start cleaning the buffer, and wait for it to finish */
1635 buf_CleanAsyncLocked(bp, reqp, NULL);
1636 buf_WaitIO(scp, bp);
1637 lock_ReleaseMutex(&bp->mx);
1640 * if the error for the previous buffer was BADFD
1641 * then all buffers for the FID are bad. Do not
1642 * attempt to stabalize.
1644 if (code != CM_ERROR_BADFD) {
1645 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1646 if (code && code != CM_ERROR_BADFD)
1649 if (code == CM_ERROR_BADFD) {
1650 /* if the scp's FID is bad its because we received VNOVNODE
1651 * when attempting to FetchStatus before the write. This
1652 * page therefore contains data that can no longer be stored.
1654 lock_ObtainMutex(&bp->mx);
1655 bp->flags &= ~CM_BUF_DIRTY;
1656 bp->flags |= CM_BUF_ERROR;
1657 bp->error = CM_ERROR_BADFD;
1658 bp->dirty_offset = 0;
1659 bp->dirty_length = 0;
1660 bp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
1662 lock_ReleaseMutex(&bp->mx);
1665 /* actually, we only know that buffer is clean if ref
1666 * count is 1, since we don't have buffer itself locked.
1668 if (!(bp->flags & CM_BUF_DIRTY)) {
1669 lock_ObtainWrite(&buf_globalLock);
1670 if (bp->refCount == 1) { /* bp is held above */
1671 nbp = bp->fileHashp;
1673 buf_HoldLocked(nbp);
1674 buf_ReleaseLocked(bp, TRUE);
1678 lock_ReleaseWrite(&buf_globalLock);
1682 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1687 lock_ObtainRead(&buf_globalLock);
1688 nbp = bp->fileHashp;
1690 buf_HoldLocked(nbp);
1691 buf_ReleaseLocked(bp, FALSE);
1692 lock_ReleaseRead(&buf_globalLock);
1694 } /* for loop over a bunch of buffers */
1697 buf_ValidateBufQueues();
1698 #endif /* TESTING */
1704 /* Must be called with scp->rw held */
1705 long buf_ForceDataVersion(cm_scache_t * scp, afs_uint64 fromVersion, afs_uint64 toVersion)
1711 lock_AssertAny(&scp->rw);
1713 i = BUF_FILEHASH(&scp->fid);
1715 lock_ObtainRead(&buf_globalLock);
1717 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp = bp->fileHashp) {
1718 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1719 if (bp->dataVersion == fromVersion) {
1720 bp->dataVersion = toVersion;
1725 lock_ReleaseRead(&buf_globalLock);
1733 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1737 cm_buf_t *bp; /* buffer we're hacking on */
1738 cm_buf_t *nbp; /* next one */
1741 i = BUF_FILEHASH(&scp->fid);
1743 lock_ObtainRead(&buf_globalLock);
1744 bp = cm_data.buf_fileHashTablepp[i];
1747 lock_ReleaseRead(&buf_globalLock);
1748 for (; bp; bp = nbp) {
1749 /* clean buffer synchronously */
1750 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1751 lock_ObtainMutex(&bp->mx);
1752 if (bp->flags & CM_BUF_DIRTY) {
1753 if (userp && userp != bp->userp) {
1756 cm_ReleaseUser(bp->userp);
1761 case CM_ERROR_NOSUCHFILE:
1762 case CM_ERROR_BADFD:
1763 case CM_ERROR_NOACCESS:
1764 case CM_ERROR_QUOTA:
1765 case CM_ERROR_SPACE:
1766 case CM_ERROR_TOOBIG:
1767 case CM_ERROR_READONLY:
1768 case CM_ERROR_NOSUCHPATH:
1770 * Apply the previous fatal error to this buffer.
1771 * Do not waste the time attempting to store to
1772 * the file server when we know it will fail.
1774 bp->flags &= ~CM_BUF_DIRTY;
1775 bp->flags |= CM_BUF_ERROR;
1776 bp->dirty_offset = 0;
1777 bp->dirty_length = 0;
1779 bp->dataVersion = CM_BUF_VERSION_BAD;
1782 case CM_ERROR_TIMEDOUT:
1783 case CM_ERROR_ALLDOWN:
1784 case CM_ERROR_ALLBUSY:
1785 case CM_ERROR_ALLOFFLINE:
1786 case CM_ERROR_CLOCKSKEW:
1787 /* do not mark the buffer in error state but do
1788 * not attempt to complete the rest either.
1792 code = buf_CleanAsyncLocked(bp, reqp, &wasDirty);
1793 if (bp->flags & CM_BUF_ERROR) {
1799 buf_CleanWait(scp, bp, TRUE);
1801 lock_ReleaseMutex(&bp->mx);
1804 lock_ObtainRead(&buf_globalLock);
1805 nbp = bp->fileHashp;
1807 buf_HoldLocked(nbp);
1808 buf_ReleaseLocked(bp, FALSE);
1809 lock_ReleaseRead(&buf_globalLock);
1810 } /* for loop over a bunch of buffers */
1813 buf_ValidateBufQueues();
1814 #endif /* TESTING */
1822 buf_ValidateBufQueues(void)
1824 cm_buf_t * bp, *bpb, *bpf, *bpa;
1825 afs_uint32 countf=0, countb=0, counta=0;
1827 lock_ObtainRead(&buf_globalLock);
1828 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1829 if (bp->magic != CM_BUF_MAGIC)
1830 osi_panic("buf magic error",__FILE__,__LINE__);
1835 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
1836 if (bp->magic != CM_BUF_MAGIC)
1837 osi_panic("buf magic error",__FILE__,__LINE__);
1842 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
1843 if (bp->magic != CM_BUF_MAGIC)
1844 osi_panic("buf magic error",__FILE__,__LINE__);
1848 lock_ReleaseRead(&buf_globalLock);
1850 if (countb != countf)
1851 osi_panic("buf magic error",__FILE__,__LINE__);
1853 if (counta != cm_data.buf_nbuffers)
1854 osi_panic("buf magic error",__FILE__,__LINE__);
1856 #endif /* TESTING */
1858 /* dump the contents of the buf_scacheHashTablepp. */
1859 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
1866 if (cm_data.buf_scacheHashTablepp == NULL)
1870 lock_ObtainRead(&buf_globalLock);
1872 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\r\n",
1873 cookie, cm_data.buf_hashSize);
1874 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1876 for (i = 0; i < cm_data.buf_hashSize; i++)
1878 for (bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp)
1880 StringCbPrintfA(output, sizeof(output),
1881 "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d, "
1882 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1883 "flags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
1884 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
1885 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
1886 bp->offset.LowPart, bp->dataVersion, bp->flags,
1887 bp->cmFlags, bp->error, bp->refCount);
1888 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1892 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\r\n", cookie);
1893 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1895 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_freeListEndp\r\n", cookie);
1896 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1897 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1898 StringCbPrintfA(output, sizeof(output),
1899 "%s bp=0x%08X, fid (cell=%d, volume=%d, "
1900 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1901 "flags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
1902 cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
1903 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
1904 bp->offset.LowPart, bp->dataVersion, bp->flags,
1905 bp->cmFlags, bp->error, bp->refCount);
1906 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1908 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_FreeListEndp.\r\n", cookie);
1909 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1911 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_dirtyListp\r\n", cookie);
1912 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1913 for(bp = cm_data.buf_dirtyListp; bp; bp=bp->dirtyp) {
1914 StringCbPrintfA(output, sizeof(output),
1915 "%s bp=0x%08X, fid (cell=%d, volume=%d, "
1916 "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1917 "flags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
1918 cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
1919 bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
1920 bp->offset.LowPart, bp->dataVersion, bp->flags,
1921 bp->cmFlags, bp->error, bp->refCount);
1922 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1924 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_dirtyListp.\r\n", cookie);
1925 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1928 lock_ReleaseRead(&buf_globalLock);
1932 void buf_ForceTrace(BOOL flush)
1941 len = GetTempPath(sizeof(buf)-10, buf);
1942 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
1943 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
1944 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1945 if (handle == INVALID_HANDLE_VALUE) {
1946 osi_panic("Cannot create log file", __FILE__, __LINE__);
1948 osi_LogPrint(buf_logp, handle);
1950 FlushFileBuffers(handle);
1951 CloseHandle(handle);
1954 long buf_DirtyBuffersExist(cm_fid_t *fidp)
1957 afs_uint32 bcount = 0;
1960 i = BUF_FILEHASH(fidp);
1962 for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->allp, bcount++) {
1963 if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY))
1970 long buf_CleanDirtyBuffers(cm_scache_t *scp)
1973 afs_uint32 bcount = 0;
1974 cm_fid_t * fidp = &scp->fid;
1976 for (bp = cm_data.buf_allp; bp; bp=bp->allp, bcount++) {
1977 if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
1979 lock_ObtainMutex(&bp->mx);
1980 bp->cmFlags &= ~CM_BUF_CMSTORING;
1981 bp->flags &= ~CM_BUF_DIRTY;
1982 bp->dirty_offset = 0;
1983 bp->dirty_length = 0;
1984 bp->flags |= CM_BUF_ERROR;
1985 bp->error = VNOVNODE;
1986 bp->dataVersion = CM_BUF_VERSION_BAD; /* bad */
1988 if (bp->flags & CM_BUF_WAITING) {
1989 osi_Log2(buf_logp, "BUF CleanDirtyBuffers Waking [scp 0x%x] bp 0x%x", scp, bp);
1990 osi_Wakeup((long) &bp);
1992 lock_ReleaseMutex(&bp->mx);