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>
24 #include "cm_memmap.h"
27 #define TRACE_BUFFER 1
30 extern void afsi_log(char *pattern, ...);
32 /* This module implements the buffer package used by the local transaction
33 * system (cm). It is initialized by calling cm_Init, which calls buf_Init;
34 * it must be initalized before any of its main routines are called.
36 * Each buffer is hashed into a hash table by file ID and offset, and if its
37 * reference count is zero, it is also in a free list.
39 * There are two locks involved in buffer processing. The global lock
40 * buf_globalLock protects all of the global variables defined in this module,
41 * the reference counts and hash pointers in the actual cm_buf_t structures,
42 * and the LRU queue pointers in the buffer structures.
44 * The mutexes in the buffer structures protect the remaining fields in the
45 * buffers, as well the data itself.
47 * The locking hierarchy here is this:
49 * - resv multiple simul. buffers reservation
50 * - lock buffer I/O flags
51 * - lock buffer's mutex
52 * - lock buf_globalLock
56 /* global debugging log */
57 osi_log_t *buf_logp = NULL;
59 /* Global lock protecting hash tables and free lists */
60 osi_rwlock_t buf_globalLock;
62 /* ptr to head of the free list (most recently used) and the
63 * tail (the guy to remove first). We use osi_Q* functions
64 * to put stuff in buf_freeListp, and maintain the end
68 /* a pointer to a list of all buffers, just so that we can find them
69 * easily for debugging, and for the incr syncer. Locked under
73 /* defaults setup; these variables may be manually assigned into
74 * before calling cm_Init, as a way of changing these defaults.
77 /* callouts for reading and writing data, etc */
78 cm_buf_ops_t *cm_buf_opsp;
81 /* for experimental disk caching support in Win95 client */
82 cm_buf_t *buf_diskFreeListp;
83 cm_buf_t *buf_diskFreeListEndp;
84 cm_buf_t *buf_diskAllp;
85 extern int cm_diskCacheEnabled;
86 #endif /* DISKCACHE95 */
88 /* set this to 1 when we are terminating to prevent access attempts */
89 static int buf_ShutdownFlag = 0;
91 /* hold a reference to an already held buffer */
92 void buf_Hold(cm_buf_t *bp)
94 osi_assert(bp->magic == CM_BUF_MAGIC);
95 lock_ObtainWrite(&buf_globalLock);
97 lock_ReleaseWrite(&buf_globalLock);
100 /* incremental sync daemon. Writes 1/10th of all the buffers every 5000 ms */
101 void buf_IncrSyncer(long parm)
103 cm_buf_t *bp; /* buffer we're hacking on; held */
104 long i; /* counter */
105 long nAtOnce; /* how many to do at once */
108 lock_ObtainWrite(&buf_globalLock);
109 bp = cm_data.buf_allp;
111 lock_ReleaseWrite(&buf_globalLock);
112 nAtOnce = cm_data.buf_nbuffers / 10;
113 while (buf_ShutdownFlag == 0) {
115 i = SleepEx(5000, 1);
116 if (i != 0) continue;
121 if (buf_ShutdownFlag == 1)
124 /* now go through our percentage of the buffers */
125 for (i=0; i<nAtOnce; i++) {
126 /* don't want its identity changing while we're
127 * messing with it, so must do all of this with
131 /* start cleaning the buffer; don't touch log pages since
132 * the log code counts on knowing exactly who is writing
133 * a log page at any given instant.
136 req.flags |= CM_REQ_NORETRY;
137 buf_CleanAsync(bp, &req);
139 /* now advance to the next buffer; the allp chain never changes,
140 * and so can be followed even when holding no locks.
142 lock_ObtainWrite(&buf_globalLock);
143 buf_LockedRelease(bp);
146 bp = cm_data.buf_allp;
148 lock_ReleaseWrite(&buf_globalLock);
149 } /* for loop over a bunch of buffers */
150 } /* whole daemon's while loop */
154 buf_ValidateBuffers(void)
156 cm_buf_t * bp, *bpf, *bpa, *bpb;
157 afs_uint32 countb = 0, countf = 0, counta = 0;
159 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
160 if (bp->magic != CM_BUF_MAGIC) {
161 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
162 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
168 if (countb > cm_data.buf_nbuffers) {
169 afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
170 fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
175 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
176 if (bp->magic != CM_BUF_MAGIC) {
177 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
178 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
184 if (countf > cm_data.buf_nbuffers) {
185 afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
186 fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
191 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
192 if (bp->magic != CM_BUF_MAGIC) {
193 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
194 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
200 if (counta > cm_data.buf_nbuffers) {
201 afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
202 fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
207 if (countb != countf) {
208 afsi_log("cm_ValidateBuffers failure: countb != countf");
209 fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
213 if (counta != cm_data.buf_nbuffers) {
214 afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
215 fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
222 void buf_Shutdown(void)
224 buf_ShutdownFlag = 1;
227 /* initialize the buffer package; called with no locks
228 * held during the initialization phase.
230 long buf_Init(int newFile, cm_buf_ops_t *opsp, long nbuffers)
232 static osi_once_t once;
241 cm_data.buf_nbuffers = nbuffers;
243 /* Have to be able to reserve a whole chunk */
244 if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
245 return CM_ERROR_TOOFEWBUFS;
248 /* recall for callouts */
251 if (osi_Once(&once)) {
252 /* initialize global locks */
253 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock");
256 /* remember this for those who want to reset it */
257 cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
259 /* lower hash size to a prime number */
260 cm_data.buf_hashSize = osi_PrimeLessThan(CM_BUF_HASHSIZE);
262 /* create hash table */
263 memset((void *)cm_data.buf_hashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
265 /* another hash table */
266 memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
268 /* create buffer headers and put in free list */
269 bp = cm_data.bufHeaderBaseAddress;
270 data = cm_data.bufDataBaseAddress;
271 cm_data.buf_allp = NULL;
273 for (i=0; i<cm_data.buf_nbuffers; i++) {
274 osi_assert(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress);
275 osi_assert(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData);
277 /* allocate and zero some storage */
278 memset(bp, 0, sizeof(cm_buf_t));
279 bp->magic = CM_BUF_MAGIC;
280 /* thread on list of all buffers */
281 bp->allp = cm_data.buf_allp;
282 cm_data.buf_allp = bp;
284 osi_QAdd((osi_queue_t **)&cm_data.buf_freeListp, &bp->q);
285 bp->flags |= CM_BUF_INLRU;
286 lock_InitializeMutex(&bp->mx, "Buffer mutex");
288 /* grab appropriate number of bytes from aligned zone */
291 /* setup last buffer pointer */
293 cm_data.buf_freeListEndp = bp;
297 data += cm_data.buf_blockSize;
300 /* none reserved at first */
301 cm_data.buf_reservedBufs = 0;
303 /* just for safety's sake */
304 cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
306 bp = cm_data.bufHeaderBaseAddress;
307 data = cm_data.bufDataBaseAddress;
309 for (i=0; i<cm_data.buf_nbuffers; i++) {
310 lock_InitializeMutex(&bp->mx, "Buffer mutex");
313 bp->waitRequests = 0;
314 bp->flags &= ~CM_BUF_WAITING;
320 buf_ValidateBufQueues();
324 /* init the buffer trace log */
325 buf_logp = osi_LogCreate("buffer", 1000);
326 osi_LogEnable(buf_logp);
331 /* and create the incr-syncer */
332 phandle = thrd_Create(0, 0,
333 (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
336 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
338 CloseHandle(phandle);
343 buf_ValidateBufQueues();
348 /* add nbuffers to the buffer pool, if possible.
349 * Called with no locks held.
351 long buf_AddBuffers(long nbuffers)
354 /* The size of a virtual cache cannot be changed after it has
355 * been created. Subsequent calls to MapViewofFile() with
356 * an existing mapping object name would not allow the
357 * object to be resized. Return failure immediately.
359 * A similar problem now occurs with the persistent cache
360 * given that the memory mapped file now contains a complex
363 afsi_log("request to add %d buffers to the existing cache of size %d denied",
364 nbuffers, cm_data.buf_nbuffers);
366 return CM_ERROR_INVAL;
372 data = malloc(buf_nbuffers * cm_data.buf_blockSize);
374 /* Create buffer headers and put in free list */
375 bp = malloc(nbuffers * sizeof(*bp));
377 for (i=0; i<nbuffers; i++) {
378 memset(bp, 0, sizeof(*bp));
380 lock_InitializeMutex(&bp->mx, "cm_buf_t");
382 /* grab appropriate number of bytes from aligned zone */
385 bp->flags |= CM_BUF_INLRU;
387 lock_ObtainWrite(&buf_globalLock);
388 /* note that buf_allp chain is covered by buf_globalLock now */
389 bp->allp = cm_data.buf_allp;
390 cm_data.buf_allp = bp;
391 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
392 if (!cm_data.buf_freeListEndp)
393 cm_data.buf_freeListEndp = bp;
394 cm_data.buf_nbuffers++;
395 lock_ReleaseWrite(&buf_globalLock);
398 data += cm_data.buf_blockSize;
400 } /* for loop over all buffers */
406 /* interface to set the number of buffers to an exact figure.
407 * Called with no locks held.
409 long buf_SetNBuffers(long nbuffers)
412 return CM_ERROR_INVAL;
413 if (nbuffers == cm_data.buf_nbuffers)
415 else if (nbuffers > cm_data.buf_nbuffers)
416 return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
418 return CM_ERROR_INVAL;
421 /* release a buffer. Buffer must be referenced, but unlocked. */
422 void buf_Release(cm_buf_t *bp)
424 lock_ObtainWrite(&buf_globalLock);
425 buf_LockedRelease(bp);
426 lock_ReleaseWrite(&buf_globalLock);
429 /* wait for reading or writing to clear; called with write-locked
430 * buffer, and returns with locked buffer.
432 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
435 osi_assert(scp->magic == CM_SCACHE_MAGIC);
436 osi_assert(bp->magic == CM_BUF_MAGIC);
439 /* if no IO is happening, we're done */
440 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
443 /* otherwise I/O is happening, but some other thread is waiting for
444 * the I/O already. Wait for that guy to figure out what happened,
445 * and then check again.
447 if ( bp->flags & CM_BUF_WAITING ) {
450 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%x", bp);
452 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%x", bp);
453 bp->flags |= CM_BUF_WAITING;
454 bp->waitCount = bp->waitRequests = 1;
456 osi_SleepM((long) bp, &bp->mx);
457 lock_ObtainMutex(&bp->mx);
458 osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%x", bp);
460 if (bp->waitCount == 0) {
461 osi_Log1(afsd_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%x", bp);
462 bp->flags &= ~CM_BUF_WAITING;
463 bp->waitRequests = 0;
467 scp = cm_FindSCache(&bp->fid);
470 lock_ObtainMutex(&scp->mx);
471 if (scp->flags & CM_SCACHEFLAG_WAITING) {
472 osi_Log1(buf_logp, "buf_WaitIO waking scp 0x%x", scp);
473 osi_Wakeup(&scp->flags);
474 lock_ReleaseMutex(&scp->mx);
479 /* if we get here, the IO is done, but we may have to wakeup people waiting for
480 * the I/O to complete. Do so.
482 if (bp->flags & CM_BUF_WAITING) {
483 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%x", bp);
484 osi_Wakeup((long) bp);
486 osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%x", (long) bp);
489 /* code to drop reference count while holding buf_globalLock */
490 void buf_LockedRelease(cm_buf_t *bp)
492 /* ensure that we're in the LRU queue if our ref count is 0 */
493 osi_assert(bp->refCount > 0);
494 if (--bp->refCount == 0) {
495 if (!(bp->flags & CM_BUF_INLRU)) {
496 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
498 /* watch for transition from empty to one element */
499 if (!cm_data.buf_freeListEndp)
500 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
501 bp->flags |= CM_BUF_INLRU;
506 /* find a buffer, if any, for a particular file ID and offset. Assumes
507 * that buf_globalLock is write locked when called.
509 cm_buf_t *buf_LockedFind(struct cm_scache *scp, osi_hyper_t *offsetp)
514 i = BUF_HASH(&scp->fid, offsetp);
515 for(bp = cm_data.buf_hashTablepp[i]; bp; bp=bp->hashp) {
516 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
517 && offsetp->LowPart == bp->offset.LowPart
518 && offsetp->HighPart == bp->offset.HighPart) {
524 /* return whatever we found, if anything */
528 /* find a buffer with offset *offsetp for vnode *scp. Called
529 * with no locks held.
531 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
535 lock_ObtainWrite(&buf_globalLock);
536 bp = buf_LockedFind(scp, offsetp);
537 lock_ReleaseWrite(&buf_globalLock);
542 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
545 * Makes sure that there's only one person writing this block
546 * at any given time, and also ensures that the log is forced sufficiently far,
547 * if this buffer contains logged data.
549 void buf_LockedCleanAsync(cm_buf_t *bp, cm_req_t *reqp)
553 osi_assert(bp->magic == CM_BUF_MAGIC);
555 while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
556 lock_ReleaseMutex(&bp->mx);
558 code = (*cm_buf_opsp->Writep)(&bp->fid, &bp->offset,
559 cm_data.buf_blockSize, 0, bp->userp,
562 lock_ObtainMutex(&bp->mx);
567 /* Disk cache support */
568 /* write buffer to disk cache (synchronous for now) */
569 diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
570 #endif /* DISKCACHE95 */
573 /* do logging after call to GetLastError, or else */
574 osi_Log2(buf_logp, "buf_CleanAsync starts I/O on 0x%x, done=%d", bp, code);
576 /* if someone was waiting for the I/O that just completed or failed,
579 if (bp->flags & CM_BUF_WAITING) {
580 /* turn off flags and wakeup users */
581 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%x", bp);
582 osi_Wakeup((long) bp);
586 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
587 * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
588 * The buffer must already be clean, and no I/O should be happening to it.
590 void buf_Recycle(cm_buf_t *bp)
595 cm_buf_t *prevBp, *nextBp;
597 osi_assert(bp->magic == CM_BUF_MAGIC);
599 /* if we get here, we know that the buffer still has a 0 ref count,
600 * and that it is clean and has no currently pending I/O. This is
601 * the dude to return.
602 * Remember that as long as the ref count is 0, we know that we won't
603 * have any lock conflicts, so we can grab the buffer lock out of
604 * order in the locking hierarchy.
606 osi_Log2( buf_logp, "buf_Recycle recycles 0x%x, off 0x%x",
607 bp, bp->offset.LowPart);
609 osi_assert(bp->refCount == 0);
610 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)));
611 lock_AssertWrite(&buf_globalLock);
613 if (bp->flags & CM_BUF_INHASH) {
614 /* Remove from hash */
616 i = BUF_HASH(&bp->fid, &bp->offset);
617 lbpp = &(cm_data.buf_hashTablepp[i]);
618 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
619 if (tbp == bp) break;
622 /* we better find it */
623 osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
625 *lbpp = bp->hashp; /* hash out */
627 /* Remove from file hash */
629 i = BUF_FILEHASH(&bp->fid);
630 prevBp = bp->fileHashBackp;
631 nextBp = bp->fileHashp;
633 prevBp->fileHashp = nextBp;
635 cm_data.buf_fileHashTablepp[i] = nextBp;
637 nextBp->fileHashBackp = prevBp;
639 bp->flags &= ~CM_BUF_INHASH;
642 /* bump the soft reference counter now, to invalidate softRefs; no
643 * wakeup is required since people don't sleep waiting for this
648 /* make the fid unrecognizable */
649 memset(&bp->fid, 0, sizeof(cm_fid_t));
652 /* recycle a buffer, removing it from the free list, hashing in its new identity
653 * and returning it write-locked so that no one can use it. Called without
654 * any locks held, and can return an error if it loses the race condition and
655 * finds that someone else created the desired buffer.
657 * If success is returned, the buffer is returned write-locked.
659 * May be called with null scp and offsetp, if we're just trying to reclaim some
660 * space from the buffer pool. In that case, the buffer will be returned
661 * without being hashed into the hash table.
663 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
665 cm_buf_t *bp; /* buffer we're dealing with */
666 cm_buf_t *nextBp; /* next buffer in file hash chain */
670 cm_InitReq(&req); /* just in case */
673 buf_ValidateBufQueues();
678 lock_ObtainWrite(&buf_globalLock);
679 /* check to see if we lost the race */
681 if (bp = buf_LockedFind(scp, offsetp)) {
683 lock_ReleaseWrite(&buf_globalLock);
684 return CM_BUF_EXISTS;
688 /* for debugging, assert free list isn't empty, although we
689 * really should try waiting for a running tranasction to finish
690 * instead of this; or better, we should have a transaction
691 * throttler prevent us from entering this situation.
693 osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
695 /* look at all buffers in free list, some of which may temp.
696 * have high refcounts and which then should be skipped,
697 * starting cleaning I/O for those which are dirty. If we find
698 * a clean buffer, we rehash it, lock it and return it.
700 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
701 /* check to see if it really has zero ref count. This
702 * code can bump refcounts, at least, so it may not be
705 if (bp->refCount > 0)
708 /* we don't have to lock buffer itself, since the ref
709 * count is 0 and we know it will stay zero as long as
710 * we hold the global lock.
713 /* don't recycle someone in our own chunk */
714 if (!cm_FidCmp(&bp->fid, &scp->fid)
715 && (bp->offset.LowPart & (-cm_chunkSize))
716 == (offsetp->LowPart & (-cm_chunkSize)))
719 /* if this page is being filled (!) or cleaned, see if
720 * the I/O has completed. If not, skip it, otherwise
721 * do the final processing for the I/O.
723 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
724 /* probably shouldn't do this much work while
725 * holding the big lock? Watch for contention
731 if (bp->flags & CM_BUF_DIRTY) {
732 /* if the buffer is dirty, start cleaning it and
733 * move on to the next buffer. We do this with
734 * just the lock required to minimize contention
738 lock_ReleaseWrite(&buf_globalLock);
740 /* grab required lock and clean; this only
741 * starts the I/O. By the time we're back,
742 * it'll still be marked dirty, but it will also
743 * have the WRITING flag set, so we won't get
746 buf_CleanAsync(bp, &req);
748 /* now put it back and go around again */
753 /* if we get here, we know that the buffer still has a 0
754 * ref count, and that it is clean and has no currently
755 * pending I/O. This is the dude to return.
756 * Remember that as long as the ref count is 0, we know
757 * that we won't have any lock conflicts, so we can grab
758 * the buffer lock out of order in the locking hierarchy.
762 /* clean up junk flags */
763 bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
764 bp->dataVersion = -1; /* unknown so far */
766 /* now hash in as our new buffer, and give it the
767 * appropriate label, if requested.
770 bp->flags |= CM_BUF_INHASH;
772 bp->offset = *offsetp;
773 i = BUF_HASH(&scp->fid, offsetp);
774 bp->hashp = cm_data.buf_hashTablepp[i];
775 cm_data.buf_hashTablepp[i] = bp;
776 i = BUF_FILEHASH(&scp->fid);
777 nextBp = cm_data.buf_fileHashTablepp[i];
778 bp->fileHashp = nextBp;
779 bp->fileHashBackp = NULL;
781 nextBp->fileHashBackp = bp;
782 cm_data.buf_fileHashTablepp[i] = bp;
785 /* prepare to return it. Start by giving it a good
789 /* and since it has a non-zero ref count, we should move
790 * it from the lru queue. It better be still there,
791 * since we've held the global (big) lock since we found
794 osi_assertx(bp->flags & CM_BUF_INLRU,
795 "buf_GetNewLocked: LRU screwup");
796 if (cm_data.buf_freeListEndp == bp) {
797 /* we're the last guy in this queue, so maintain it */
798 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
800 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
801 bp->flags &= ~CM_BUF_INLRU;
803 /* finally, grab the mutex so that people don't use it
804 * before the caller fills it with data. Again, no one
805 * should have been able to get to this dude to lock it.
807 osi_assertx(lock_TryMutex(&bp->mx),
808 "buf_GetNewLocked: TryMutex failed");
810 lock_ReleaseWrite(&buf_globalLock);
814 buf_ValidateBufQueues();
817 } /* for all buffers in lru queue */
818 lock_ReleaseWrite(&buf_globalLock);
819 } /* while loop over everything */
823 /* get a page, returning it held but unlocked. Doesn't fill in the page
824 * with I/O, since we're going to write the whole thing new.
826 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
830 osi_hyper_t pageOffset;
834 pageOffset.HighPart = offsetp->HighPart;
835 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
837 bp = buf_Find(scp, &pageOffset);
839 /* lock it and break out */
840 lock_ObtainMutex(&bp->mx);
844 /* otherwise, we have to create a page */
845 code = buf_GetNewLocked(scp, &pageOffset, &bp);
847 /* check if the buffer was created in a race condition branch.
848 * If so, go around so we can hold a reference to it.
850 if (code == CM_BUF_EXISTS)
853 /* something else went wrong */
857 /* otherwise, we have a locked buffer that we just created */
860 } /* big while loop */
863 if (bp->flags & CM_BUF_READING)
866 /* once it has been read once, we can unlock it and return it, still
867 * with its refcount held.
869 lock_ReleaseMutex(&bp->mx);
871 osi_Log3(buf_logp, "buf_GetNew returning bp 0x%x for file 0x%x, offset 0x%x",
872 bp, (long) scp, offsetp->LowPart);
876 /* get a page, returning it held but unlocked. Make sure it is complete */
877 /* The scp must be unlocked when passed to this function */
878 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
882 osi_hyper_t pageOffset;
883 unsigned long tcount;
888 #endif /* DISKCACHE95 */
891 pageOffset.HighPart = offsetp->HighPart;
892 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
896 buf_ValidateBufQueues();
899 bp = buf_Find(scp, &pageOffset);
901 /* lock it and break out */
902 lock_ObtainMutex(&bp->mx);
906 /* touch disk chunk to update LRU info */
907 diskcache_Touch(bp->dcp);
908 #endif /* DISKCACHE95 */
911 /* otherwise, we have to create a page */
912 code = buf_GetNewLocked(scp, &pageOffset, &bp);
914 /* check if the buffer was created in a race condition branch.
915 * If so, go around so we can hold a reference to it.
917 if (code == CM_BUF_EXISTS)
920 /* something else went wrong */
923 buf_ValidateBufQueues();
928 /* otherwise, we have a locked buffer that we just created */
931 } /* big while loop */
933 /* if we get here, we have a locked buffer that may have just been
934 * created, in which case it needs to be filled with data.
937 /* load the page; freshly created pages should be idle */
938 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
940 /* setup offset, event */
941 #ifndef DJGPP /* doesn't seem to be used */
942 bp->over.Offset = bp->offset.LowPart;
943 bp->over.OffsetHigh = bp->offset.HighPart;
946 /* start the I/O; may drop lock */
947 bp->flags |= CM_BUF_READING;
948 code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
951 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
952 bp->dcp = dcp; /* pointer to disk cache struct. */
953 #endif /* DISKCACHE95 */
956 /* failure or queued */
957 #ifndef DJGPP /* cm_bufRead always returns 0 */
958 if (code != ERROR_IO_PENDING) {
961 bp->flags |= CM_BUF_ERROR;
962 bp->flags &= ~CM_BUF_READING;
963 if (bp->flags & CM_BUF_WAITING) {
964 osi_Log1(buf_logp, "buf_Get Waking bp 0x%x", bp);
965 osi_Wakeup((long) bp);
967 lock_ReleaseMutex(&bp->mx);
970 buf_ValidateBufQueues();
977 /* otherwise, I/O completed instantly and we're done, except
978 * for padding the xfr out with 0s and checking for EOF
980 if (tcount < (unsigned long) cm_data.buf_blockSize) {
981 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
983 bp->flags |= CM_BUF_EOF;
985 bp->flags &= ~CM_BUF_READING;
986 if (bp->flags & CM_BUF_WAITING) {
987 osi_Log1(buf_logp, "buf_Get Waking bp 0x%x", bp);
988 osi_Wakeup((long) bp);
994 /* wait for reads, either that which we started above, or that someone
995 * else started. We don't care if we return a buffer being cleaned.
997 if (bp->flags & CM_BUF_READING)
1000 /* once it has been read once, we can unlock it and return it, still
1001 * with its refcount held.
1003 lock_ReleaseMutex(&bp->mx);
1006 /* now remove from queue; will be put in at the head (farthest from
1007 * being recycled) when we're done in buf_Release.
1009 lock_ObtainWrite(&buf_globalLock);
1010 if (bp->flags & CM_BUF_INLRU) {
1011 if (cm_data.buf_freeListEndp == bp)
1012 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1013 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
1014 bp->flags &= ~CM_BUF_INLRU;
1016 lock_ReleaseWrite(&buf_globalLock);
1018 osi_Log3(buf_logp, "buf_Get returning bp 0x%x for file 0x%x, offset 0x%x",
1019 bp, (long) scp, offsetp->LowPart);
1021 buf_ValidateBufQueues();
1022 #endif /* TESTING */
1026 /* count # of elements in the free list;
1027 * we don't bother doing the proper locking for accessing dataVersion or flags
1028 * since it is a pain, and this is really just an advisory call. If you need
1029 * to do better at some point, rewrite this function.
1031 long buf_CountFreeList(void)
1037 lock_ObtainRead(&buf_globalLock);
1038 for(bufp = cm_data.buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1039 /* if the buffer doesn't have an identity, or if the buffer
1040 * has been invalidate (by having its DV stomped upon), then
1041 * count it as free, since it isn't really being utilized.
1043 if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1046 lock_ReleaseRead(&buf_globalLock);
1050 /* clean a buffer synchronously */
1051 void buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1053 osi_assert(bp->magic == CM_BUF_MAGIC);
1055 lock_ObtainMutex(&bp->mx);
1056 buf_LockedCleanAsync(bp, reqp);
1057 lock_ReleaseMutex(&bp->mx);
1060 /* wait for a buffer's cleaning to finish */
1061 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp)
1063 osi_assert(bp->magic == CM_BUF_MAGIC);
1065 lock_ObtainMutex(&bp->mx);
1066 if (bp->flags & CM_BUF_WRITING) {
1067 buf_WaitIO(scp, bp);
1069 lock_ReleaseMutex(&bp->mx);
1072 /* set the dirty flag on a buffer, and set associated write-ahead log,
1073 * if there is one. Allow one to be added to a buffer, but not changed.
1075 * The buffer must be locked before calling this routine.
1077 void buf_SetDirty(cm_buf_t *bp)
1079 osi_assert(bp->magic == CM_BUF_MAGIC);
1080 osi_assert(bp->refCount > 0);
1082 osi_Log1(buf_logp, "buf_SetDirty 0x%x", bp);
1085 bp->flags |= CM_BUF_DIRTY;
1087 /* and turn off EOF flag, since it has associated data now */
1088 bp->flags &= ~CM_BUF_EOF;
1091 /* clean all buffers, reset log pointers and invalidate all buffers.
1092 * Called with no locks held, and returns with same.
1094 * This function is guaranteed to clean and remove the log ptr of all the
1095 * buffers that were dirty or had non-zero log ptrs before the call was
1096 * made. That's sufficient to clean up any garbage left around by recovery,
1097 * which is all we're counting on this for; there may be newly created buffers
1098 * added while we're running, but that should be OK.
1100 * In an environment where there are no transactions (artificially imposed, for
1101 * example, when switching the database to raw mode), this function is used to
1102 * make sure that all updates have been written to the disk. In that case, we don't
1103 * really require that we forget the log association between pages and logs, but
1104 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1105 * have to worry about invalidating data in the buffers.
1107 * This function is used at the end of recovery as paranoia to get the recovered
1108 * database out to disk. It removes all references to the recovery log and cleans
1111 long buf_CleanAndReset(void)
1117 lock_ObtainWrite(&buf_globalLock);
1118 for(i=0; i<cm_data.buf_hashSize; i++) {
1119 for(bp = cm_data.buf_hashTablepp[i]; bp; bp = bp->hashp) {
1120 if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1122 lock_ReleaseWrite(&buf_globalLock);
1124 /* now no locks are held; clean buffer and go on */
1126 buf_CleanAsync(bp, &req);
1127 buf_CleanWait(NULL, bp);
1129 /* relock and release buffer */
1130 lock_ObtainWrite(&buf_globalLock);
1131 buf_LockedRelease(bp);
1133 } /* over one bucket */
1134 } /* for loop over all hash buckets */
1137 lock_ReleaseWrite(&buf_globalLock);
1140 buf_ValidateBufQueues();
1141 #endif /* TESTING */
1143 /* and we're done */
1147 /* called without global lock being held, reserves buffers for callers
1148 * that need more than one held (not locked) at once.
1150 void buf_ReserveBuffers(long nbuffers)
1152 lock_ObtainWrite(&buf_globalLock);
1154 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1155 cm_data.buf_reserveWaiting = 1;
1156 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1157 osi_SleepW((long) &cm_data.buf_reservedBufs, &buf_globalLock);
1158 lock_ObtainWrite(&buf_globalLock);
1161 cm_data.buf_reservedBufs += nbuffers;
1165 lock_ReleaseWrite(&buf_globalLock);
1168 int buf_TryReserveBuffers(long nbuffers)
1172 lock_ObtainWrite(&buf_globalLock);
1173 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1177 cm_data.buf_reservedBufs += nbuffers;
1180 lock_ReleaseWrite(&buf_globalLock);
1184 /* called without global lock held, releases reservation held by
1185 * buf_ReserveBuffers.
1187 void buf_UnreserveBuffers(long nbuffers)
1189 lock_ObtainWrite(&buf_globalLock);
1190 cm_data.buf_reservedBufs -= nbuffers;
1191 if (cm_data.buf_reserveWaiting) {
1192 cm_data.buf_reserveWaiting = 0;
1193 osi_Wakeup((long) &cm_data.buf_reservedBufs);
1195 lock_ReleaseWrite(&buf_globalLock);
1198 /* truncate the buffers past sizep, zeroing out the page, if we don't
1199 * end on a page boundary.
1201 * Requires cm_bufCreateLock to be write locked.
1203 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1207 cm_buf_t *nbufp; /* next buffer, if didRelease */
1214 /* assert that cm_bufCreateLock is held in write mode */
1215 lock_AssertWrite(&scp->bufCreateLock);
1217 i = BUF_FILEHASH(&scp->fid);
1219 lock_ObtainWrite(&buf_globalLock);
1220 bufp = cm_data.buf_fileHashTablepp[i];
1222 lock_ReleaseWrite(&buf_globalLock);
1227 lock_ReleaseWrite(&buf_globalLock);
1228 for(; bufp; bufp = nbufp) {
1230 lock_ObtainMutex(&bufp->mx);
1232 bufEnd.HighPart = 0;
1233 bufEnd.LowPart = cm_data.buf_blockSize;
1234 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1236 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1237 LargeIntegerLessThan(*sizep, bufEnd)) {
1238 buf_WaitIO(scp, bufp);
1240 lock_ObtainMutex(&scp->mx);
1242 /* make sure we have a callback (so we have the right value for
1243 * the length), and wait for it to be safe to do a truncate.
1245 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1246 CM_SCACHESYNC_NEEDCALLBACK
1247 | CM_SCACHESYNC_GETSTATUS
1248 | CM_SCACHESYNC_SETSIZE
1249 | CM_SCACHESYNC_BUFLOCKED);
1250 /* if we succeeded in our locking, and this applies to the right
1251 * file, and the truncate request overlaps the buffer either
1252 * totally or partially, then do something.
1254 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1255 && LargeIntegerLessThan(*sizep, bufEnd)) {
1257 lock_ObtainWrite(&buf_globalLock);
1259 /* destroy the buffer, turning off its dirty bit, if
1260 * we're truncating the whole buffer. Otherwise, set
1261 * the dirty bit, and clear out the tail of the buffer
1262 * if we just overlap some.
1264 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1265 /* truncating the entire page */
1266 bufp->flags &= ~CM_BUF_DIRTY;
1267 bufp->dataVersion = -1; /* known bad */
1268 bufp->dirtyCounter++;
1271 /* don't set dirty, since dirty implies
1272 * currently up-to-date. Don't need to do this,
1273 * since we'll update the length anyway.
1275 * Zero out remainder of the page, in case we
1276 * seek and write past EOF, and make this data
1279 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1280 osi_assert(bufferPos != 0);
1281 memset(bufp->datap + bufferPos, 0,
1282 cm_data.buf_blockSize - bufferPos);
1285 lock_ReleaseWrite(&buf_globalLock);
1288 lock_ReleaseMutex(&scp->mx);
1289 lock_ReleaseMutex(&bufp->mx);
1291 lock_ObtainWrite(&buf_globalLock);
1292 nbufp = bufp->fileHashp;
1293 if (nbufp) nbufp->refCount++;
1294 buf_LockedRelease(bufp);
1295 lock_ReleaseWrite(&buf_globalLock);
1298 /* bail out early if we fail */
1300 /* at this point, nbufp is held; bufp has already been
1307 buf_ValidateBufQueues();
1308 #endif /* TESTING */
1315 buf_ValidateBufQueues();
1316 #endif /* TESTING */
1322 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1325 cm_buf_t *bp; /* buffer we're hacking on */
1330 i = BUF_FILEHASH(&scp->fid);
1333 lock_ObtainWrite(&buf_globalLock);
1334 bp = cm_data.buf_fileHashTablepp[i];
1337 lock_ReleaseWrite(&buf_globalLock);
1338 for (; bp; bp = nbp) {
1339 didRelease = 0; /* haven't released this buffer yet */
1341 /* clean buffer synchronously */
1342 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1343 lock_ObtainMutex(&bp->mx);
1345 /* start cleaning the buffer, and wait for it to finish */
1346 buf_LockedCleanAsync(bp, reqp);
1347 buf_WaitIO(scp, bp);
1348 lock_ReleaseMutex(&bp->mx);
1350 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1354 lock_ObtainWrite(&buf_globalLock);
1355 /* actually, we only know that buffer is clean if ref
1356 * count is 1, since we don't have buffer itself locked.
1358 if (!(bp->flags & CM_BUF_DIRTY)) {
1359 if (bp->refCount == 1) { /* bp is held above */
1360 buf_LockedRelease(bp);
1361 nbp = bp->fileHashp;
1368 lock_ReleaseWrite(&buf_globalLock);
1370 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1375 lock_ObtainWrite(&buf_globalLock);
1376 if (nbp = bp->fileHashp)
1378 buf_LockedRelease(bp);
1379 lock_ReleaseWrite(&buf_globalLock);
1381 } /* for loop over a bunch of buffers */
1384 buf_ValidateBufQueues();
1385 #endif /* TESTING */
1391 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1394 cm_buf_t *bp; /* buffer we're hacking on */
1395 cm_buf_t *nbp; /* next one */
1398 i = BUF_FILEHASH(&scp->fid);
1401 lock_ObtainWrite(&buf_globalLock);
1402 bp = cm_data.buf_fileHashTablepp[i];
1405 lock_ReleaseWrite(&buf_globalLock);
1406 for (; bp; bp = nbp) {
1407 /* clean buffer synchronously */
1408 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1411 lock_ObtainMutex(&bp->mx);
1413 cm_ReleaseUser(bp->userp);
1415 lock_ReleaseMutex(&bp->mx);
1417 buf_CleanAsync(bp, reqp);
1418 buf_CleanWait(scp, bp);
1419 lock_ObtainMutex(&bp->mx);
1420 if (bp->flags & CM_BUF_ERROR) {
1421 if (code == 0 || code == -1)
1426 lock_ReleaseMutex(&bp->mx);
1429 lock_ObtainWrite(&buf_globalLock);
1430 buf_LockedRelease(bp);
1431 nbp = bp->fileHashp;
1434 lock_ReleaseWrite(&buf_globalLock);
1435 } /* for loop over a bunch of buffers */
1438 buf_ValidateBufQueues();
1439 #endif /* TESTING */
1447 buf_ValidateBufQueues(void)
1449 cm_buf_t * bp, *bpb, *bpf, *bpa;
1450 afs_uint32 countf=0, countb=0, counta=0;
1452 lock_ObtainRead(&buf_globalLock);
1453 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1454 if (bp->magic != CM_BUF_MAGIC)
1460 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
1461 if (bp->magic != CM_BUF_MAGIC)
1467 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
1468 if (bp->magic != CM_BUF_MAGIC)
1473 lock_ReleaseRead(&buf_globalLock);
1475 if (countb != countf)
1478 if (counta != cm_data.buf_nbuffers)
1481 #endif /* TESTING */
1483 /* dump the contents of the buf_hashTablepp. */
1484 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
1491 if (cm_data.buf_hashTablepp == NULL)
1495 lock_ObtainRead(&buf_globalLock);
1497 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\n",
1498 cookie, cm_data.buf_hashSize);
1499 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1501 for (i = 0; i < cm_data.buf_hashSize; i++)
1503 for (bp = cm_data.buf_hashTablepp[i]; bp; bp=bp->hashp)
1507 StringCbPrintfA(output, sizeof(output), "vnode=%d, unique=%d), size=%d refCount=%d\n",
1508 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
1509 bp->fid.vnode, bp->fid.unique, bp->size, bp->refCount);
1510 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1515 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\n", cookie);
1516 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1519 lock_ReleaseRead(&buf_globalLock);
1523 void buf_ForceTrace(BOOL flush)
1532 len = GetTempPath(sizeof(buf)-10, buf);
1533 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
1534 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
1535 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1536 if (handle == INVALID_HANDLE_VALUE) {
1537 osi_panic("Cannot create log file", __FILE__, __LINE__);
1539 osi_LogPrint(buf_logp, handle);
1541 FlushFileBuffers(handle);
1542 CloseHandle(handle);