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>
25 #include "cm_memmap.h"
28 #define TRACE_BUFFER 1
31 extern void afsi_log(char *pattern, ...);
33 /* This module implements the buffer package used by the local transaction
34 * system (cm). It is initialized by calling cm_Init, which calls buf_Init;
35 * it must be initalized before any of its main routines are called.
37 * Each buffer is hashed into a hash table by file ID and offset, and if its
38 * reference count is zero, it is also in a free list.
40 * There are two locks involved in buffer processing. The global lock
41 * buf_globalLock protects all of the global variables defined in this module,
42 * the reference counts and hash pointers in the actual cm_buf_t structures,
43 * and the LRU queue pointers in the buffer structures.
45 * The mutexes in the buffer structures protect the remaining fields in the
46 * buffers, as well the data itself.
48 * The locking hierarchy here is this:
50 * - resv multiple simul. buffers reservation
51 * - lock buffer I/O flags
52 * - lock buffer's mutex
53 * - lock buf_globalLock
57 /* global debugging log */
58 osi_log_t *buf_logp = NULL;
60 /* Global lock protecting hash tables and free lists */
61 osi_rwlock_t buf_globalLock;
63 /* ptr to head of the free list (most recently used) and the
64 * tail (the guy to remove first). We use osi_Q* functions
65 * to put stuff in buf_freeListp, and maintain the end
69 /* a pointer to a list of all buffers, just so that we can find them
70 * easily for debugging, and for the incr syncer. Locked under
74 /* defaults setup; these variables may be manually assigned into
75 * before calling cm_Init, as a way of changing these defaults.
78 /* callouts for reading and writing data, etc */
79 cm_buf_ops_t *cm_buf_opsp;
82 /* for experimental disk caching support in Win95 client */
83 cm_buf_t *buf_diskFreeListp;
84 cm_buf_t *buf_diskFreeListEndp;
85 cm_buf_t *buf_diskAllp;
86 extern int cm_diskCacheEnabled;
87 #endif /* DISKCACHE95 */
89 /* set this to 1 when we are terminating to prevent access attempts */
90 static int buf_ShutdownFlag = 0;
92 /* hold a reference to an already held buffer */
93 void buf_Hold(cm_buf_t *bp)
95 osi_assert(bp->magic == CM_BUF_MAGIC);
96 lock_ObtainWrite(&buf_globalLock);
98 lock_ReleaseWrite(&buf_globalLock);
101 /* incremental sync daemon. Writes 1/10th of all the buffers every 5000 ms */
102 void buf_IncrSyncer(long parm)
104 cm_buf_t *bp; /* buffer we're hacking on; held */
105 long i; /* counter */
106 long nAtOnce; /* how many to do at once */
109 lock_ObtainWrite(&buf_globalLock);
110 bp = cm_data.buf_allp;
112 lock_ReleaseWrite(&buf_globalLock);
113 nAtOnce = (long)sqrt(cm_data.buf_nbuffers);
114 while (buf_ShutdownFlag == 0) {
116 i = SleepEx(5000, 1);
117 if (i != 0) continue;
122 if (buf_ShutdownFlag == 1)
125 /* now go through our percentage of the buffers */
126 for (i=0; i<nAtOnce; i++) {
127 /* don't want its identity changing while we're
128 * messing with it, so must do all of this with
132 /* start cleaning the buffer; don't touch log pages since
133 * the log code counts on knowing exactly who is writing
134 * a log page at any given instant.
137 req.flags |= CM_REQ_NORETRY;
138 buf_CleanAsync(bp, &req);
140 /* now advance to the next buffer; the allp chain never changes,
141 * and so can be followed even when holding no locks.
143 lock_ObtainWrite(&buf_globalLock);
144 buf_LockedRelease(bp);
147 bp = cm_data.buf_allp;
149 lock_ReleaseWrite(&buf_globalLock);
150 } /* for loop over a bunch of buffers */
151 } /* whole daemon's while loop */
155 buf_ValidateBuffers(void)
157 cm_buf_t * bp, *bpf, *bpa, *bpb;
158 afs_uint32 countb = 0, countf = 0, counta = 0;
160 if (cm_data.buf_freeListp == NULL && cm_data.buf_freeListEndp != NULL ||
161 cm_data.buf_freeListp != NULL && cm_data.buf_freeListEndp == NULL) {
162 afsi_log("cm_ValidateBuffers failure: inconsistent free list pointers");
163 fprintf(stderr, "cm_ValidateBuffers failure: inconsistent free list pointers\n");
167 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
168 if (bp->magic != CM_BUF_MAGIC) {
169 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
170 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
176 if (countb > cm_data.buf_nbuffers) {
177 afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
178 fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
183 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
184 if (bp->magic != CM_BUF_MAGIC) {
185 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
186 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
192 if (countf > cm_data.buf_nbuffers) {
193 afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
194 fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
199 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
200 if (bp->magic != CM_BUF_MAGIC) {
201 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
202 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
208 if (counta > cm_data.buf_nbuffers) {
209 afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
210 fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
215 if (countb != countf) {
216 afsi_log("cm_ValidateBuffers failure: countb != countf");
217 fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
221 if (counta != cm_data.buf_nbuffers) {
222 afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
223 fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
230 void buf_Shutdown(void)
232 buf_ShutdownFlag = 1;
235 /* initialize the buffer package; called with no locks
236 * held during the initialization phase.
238 long buf_Init(int newFile, cm_buf_ops_t *opsp, long nbuffers)
240 static osi_once_t once;
249 cm_data.buf_nbuffers = nbuffers;
251 /* Have to be able to reserve a whole chunk */
252 if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
253 return CM_ERROR_TOOFEWBUFS;
256 /* recall for callouts */
259 if (osi_Once(&once)) {
260 /* initialize global locks */
261 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock");
264 /* remember this for those who want to reset it */
265 cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
267 /* lower hash size to a prime number */
268 cm_data.buf_hashSize = osi_PrimeLessThan(CM_BUF_HASHSIZE);
270 /* create hash table */
271 memset((void *)cm_data.buf_hashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
273 /* another hash table */
274 memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
276 /* create buffer headers and put in free list */
277 bp = cm_data.bufHeaderBaseAddress;
278 data = cm_data.bufDataBaseAddress;
279 cm_data.buf_allp = NULL;
281 for (i=0; i<cm_data.buf_nbuffers; i++) {
282 osi_assert(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress);
283 osi_assert(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData);
285 /* allocate and zero some storage */
286 memset(bp, 0, sizeof(cm_buf_t));
287 bp->magic = CM_BUF_MAGIC;
288 /* thread on list of all buffers */
289 bp->allp = cm_data.buf_allp;
290 cm_data.buf_allp = bp;
292 osi_QAdd((osi_queue_t **)&cm_data.buf_freeListp, &bp->q);
293 bp->flags |= CM_BUF_INLRU;
294 lock_InitializeMutex(&bp->mx, "Buffer mutex");
296 /* grab appropriate number of bytes from aligned zone */
299 /* setup last buffer pointer */
301 cm_data.buf_freeListEndp = bp;
305 data += cm_data.buf_blockSize;
308 /* none reserved at first */
309 cm_data.buf_reservedBufs = 0;
311 /* just for safety's sake */
312 cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
314 bp = cm_data.bufHeaderBaseAddress;
315 data = cm_data.bufDataBaseAddress;
317 for (i=0; i<cm_data.buf_nbuffers; i++) {
318 lock_InitializeMutex(&bp->mx, "Buffer mutex");
321 bp->waitRequests = 0;
322 bp->flags &= ~CM_BUF_WAITING;
328 buf_ValidateBufQueues();
332 /* init the buffer trace log */
333 buf_logp = osi_LogCreate("buffer", 1000);
334 osi_LogEnable(buf_logp);
339 /* and create the incr-syncer */
340 phandle = thrd_Create(0, 0,
341 (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
344 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
346 CloseHandle(phandle);
351 buf_ValidateBufQueues();
356 /* add nbuffers to the buffer pool, if possible.
357 * Called with no locks held.
359 long buf_AddBuffers(long nbuffers)
362 /* The size of a virtual cache cannot be changed after it has
363 * been created. Subsequent calls to MapViewofFile() with
364 * an existing mapping object name would not allow the
365 * object to be resized. Return failure immediately.
367 * A similar problem now occurs with the persistent cache
368 * given that the memory mapped file now contains a complex
371 afsi_log("request to add %d buffers to the existing cache of size %d denied",
372 nbuffers, cm_data.buf_nbuffers);
374 return CM_ERROR_INVAL;
380 data = malloc(buf_nbuffers * cm_data.buf_blockSize);
382 /* Create buffer headers and put in free list */
383 bp = malloc(nbuffers * sizeof(*bp));
385 for (i=0; i<nbuffers; i++) {
386 memset(bp, 0, sizeof(*bp));
388 lock_InitializeMutex(&bp->mx, "cm_buf_t");
390 /* grab appropriate number of bytes from aligned zone */
393 bp->flags |= CM_BUF_INLRU;
395 lock_ObtainWrite(&buf_globalLock);
396 /* note that buf_allp chain is covered by buf_globalLock now */
397 bp->allp = cm_data.buf_allp;
398 cm_data.buf_allp = bp;
399 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
400 if (!cm_data.buf_freeListEndp)
401 cm_data.buf_freeListEndp = bp;
402 cm_data.buf_nbuffers++;
403 lock_ReleaseWrite(&buf_globalLock);
406 data += cm_data.buf_blockSize;
408 } /* for loop over all buffers */
414 /* interface to set the number of buffers to an exact figure.
415 * Called with no locks held.
417 long buf_SetNBuffers(long nbuffers)
420 return CM_ERROR_INVAL;
421 if (nbuffers == cm_data.buf_nbuffers)
423 else if (nbuffers > cm_data.buf_nbuffers)
424 return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
426 return CM_ERROR_INVAL;
429 /* release a buffer. Buffer must be referenced, but unlocked. */
430 void buf_Release(cm_buf_t *bp)
432 lock_ObtainWrite(&buf_globalLock);
433 buf_LockedRelease(bp);
434 lock_ReleaseWrite(&buf_globalLock);
437 /* wait for reading or writing to clear; called with write-locked
438 * buffer and unlocked scp and returns with locked buffer.
440 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
443 osi_assert(scp->magic == CM_SCACHE_MAGIC);
444 osi_assert(bp->magic == CM_BUF_MAGIC);
447 /* if no IO is happening, we're done */
448 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
451 /* otherwise I/O is happening, but some other thread is waiting for
452 * the I/O already. Wait for that guy to figure out what happened,
453 * and then check again.
455 if ( bp->flags & CM_BUF_WAITING ) {
458 osi_Log1(afsd_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%x", bp);
460 osi_Log1(afsd_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%x", bp);
461 bp->flags |= CM_BUF_WAITING;
462 bp->waitCount = bp->waitRequests = 1;
464 osi_SleepM((long) bp, &bp->mx);
465 lock_ObtainMutex(&bp->mx);
466 osi_Log1(afsd_logp, "buf_WaitIO conflict wait done for 0x%x", bp);
468 if (bp->waitCount == 0) {
469 osi_Log1(afsd_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%x", bp);
470 bp->flags &= ~CM_BUF_WAITING;
471 bp->waitRequests = 0;
475 scp = cm_FindSCache(&bp->fid);
478 lock_ObtainMutex(&scp->mx);
479 if (scp->flags & CM_SCACHEFLAG_WAITING) {
480 osi_Log1(afsd_logp, "buf_WaitIO waking scp 0x%x", scp);
481 osi_Wakeup((long)&scp->flags);
483 lock_ReleaseMutex(&scp->mx);
487 /* if we get here, the IO is done, but we may have to wakeup people waiting for
488 * the I/O to complete. Do so.
490 if (bp->flags & CM_BUF_WAITING) {
491 osi_Log1(afsd_logp, "buf_WaitIO Waking bp 0x%x", bp);
492 osi_Wakeup((long) bp);
494 osi_Log1(afsd_logp, "WaitIO finished wait for bp 0x%x", (long) bp);
497 /* code to drop reference count while holding buf_globalLock */
498 void buf_LockedRelease(cm_buf_t *bp)
500 /* ensure that we're in the LRU queue if our ref count is 0 */
501 osi_assert(bp->refCount > 0);
502 if (--bp->refCount == 0) {
503 if (!(bp->flags & CM_BUF_INLRU)) {
504 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
506 /* watch for transition from empty to one element */
507 if (!cm_data.buf_freeListEndp)
508 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
509 bp->flags |= CM_BUF_INLRU;
514 /* find a buffer, if any, for a particular file ID and offset. Assumes
515 * that buf_globalLock is write locked when called.
517 cm_buf_t *buf_LockedFind(struct cm_scache *scp, osi_hyper_t *offsetp)
522 i = BUF_HASH(&scp->fid, offsetp);
523 for(bp = cm_data.buf_hashTablepp[i]; bp; bp=bp->hashp) {
524 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
525 && offsetp->LowPart == bp->offset.LowPart
526 && offsetp->HighPart == bp->offset.HighPart) {
532 /* return whatever we found, if anything */
536 /* find a buffer with offset *offsetp for vnode *scp. Called
537 * with no locks held.
539 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
543 lock_ObtainWrite(&buf_globalLock);
544 bp = buf_LockedFind(scp, offsetp);
545 lock_ReleaseWrite(&buf_globalLock);
550 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
553 * Makes sure that there's only one person writing this block
554 * at any given time, and also ensures that the log is forced sufficiently far,
555 * if this buffer contains logged data.
557 void buf_LockedCleanAsync(cm_buf_t *bp, cm_req_t *reqp)
561 osi_assert(bp->magic == CM_BUF_MAGIC);
563 while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
564 lock_ReleaseMutex(&bp->mx);
566 osi_Log1(afsd_logp, "buf_LockedCleanAsync starts I/O on 0x%x", bp);
567 code = (*cm_buf_opsp->Writep)(&bp->fid, &bp->offset,
568 cm_data.buf_blockSize, 0, bp->userp,
570 osi_Log2(afsd_logp, "buf_LockedCleanAsync I/O on 0x%x, done=%d", bp, code);
572 lock_ObtainMutex(&bp->mx);
577 /* Disk cache support */
578 /* write buffer to disk cache (synchronous for now) */
579 diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
580 #endif /* DISKCACHE95 */
583 /* do logging after call to GetLastError, or else */
585 /* if someone was waiting for the I/O that just completed or failed,
588 if (bp->flags & CM_BUF_WAITING) {
589 /* turn off flags and wakeup users */
590 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%x", bp);
591 osi_Wakeup((long) bp);
595 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
596 * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
597 * The buffer must already be clean, and no I/O should be happening to it.
599 void buf_Recycle(cm_buf_t *bp)
604 cm_buf_t *prevBp, *nextBp;
606 osi_assert(bp->magic == CM_BUF_MAGIC);
608 /* if we get here, we know that the buffer still has a 0 ref count,
609 * and that it is clean and has no currently pending I/O. This is
610 * the dude to return.
611 * Remember that as long as the ref count is 0, we know that we won't
612 * have any lock conflicts, so we can grab the buffer lock out of
613 * order in the locking hierarchy.
615 osi_Log2( buf_logp, "buf_Recycle recycles 0x%x, off 0x%x",
616 bp, bp->offset.LowPart);
618 osi_assert(bp->refCount == 0);
619 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)));
620 lock_AssertWrite(&buf_globalLock);
622 if (bp->flags & CM_BUF_INHASH) {
623 /* Remove from hash */
625 i = BUF_HASH(&bp->fid, &bp->offset);
626 lbpp = &(cm_data.buf_hashTablepp[i]);
627 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
628 if (tbp == bp) break;
631 /* we better find it */
632 osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
634 *lbpp = bp->hashp; /* hash out */
636 /* Remove from file hash */
638 i = BUF_FILEHASH(&bp->fid);
639 prevBp = bp->fileHashBackp;
640 nextBp = bp->fileHashp;
642 prevBp->fileHashp = nextBp;
644 cm_data.buf_fileHashTablepp[i] = nextBp;
646 nextBp->fileHashBackp = prevBp;
648 bp->flags &= ~CM_BUF_INHASH;
651 /* bump the soft reference counter now, to invalidate softRefs; no
652 * wakeup is required since people don't sleep waiting for this
657 /* make the fid unrecognizable */
658 memset(&bp->fid, 0, sizeof(cm_fid_t));
661 /* recycle a buffer, removing it from the free list, hashing in its new identity
662 * and returning it write-locked so that no one can use it. Called without
663 * any locks held, and can return an error if it loses the race condition and
664 * finds that someone else created the desired buffer.
666 * If success is returned, the buffer is returned write-locked.
668 * May be called with null scp and offsetp, if we're just trying to reclaim some
669 * space from the buffer pool. In that case, the buffer will be returned
670 * without being hashed into the hash table.
672 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
674 cm_buf_t *bp; /* buffer we're dealing with */
675 cm_buf_t *nextBp; /* next buffer in file hash chain */
679 cm_InitReq(&req); /* just in case */
682 buf_ValidateBufQueues();
687 lock_ObtainWrite(&buf_globalLock);
688 /* check to see if we lost the race */
690 if (bp = buf_LockedFind(scp, offsetp)) {
692 lock_ReleaseWrite(&buf_globalLock);
693 return CM_BUF_EXISTS;
697 /* does this fix the problem below? it's a simple solution. */
698 if (!cm_data.buf_freeListEndp)
700 lock_ReleaseWrite(&buf_globalLock);
705 /* for debugging, assert free list isn't empty, although we
706 * really should try waiting for a running tranasction to finish
707 * instead of this; or better, we should have a transaction
708 * throttler prevent us from entering this situation.
710 osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
712 /* look at all buffers in free list, some of which may temp.
713 * have high refcounts and which then should be skipped,
714 * starting cleaning I/O for those which are dirty. If we find
715 * a clean buffer, we rehash it, lock it and return it.
717 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
718 /* check to see if it really has zero ref count. This
719 * code can bump refcounts, at least, so it may not be
722 if (bp->refCount > 0)
725 /* we don't have to lock buffer itself, since the ref
726 * count is 0 and we know it will stay zero as long as
727 * we hold the global lock.
730 /* don't recycle someone in our own chunk */
731 if (!cm_FidCmp(&bp->fid, &scp->fid)
732 && (bp->offset.LowPart & (-cm_chunkSize))
733 == (offsetp->LowPart & (-cm_chunkSize)))
736 /* if this page is being filled (!) or cleaned, see if
737 * the I/O has completed. If not, skip it, otherwise
738 * do the final processing for the I/O.
740 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
741 /* probably shouldn't do this much work while
742 * holding the big lock? Watch for contention
748 if (bp->flags & CM_BUF_DIRTY) {
749 /* if the buffer is dirty, start cleaning it and
750 * move on to the next buffer. We do this with
751 * just the lock required to minimize contention
755 lock_ReleaseWrite(&buf_globalLock);
757 /* grab required lock and clean; this only
758 * starts the I/O. By the time we're back,
759 * it'll still be marked dirty, but it will also
760 * have the WRITING flag set, so we won't get
763 buf_CleanAsync(bp, &req);
765 /* now put it back and go around again */
770 /* if we get here, we know that the buffer still has a 0
771 * ref count, and that it is clean and has no currently
772 * pending I/O. This is the dude to return.
773 * Remember that as long as the ref count is 0, we know
774 * that we won't have any lock conflicts, so we can grab
775 * the buffer lock out of order in the locking hierarchy.
779 /* clean up junk flags */
780 bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
781 bp->dataVersion = -1; /* unknown so far */
783 /* now hash in as our new buffer, and give it the
784 * appropriate label, if requested.
787 bp->flags |= CM_BUF_INHASH;
789 bp->offset = *offsetp;
790 i = BUF_HASH(&scp->fid, offsetp);
791 bp->hashp = cm_data.buf_hashTablepp[i];
792 cm_data.buf_hashTablepp[i] = bp;
793 i = BUF_FILEHASH(&scp->fid);
794 nextBp = cm_data.buf_fileHashTablepp[i];
795 bp->fileHashp = nextBp;
796 bp->fileHashBackp = NULL;
798 nextBp->fileHashBackp = bp;
799 cm_data.buf_fileHashTablepp[i] = bp;
802 /* prepare to return it. Start by giving it a good
806 /* and since it has a non-zero ref count, we should move
807 * it from the lru queue. It better be still there,
808 * since we've held the global (big) lock since we found
811 osi_assertx(bp->flags & CM_BUF_INLRU,
812 "buf_GetNewLocked: LRU screwup");
813 if (cm_data.buf_freeListEndp == bp) {
814 /* we're the last guy in this queue, so maintain it */
815 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
817 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
818 bp->flags &= ~CM_BUF_INLRU;
820 /* finally, grab the mutex so that people don't use it
821 * before the caller fills it with data. Again, no one
822 * should have been able to get to this dude to lock it.
824 osi_assertx(lock_TryMutex(&bp->mx),
825 "buf_GetNewLocked: TryMutex failed");
827 lock_ReleaseWrite(&buf_globalLock);
831 buf_ValidateBufQueues();
834 } /* for all buffers in lru queue */
835 lock_ReleaseWrite(&buf_globalLock);
836 } /* while loop over everything */
840 /* get a page, returning it held but unlocked. Doesn't fill in the page
841 * with I/O, since we're going to write the whole thing new.
843 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
847 osi_hyper_t pageOffset;
851 pageOffset.HighPart = offsetp->HighPart;
852 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
854 bp = buf_Find(scp, &pageOffset);
856 /* lock it and break out */
857 lock_ObtainMutex(&bp->mx);
861 /* otherwise, we have to create a page */
862 code = buf_GetNewLocked(scp, &pageOffset, &bp);
864 /* check if the buffer was created in a race condition branch.
865 * If so, go around so we can hold a reference to it.
867 if (code == CM_BUF_EXISTS)
870 /* something else went wrong */
874 /* otherwise, we have a locked buffer that we just created */
877 } /* big while loop */
880 if (bp->flags & CM_BUF_READING)
883 /* once it has been read once, we can unlock it and return it, still
884 * with its refcount held.
886 lock_ReleaseMutex(&bp->mx);
888 osi_Log3(buf_logp, "buf_GetNew returning bp 0x%x for file 0x%x, offset 0x%x",
889 bp, (long) scp, offsetp->LowPart);
893 /* get a page, returning it held but unlocked. Make sure it is complete */
894 /* The scp must be unlocked when passed to this function */
895 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
899 osi_hyper_t pageOffset;
900 unsigned long tcount;
905 #endif /* DISKCACHE95 */
908 pageOffset.HighPart = offsetp->HighPart;
909 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
913 buf_ValidateBufQueues();
916 bp = buf_Find(scp, &pageOffset);
918 /* lock it and break out */
919 lock_ObtainMutex(&bp->mx);
923 /* touch disk chunk to update LRU info */
924 diskcache_Touch(bp->dcp);
925 #endif /* DISKCACHE95 */
928 /* otherwise, we have to create a page */
929 code = buf_GetNewLocked(scp, &pageOffset, &bp);
931 /* check if the buffer was created in a race condition branch.
932 * If so, go around so we can hold a reference to it.
934 if (code == CM_BUF_EXISTS)
937 /* something else went wrong */
940 buf_ValidateBufQueues();
945 /* otherwise, we have a locked buffer that we just created */
948 } /* big while loop */
950 /* if we get here, we have a locked buffer that may have just been
951 * created, in which case it needs to be filled with data.
954 /* load the page; freshly created pages should be idle */
955 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
957 /* setup offset, event */
958 #ifndef DJGPP /* doesn't seem to be used */
959 bp->over.Offset = bp->offset.LowPart;
960 bp->over.OffsetHigh = bp->offset.HighPart;
963 /* start the I/O; may drop lock */
964 bp->flags |= CM_BUF_READING;
965 code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
968 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
969 bp->dcp = dcp; /* pointer to disk cache struct. */
970 #endif /* DISKCACHE95 */
973 /* failure or queued */
974 #ifndef DJGPP /* cm_bufRead always returns 0 */
975 if (code != ERROR_IO_PENDING) {
978 bp->flags |= CM_BUF_ERROR;
979 bp->flags &= ~CM_BUF_READING;
980 if (bp->flags & CM_BUF_WAITING) {
981 osi_Log1(buf_logp, "buf_Get Waking bp 0x%x", bp);
982 osi_Wakeup((long) bp);
984 lock_ReleaseMutex(&bp->mx);
987 buf_ValidateBufQueues();
994 /* otherwise, I/O completed instantly and we're done, except
995 * for padding the xfr out with 0s and checking for EOF
997 if (tcount < (unsigned long) cm_data.buf_blockSize) {
998 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
1000 bp->flags |= CM_BUF_EOF;
1002 bp->flags &= ~CM_BUF_READING;
1003 if (bp->flags & CM_BUF_WAITING) {
1004 osi_Log1(buf_logp, "buf_Get Waking bp 0x%x", bp);
1005 osi_Wakeup((long) bp);
1011 /* wait for reads, either that which we started above, or that someone
1012 * else started. We don't care if we return a buffer being cleaned.
1014 if (bp->flags & CM_BUF_READING)
1015 buf_WaitIO(scp, bp);
1017 /* once it has been read once, we can unlock it and return it, still
1018 * with its refcount held.
1020 lock_ReleaseMutex(&bp->mx);
1023 /* now remove from queue; will be put in at the head (farthest from
1024 * being recycled) when we're done in buf_Release.
1026 lock_ObtainWrite(&buf_globalLock);
1027 if (bp->flags & CM_BUF_INLRU) {
1028 if (cm_data.buf_freeListEndp == bp)
1029 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1030 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
1031 bp->flags &= ~CM_BUF_INLRU;
1033 lock_ReleaseWrite(&buf_globalLock);
1035 osi_Log3(buf_logp, "buf_Get returning bp 0x%x for file 0x%x, offset 0x%x",
1036 bp, (long) scp, offsetp->LowPart);
1038 buf_ValidateBufQueues();
1039 #endif /* TESTING */
1043 /* count # of elements in the free list;
1044 * we don't bother doing the proper locking for accessing dataVersion or flags
1045 * since it is a pain, and this is really just an advisory call. If you need
1046 * to do better at some point, rewrite this function.
1048 long buf_CountFreeList(void)
1054 lock_ObtainRead(&buf_globalLock);
1055 for(bufp = cm_data.buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1056 /* if the buffer doesn't have an identity, or if the buffer
1057 * has been invalidate (by having its DV stomped upon), then
1058 * count it as free, since it isn't really being utilized.
1060 if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1063 lock_ReleaseRead(&buf_globalLock);
1067 /* clean a buffer synchronously */
1068 void buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1070 osi_assert(bp->magic == CM_BUF_MAGIC);
1072 lock_ObtainMutex(&bp->mx);
1073 buf_LockedCleanAsync(bp, reqp);
1074 lock_ReleaseMutex(&bp->mx);
1077 /* wait for a buffer's cleaning to finish */
1078 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp)
1080 osi_assert(bp->magic == CM_BUF_MAGIC);
1082 lock_ObtainMutex(&bp->mx);
1083 if (bp->flags & CM_BUF_WRITING) {
1084 buf_WaitIO(scp, bp);
1086 lock_ReleaseMutex(&bp->mx);
1089 /* set the dirty flag on a buffer, and set associated write-ahead log,
1090 * if there is one. Allow one to be added to a buffer, but not changed.
1092 * The buffer must be locked before calling this routine.
1094 void buf_SetDirty(cm_buf_t *bp)
1096 osi_assert(bp->magic == CM_BUF_MAGIC);
1097 osi_assert(bp->refCount > 0);
1099 osi_Log1(buf_logp, "buf_SetDirty 0x%x", bp);
1102 bp->flags |= CM_BUF_DIRTY;
1104 /* and turn off EOF flag, since it has associated data now */
1105 bp->flags &= ~CM_BUF_EOF;
1108 /* clean all buffers, reset log pointers and invalidate all buffers.
1109 * Called with no locks held, and returns with same.
1111 * This function is guaranteed to clean and remove the log ptr of all the
1112 * buffers that were dirty or had non-zero log ptrs before the call was
1113 * made. That's sufficient to clean up any garbage left around by recovery,
1114 * which is all we're counting on this for; there may be newly created buffers
1115 * added while we're running, but that should be OK.
1117 * In an environment where there are no transactions (artificially imposed, for
1118 * example, when switching the database to raw mode), this function is used to
1119 * make sure that all updates have been written to the disk. In that case, we don't
1120 * really require that we forget the log association between pages and logs, but
1121 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1122 * have to worry about invalidating data in the buffers.
1124 * This function is used at the end of recovery as paranoia to get the recovered
1125 * database out to disk. It removes all references to the recovery log and cleans
1128 long buf_CleanAndReset(void)
1134 lock_ObtainWrite(&buf_globalLock);
1135 for(i=0; i<cm_data.buf_hashSize; i++) {
1136 for(bp = cm_data.buf_hashTablepp[i]; bp; bp = bp->hashp) {
1137 if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1139 lock_ReleaseWrite(&buf_globalLock);
1141 /* now no locks are held; clean buffer and go on */
1143 buf_CleanAsync(bp, &req);
1144 buf_CleanWait(NULL, bp);
1146 /* relock and release buffer */
1147 lock_ObtainWrite(&buf_globalLock);
1148 buf_LockedRelease(bp);
1150 } /* over one bucket */
1151 } /* for loop over all hash buckets */
1154 lock_ReleaseWrite(&buf_globalLock);
1157 buf_ValidateBufQueues();
1158 #endif /* TESTING */
1160 /* and we're done */
1164 /* called without global lock being held, reserves buffers for callers
1165 * that need more than one held (not locked) at once.
1167 void buf_ReserveBuffers(long nbuffers)
1169 lock_ObtainWrite(&buf_globalLock);
1171 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1172 cm_data.buf_reserveWaiting = 1;
1173 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1174 osi_SleepW((long) &cm_data.buf_reservedBufs, &buf_globalLock);
1175 lock_ObtainWrite(&buf_globalLock);
1178 cm_data.buf_reservedBufs += nbuffers;
1182 lock_ReleaseWrite(&buf_globalLock);
1185 int buf_TryReserveBuffers(long nbuffers)
1189 lock_ObtainWrite(&buf_globalLock);
1190 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1194 cm_data.buf_reservedBufs += nbuffers;
1197 lock_ReleaseWrite(&buf_globalLock);
1201 /* called without global lock held, releases reservation held by
1202 * buf_ReserveBuffers.
1204 void buf_UnreserveBuffers(long nbuffers)
1206 lock_ObtainWrite(&buf_globalLock);
1207 cm_data.buf_reservedBufs -= nbuffers;
1208 if (cm_data.buf_reserveWaiting) {
1209 cm_data.buf_reserveWaiting = 0;
1210 osi_Wakeup((long) &cm_data.buf_reservedBufs);
1212 lock_ReleaseWrite(&buf_globalLock);
1215 /* truncate the buffers past sizep, zeroing out the page, if we don't
1216 * end on a page boundary.
1218 * Requires cm_bufCreateLock to be write locked.
1220 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1224 cm_buf_t *nbufp; /* next buffer, if didRelease */
1231 /* assert that cm_bufCreateLock is held in write mode */
1232 lock_AssertWrite(&scp->bufCreateLock);
1234 i = BUF_FILEHASH(&scp->fid);
1236 lock_ObtainWrite(&buf_globalLock);
1237 bufp = cm_data.buf_fileHashTablepp[i];
1239 lock_ReleaseWrite(&buf_globalLock);
1244 lock_ReleaseWrite(&buf_globalLock);
1245 for(; bufp; bufp = nbufp) {
1247 lock_ObtainMutex(&bufp->mx);
1249 bufEnd.HighPart = 0;
1250 bufEnd.LowPart = cm_data.buf_blockSize;
1251 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1253 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1254 LargeIntegerLessThan(*sizep, bufEnd)) {
1255 buf_WaitIO(scp, bufp);
1257 lock_ObtainMutex(&scp->mx);
1259 /* make sure we have a callback (so we have the right value for
1260 * the length), and wait for it to be safe to do a truncate.
1262 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1263 CM_SCACHESYNC_NEEDCALLBACK
1264 | CM_SCACHESYNC_GETSTATUS
1265 | CM_SCACHESYNC_SETSIZE
1266 | CM_SCACHESYNC_BUFLOCKED);
1267 /* if we succeeded in our locking, and this applies to the right
1268 * file, and the truncate request overlaps the buffer either
1269 * totally or partially, then do something.
1271 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1272 && LargeIntegerLessThan(*sizep, bufEnd)) {
1274 lock_ObtainWrite(&buf_globalLock);
1276 /* destroy the buffer, turning off its dirty bit, if
1277 * we're truncating the whole buffer. Otherwise, set
1278 * the dirty bit, and clear out the tail of the buffer
1279 * if we just overlap some.
1281 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1282 /* truncating the entire page */
1283 bufp->flags &= ~CM_BUF_DIRTY;
1284 bufp->dataVersion = -1; /* known bad */
1285 bufp->dirtyCounter++;
1288 /* don't set dirty, since dirty implies
1289 * currently up-to-date. Don't need to do this,
1290 * since we'll update the length anyway.
1292 * Zero out remainder of the page, in case we
1293 * seek and write past EOF, and make this data
1296 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1297 osi_assert(bufferPos != 0);
1298 memset(bufp->datap + bufferPos, 0,
1299 cm_data.buf_blockSize - bufferPos);
1302 lock_ReleaseWrite(&buf_globalLock);
1305 lock_ReleaseMutex(&scp->mx);
1306 lock_ReleaseMutex(&bufp->mx);
1308 lock_ObtainWrite(&buf_globalLock);
1309 nbufp = bufp->fileHashp;
1310 if (nbufp) nbufp->refCount++;
1311 buf_LockedRelease(bufp);
1312 lock_ReleaseWrite(&buf_globalLock);
1315 /* bail out early if we fail */
1317 /* at this point, nbufp is held; bufp has already been
1324 buf_ValidateBufQueues();
1325 #endif /* TESTING */
1332 buf_ValidateBufQueues();
1333 #endif /* TESTING */
1339 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1342 cm_buf_t *bp; /* buffer we're hacking on */
1347 i = BUF_FILEHASH(&scp->fid);
1350 lock_ObtainWrite(&buf_globalLock);
1351 bp = cm_data.buf_fileHashTablepp[i];
1354 lock_ReleaseWrite(&buf_globalLock);
1355 for (; bp; bp = nbp) {
1356 didRelease = 0; /* haven't released this buffer yet */
1358 /* clean buffer synchronously */
1359 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1360 lock_ObtainMutex(&bp->mx);
1362 /* start cleaning the buffer, and wait for it to finish */
1363 buf_LockedCleanAsync(bp, reqp);
1364 buf_WaitIO(scp, bp);
1365 lock_ReleaseMutex(&bp->mx);
1367 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1371 lock_ObtainWrite(&buf_globalLock);
1372 /* actually, we only know that buffer is clean if ref
1373 * count is 1, since we don't have buffer itself locked.
1375 if (!(bp->flags & CM_BUF_DIRTY)) {
1376 if (bp->refCount == 1) { /* bp is held above */
1377 buf_LockedRelease(bp);
1378 nbp = bp->fileHashp;
1385 lock_ReleaseWrite(&buf_globalLock);
1387 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1392 lock_ObtainWrite(&buf_globalLock);
1393 if (nbp = bp->fileHashp)
1395 buf_LockedRelease(bp);
1396 lock_ReleaseWrite(&buf_globalLock);
1398 } /* for loop over a bunch of buffers */
1401 buf_ValidateBufQueues();
1402 #endif /* TESTING */
1408 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1411 cm_buf_t *bp; /* buffer we're hacking on */
1412 cm_buf_t *nbp; /* next one */
1415 i = BUF_FILEHASH(&scp->fid);
1418 lock_ObtainWrite(&buf_globalLock);
1419 bp = cm_data.buf_fileHashTablepp[i];
1422 lock_ReleaseWrite(&buf_globalLock);
1423 for (; bp; bp = nbp) {
1424 /* clean buffer synchronously */
1425 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1428 lock_ObtainMutex(&bp->mx);
1430 cm_ReleaseUser(bp->userp);
1432 lock_ReleaseMutex(&bp->mx);
1434 buf_CleanAsync(bp, reqp);
1435 buf_CleanWait(scp, bp);
1436 lock_ObtainMutex(&bp->mx);
1437 if (bp->flags & CM_BUF_ERROR) {
1438 if (code == 0 || code == -1)
1443 lock_ReleaseMutex(&bp->mx);
1446 lock_ObtainWrite(&buf_globalLock);
1447 buf_LockedRelease(bp);
1448 nbp = bp->fileHashp;
1451 lock_ReleaseWrite(&buf_globalLock);
1452 } /* for loop over a bunch of buffers */
1455 buf_ValidateBufQueues();
1456 #endif /* TESTING */
1464 buf_ValidateBufQueues(void)
1466 cm_buf_t * bp, *bpb, *bpf, *bpa;
1467 afs_uint32 countf=0, countb=0, counta=0;
1469 lock_ObtainRead(&buf_globalLock);
1470 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1471 if (bp->magic != CM_BUF_MAGIC)
1477 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
1478 if (bp->magic != CM_BUF_MAGIC)
1484 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
1485 if (bp->magic != CM_BUF_MAGIC)
1490 lock_ReleaseRead(&buf_globalLock);
1492 if (countb != countf)
1495 if (counta != cm_data.buf_nbuffers)
1498 #endif /* TESTING */
1500 /* dump the contents of the buf_hashTablepp. */
1501 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
1508 if (cm_data.buf_hashTablepp == NULL)
1512 lock_ObtainRead(&buf_globalLock);
1514 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\n",
1515 cookie, cm_data.buf_hashSize);
1516 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1518 for (i = 0; i < cm_data.buf_hashSize; i++)
1520 for (bp = cm_data.buf_hashTablepp[i]; bp; bp=bp->hashp)
1524 StringCbPrintfA(output, sizeof(output), "vnode=%d, unique=%d), size=%d refCount=%d\n",
1525 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
1526 bp->fid.vnode, bp->fid.unique, bp->size, bp->refCount);
1527 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1532 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\n", cookie);
1533 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1536 lock_ReleaseRead(&buf_globalLock);
1540 void buf_ForceTrace(BOOL flush)
1549 len = GetTempPath(sizeof(buf)-10, buf);
1550 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
1551 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
1552 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1553 if (handle == INVALID_HANDLE_VALUE) {
1554 osi_panic("Cannot create log file", __FILE__, __LINE__);
1556 osi_LogPrint(buf_logp, handle);
1558 FlushFileBuffers(handle);
1559 CloseHandle(handle);