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;
90 /* hold a reference to an already held buffer */
91 void buf_Hold(cm_buf_t *bp)
93 osi_assert(bp->magic == CM_BUF_MAGIC);
94 lock_ObtainWrite(&buf_globalLock);
96 lock_ReleaseWrite(&buf_globalLock);
99 /* incremental sync daemon. Writes 1/10th of all the buffers every 5000 ms */
100 void buf_IncrSyncer(long parm)
102 cm_buf_t *bp; /* buffer we're hacking on; held */
103 long i; /* counter */
104 long nAtOnce; /* how many to do at once */
107 lock_ObtainWrite(&buf_globalLock);
108 bp = cm_data.buf_allp;
110 lock_ReleaseWrite(&buf_globalLock);
111 nAtOnce = (long)sqrt((double)cm_data.buf_nbuffers);
112 while (buf_ShutdownFlag == 0) {
113 i = SleepEx(5000, 1);
114 if (i != 0) continue;
116 if (buf_ShutdownFlag == 1)
119 /* now go through our percentage of the buffers */
120 for (i=0; i<nAtOnce; i++) {
121 /* don't want its identity changing while we're
122 * messing with it, so must do all of this with
126 /* start cleaning the buffer; don't touch log pages since
127 * the log code counts on knowing exactly who is writing
128 * a log page at any given instant.
131 req.flags |= CM_REQ_NORETRY;
132 buf_CleanAsync(bp, &req);
134 /* now advance to the next buffer; the allp chain never changes,
135 * and so can be followed even when holding no locks.
137 lock_ObtainWrite(&buf_globalLock);
138 buf_LockedRelease(bp);
141 bp = cm_data.buf_allp;
143 lock_ReleaseWrite(&buf_globalLock);
144 } /* for loop over a bunch of buffers */
145 } /* whole daemon's while loop */
149 buf_ValidateBuffers(void)
151 cm_buf_t * bp, *bpf, *bpa, *bpb;
152 afs_uint64 countb = 0, countf = 0, counta = 0;
154 if (cm_data.buf_freeListp == NULL && cm_data.buf_freeListEndp != NULL ||
155 cm_data.buf_freeListp != NULL && cm_data.buf_freeListEndp == NULL) {
156 afsi_log("cm_ValidateBuffers failure: inconsistent free list pointers");
157 fprintf(stderr, "cm_ValidateBuffers failure: inconsistent free list pointers\n");
161 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
162 if (bp->magic != CM_BUF_MAGIC) {
163 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
164 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
170 if (countb > cm_data.buf_nbuffers) {
171 afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
172 fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
177 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
178 if (bp->magic != CM_BUF_MAGIC) {
179 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
180 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
186 if (countf > cm_data.buf_nbuffers) {
187 afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
188 fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
193 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
194 if (bp->magic != CM_BUF_MAGIC) {
195 afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
196 fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
202 if (counta > cm_data.buf_nbuffers) {
203 afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
204 fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
209 if (countb != countf) {
210 afsi_log("cm_ValidateBuffers failure: countb != countf");
211 fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
215 if (counta != cm_data.buf_nbuffers) {
216 afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
217 fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
224 void buf_Shutdown(void)
226 buf_ShutdownFlag = 1;
229 /* initialize the buffer package; called with no locks
230 * held during the initialization phase.
232 long buf_Init(int newFile, cm_buf_ops_t *opsp, afs_uint64 nbuffers)
234 static osi_once_t once;
243 cm_data.buf_nbuffers = nbuffers;
245 /* Have to be able to reserve a whole chunk */
246 if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
247 return CM_ERROR_TOOFEWBUFS;
250 /* recall for callouts */
253 if (osi_Once(&once)) {
254 /* initialize global locks */
255 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock");
258 /* remember this for those who want to reset it */
259 cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
261 /* lower hash size to a prime number */
262 cm_data.buf_hashSize = osi_PrimeLessThan(CM_BUF_HASHSIZE);
264 /* create hash table */
265 memset((void *)cm_data.buf_hashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
267 /* another hash table */
268 memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
270 /* create buffer headers and put in free list */
271 bp = cm_data.bufHeaderBaseAddress;
272 data = cm_data.bufDataBaseAddress;
273 cm_data.buf_allp = NULL;
275 for (i=0; i<cm_data.buf_nbuffers; i++) {
276 osi_assert(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress);
277 osi_assert(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData);
279 /* allocate and zero some storage */
280 memset(bp, 0, sizeof(cm_buf_t));
281 bp->magic = CM_BUF_MAGIC;
282 /* thread on list of all buffers */
283 bp->allp = cm_data.buf_allp;
284 cm_data.buf_allp = bp;
286 osi_QAdd((osi_queue_t **)&cm_data.buf_freeListp, &bp->q);
287 bp->flags |= CM_BUF_INLRU;
288 lock_InitializeMutex(&bp->mx, "Buffer mutex");
290 /* grab appropriate number of bytes from aligned zone */
293 /* setup last buffer pointer */
295 cm_data.buf_freeListEndp = bp;
299 data += cm_data.buf_blockSize;
302 /* none reserved at first */
303 cm_data.buf_reservedBufs = 0;
305 /* just for safety's sake */
306 cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
308 bp = cm_data.bufHeaderBaseAddress;
309 data = cm_data.bufDataBaseAddress;
311 for (i=0; i<cm_data.buf_nbuffers; i++) {
312 lock_InitializeMutex(&bp->mx, "Buffer mutex");
315 bp->waitRequests = 0;
316 bp->flags &= ~CM_BUF_WAITING;
322 buf_ValidateBufQueues();
326 /* init the buffer trace log */
327 buf_logp = osi_LogCreate("buffer", 1000);
328 osi_LogEnable(buf_logp);
333 /* and create the incr-syncer */
334 phandle = thrd_Create(0, 0,
335 (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
338 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
339 CloseHandle(phandle);
343 buf_ValidateBufQueues();
348 /* add nbuffers to the buffer pool, if possible.
349 * Called with no locks held.
351 long buf_AddBuffers(afs_uint64 nbuffers)
353 /* The size of a virtual cache cannot be changed after it has
354 * been created. Subsequent calls to MapViewofFile() with
355 * an existing mapping object name would not allow the
356 * object to be resized. Return failure immediately.
358 * A similar problem now occurs with the persistent cache
359 * given that the memory mapped file now contains a complex
362 afsi_log("request to add %d buffers to the existing cache of size %d denied",
363 nbuffers, cm_data.buf_nbuffers);
365 return CM_ERROR_INVAL;
368 /* interface to set the number of buffers to an exact figure.
369 * Called with no locks held.
371 long buf_SetNBuffers(afs_uint64 nbuffers)
374 return CM_ERROR_INVAL;
375 if (nbuffers == cm_data.buf_nbuffers)
377 else if (nbuffers > cm_data.buf_nbuffers)
378 return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
380 return CM_ERROR_INVAL;
383 /* release a buffer. Buffer must be referenced, but unlocked. */
384 void buf_Release(cm_buf_t *bp)
386 lock_ObtainWrite(&buf_globalLock);
387 buf_LockedRelease(bp);
388 lock_ReleaseWrite(&buf_globalLock);
391 /* wait for reading or writing to clear; called with write-locked
392 * buffer and unlocked scp and returns with locked buffer.
394 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
397 osi_assert(scp->magic == CM_SCACHE_MAGIC);
398 osi_assert(bp->magic == CM_BUF_MAGIC);
401 /* if no IO is happening, we're done */
402 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
405 /* otherwise I/O is happening, but some other thread is waiting for
406 * the I/O already. Wait for that guy to figure out what happened,
407 * and then check again.
409 if ( bp->flags & CM_BUF_WAITING ) {
412 osi_Log1(afsd_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%p", bp);
414 osi_Log1(afsd_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%p", bp);
415 bp->flags |= CM_BUF_WAITING;
416 bp->waitCount = bp->waitRequests = 1;
418 osi_SleepM((LONG_PTR)bp, &bp->mx);
420 smb_UpdateServerPriority();
422 lock_ObtainMutex(&bp->mx);
423 osi_Log1(afsd_logp, "buf_WaitIO conflict wait done for 0x%p", bp);
425 if (bp->waitCount == 0) {
426 osi_Log1(afsd_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%p", bp);
427 bp->flags &= ~CM_BUF_WAITING;
428 bp->waitRequests = 0;
432 scp = cm_FindSCache(&bp->fid);
435 lock_ObtainMutex(&scp->mx);
436 if (scp->flags & CM_SCACHEFLAG_WAITING) {
437 osi_Log1(afsd_logp, "buf_WaitIO waking scp 0x%p", scp);
438 osi_Wakeup((LONG_PTR)&scp->flags);
440 lock_ReleaseMutex(&scp->mx);
444 /* if we get here, the IO is done, but we may have to wakeup people waiting for
445 * the I/O to complete. Do so.
447 if (bp->flags & CM_BUF_WAITING) {
448 osi_Log1(afsd_logp, "buf_WaitIO Waking bp 0x%p", bp);
449 osi_Wakeup((LONG_PTR) bp);
451 osi_Log1(afsd_logp, "WaitIO finished wait for bp 0x%p", bp);
454 /* code to drop reference count while holding buf_globalLock */
455 void buf_LockedRelease(cm_buf_t *bp)
457 /* ensure that we're in the LRU queue if our ref count is 0 */
458 osi_assert(bp->refCount > 0);
459 if (--bp->refCount == 0) {
460 if (!(bp->flags & CM_BUF_INLRU)) {
461 osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
463 /* watch for transition from empty to one element */
464 if (!cm_data.buf_freeListEndp)
465 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
466 bp->flags |= CM_BUF_INLRU;
471 /* find a buffer, if any, for a particular file ID and offset. Assumes
472 * that buf_globalLock is write locked when called.
474 cm_buf_t *buf_LockedFind(struct cm_scache *scp, osi_hyper_t *offsetp)
479 i = BUF_HASH(&scp->fid, offsetp);
480 for(bp = cm_data.buf_hashTablepp[i]; bp; bp=bp->hashp) {
481 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
482 && offsetp->LowPart == bp->offset.LowPart
483 && offsetp->HighPart == bp->offset.HighPart) {
489 /* return whatever we found, if anything */
493 /* find a buffer with offset *offsetp for vnode *scp. Called
494 * with no locks held.
496 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
500 lock_ObtainWrite(&buf_globalLock);
501 bp = buf_LockedFind(scp, offsetp);
502 lock_ReleaseWrite(&buf_globalLock);
507 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
510 * Makes sure that there's only one person writing this block
511 * at any given time, and also ensures that the log is forced sufficiently far,
512 * if this buffer contains logged data.
514 void buf_LockedCleanAsync(cm_buf_t *bp, cm_req_t *reqp)
518 osi_assert(bp->magic == CM_BUF_MAGIC);
520 while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
521 lock_ReleaseMutex(&bp->mx);
523 osi_Log1(afsd_logp, "buf_LockedCleanAsync starts I/O on 0x%p", bp);
524 code = (*cm_buf_opsp->Writep)(&bp->fid, &bp->offset,
525 cm_data.buf_blockSize, 0, bp->userp,
527 osi_Log2(afsd_logp, "buf_LockedCleanAsync I/O on 0x%p, done=%d", bp, code);
529 lock_ObtainMutex(&bp->mx);
534 /* Disk cache support */
535 /* write buffer to disk cache (synchronous for now) */
536 diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
537 #endif /* DISKCACHE95 */
540 /* do logging after call to GetLastError, or else */
542 /* if someone was waiting for the I/O that just completed or failed,
545 if (bp->flags & CM_BUF_WAITING) {
546 /* turn off flags and wakeup users */
547 osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
548 osi_Wakeup((LONG_PTR) bp);
552 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
553 * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
554 * The buffer must already be clean, and no I/O should be happening to it.
556 void buf_Recycle(cm_buf_t *bp)
561 cm_buf_t *prevBp, *nextBp;
563 osi_assert(bp->magic == CM_BUF_MAGIC);
565 /* if we get here, we know that the buffer still has a 0 ref count,
566 * and that it is clean and has no currently pending I/O. This is
567 * the dude to return.
568 * Remember that as long as the ref count is 0, we know that we won't
569 * have any lock conflicts, so we can grab the buffer lock out of
570 * order in the locking hierarchy.
572 osi_Log2( buf_logp, "buf_Recycle recycles 0x%p, off 0x%x",
573 bp, bp->offset.LowPart);
575 osi_assert(bp->refCount == 0);
576 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)));
577 lock_AssertWrite(&buf_globalLock);
579 if (bp->flags & CM_BUF_INHASH) {
580 /* Remove from hash */
582 i = BUF_HASH(&bp->fid, &bp->offset);
583 lbpp = &(cm_data.buf_hashTablepp[i]);
584 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
585 if (tbp == bp) break;
588 /* we better find it */
589 osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
591 *lbpp = bp->hashp; /* hash out */
593 /* Remove from file hash */
595 i = BUF_FILEHASH(&bp->fid);
596 prevBp = bp->fileHashBackp;
597 nextBp = bp->fileHashp;
599 prevBp->fileHashp = nextBp;
601 cm_data.buf_fileHashTablepp[i] = nextBp;
603 nextBp->fileHashBackp = prevBp;
605 bp->flags &= ~CM_BUF_INHASH;
608 /* bump the soft reference counter now, to invalidate softRefs; no
609 * wakeup is required since people don't sleep waiting for this
614 /* make the fid unrecognizable */
615 memset(&bp->fid, 0, sizeof(cm_fid_t));
618 /* recycle a buffer, removing it from the free list, hashing in its new identity
619 * and returning it write-locked so that no one can use it. Called without
620 * any locks held, and can return an error if it loses the race condition and
621 * finds that someone else created the desired buffer.
623 * If success is returned, the buffer is returned write-locked.
625 * May be called with null scp and offsetp, if we're just trying to reclaim some
626 * space from the buffer pool. In that case, the buffer will be returned
627 * without being hashed into the hash table.
629 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
631 cm_buf_t *bp; /* buffer we're dealing with */
632 cm_buf_t *nextBp; /* next buffer in file hash chain */
636 cm_InitReq(&req); /* just in case */
639 buf_ValidateBufQueues();
644 lock_ObtainWrite(&buf_globalLock);
645 /* check to see if we lost the race */
647 if (bp = buf_LockedFind(scp, offsetp)) {
649 lock_ReleaseWrite(&buf_globalLock);
650 return CM_BUF_EXISTS;
654 /* does this fix the problem below? it's a simple solution. */
655 if (!cm_data.buf_freeListEndp)
657 lock_ReleaseWrite(&buf_globalLock);
662 /* for debugging, assert free list isn't empty, although we
663 * really should try waiting for a running tranasction to finish
664 * instead of this; or better, we should have a transaction
665 * throttler prevent us from entering this situation.
667 osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
669 /* look at all buffers in free list, some of which may temp.
670 * have high refcounts and which then should be skipped,
671 * starting cleaning I/O for those which are dirty. If we find
672 * a clean buffer, we rehash it, lock it and return it.
674 for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
675 /* check to see if it really has zero ref count. This
676 * code can bump refcounts, at least, so it may not be
679 if (bp->refCount > 0)
682 /* we don't have to lock buffer itself, since the ref
683 * count is 0 and we know it will stay zero as long as
684 * we hold the global lock.
687 /* don't recycle someone in our own chunk */
688 if (!cm_FidCmp(&bp->fid, &scp->fid)
689 && (bp->offset.LowPart & (-cm_chunkSize))
690 == (offsetp->LowPart & (-cm_chunkSize)))
693 /* if this page is being filled (!) or cleaned, see if
694 * the I/O has completed. If not, skip it, otherwise
695 * do the final processing for the I/O.
697 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
698 /* probably shouldn't do this much work while
699 * holding the big lock? Watch for contention
705 if (bp->flags & CM_BUF_DIRTY) {
706 /* if the buffer is dirty, start cleaning it and
707 * move on to the next buffer. We do this with
708 * just the lock required to minimize contention
712 lock_ReleaseWrite(&buf_globalLock);
714 /* grab required lock and clean; this only
715 * starts the I/O. By the time we're back,
716 * it'll still be marked dirty, but it will also
717 * have the WRITING flag set, so we won't get
720 buf_CleanAsync(bp, &req);
722 /* now put it back and go around again */
727 /* if we get here, we know that the buffer still has a 0
728 * ref count, and that it is clean and has no currently
729 * pending I/O. This is the dude to return.
730 * Remember that as long as the ref count is 0, we know
731 * that we won't have any lock conflicts, so we can grab
732 * the buffer lock out of order in the locking hierarchy.
736 /* clean up junk flags */
737 bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
738 bp->dataVersion = -1; /* unknown so far */
740 /* now hash in as our new buffer, and give it the
741 * appropriate label, if requested.
744 bp->flags |= CM_BUF_INHASH;
746 bp->offset = *offsetp;
747 i = BUF_HASH(&scp->fid, offsetp);
748 bp->hashp = cm_data.buf_hashTablepp[i];
749 cm_data.buf_hashTablepp[i] = bp;
750 i = BUF_FILEHASH(&scp->fid);
751 nextBp = cm_data.buf_fileHashTablepp[i];
752 bp->fileHashp = nextBp;
753 bp->fileHashBackp = NULL;
755 nextBp->fileHashBackp = bp;
756 cm_data.buf_fileHashTablepp[i] = bp;
759 /* prepare to return it. Start by giving it a good
763 /* and since it has a non-zero ref count, we should move
764 * it from the lru queue. It better be still there,
765 * since we've held the global (big) lock since we found
768 osi_assertx(bp->flags & CM_BUF_INLRU,
769 "buf_GetNewLocked: LRU screwup");
770 if (cm_data.buf_freeListEndp == bp) {
771 /* we're the last guy in this queue, so maintain it */
772 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
774 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
775 bp->flags &= ~CM_BUF_INLRU;
777 /* finally, grab the mutex so that people don't use it
778 * before the caller fills it with data. Again, no one
779 * should have been able to get to this dude to lock it.
781 osi_assertx(lock_TryMutex(&bp->mx),
782 "buf_GetNewLocked: TryMutex failed");
784 lock_ReleaseWrite(&buf_globalLock);
788 buf_ValidateBufQueues();
791 } /* for all buffers in lru queue */
792 lock_ReleaseWrite(&buf_globalLock);
793 } /* while loop over everything */
797 /* get a page, returning it held but unlocked. Doesn't fill in the page
798 * with I/O, since we're going to write the whole thing new.
800 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
804 osi_hyper_t pageOffset;
808 pageOffset.HighPart = offsetp->HighPart;
809 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
811 bp = buf_Find(scp, &pageOffset);
813 /* lock it and break out */
814 lock_ObtainMutex(&bp->mx);
818 /* otherwise, we have to create a page */
819 code = buf_GetNewLocked(scp, &pageOffset, &bp);
821 /* check if the buffer was created in a race condition branch.
822 * If so, go around so we can hold a reference to it.
824 if (code == CM_BUF_EXISTS)
827 /* something else went wrong */
831 /* otherwise, we have a locked buffer that we just created */
834 } /* big while loop */
837 if (bp->flags & CM_BUF_READING)
840 /* once it has been read once, we can unlock it and return it, still
841 * with its refcount held.
843 lock_ReleaseMutex(&bp->mx);
845 osi_Log3(buf_logp, "buf_GetNew returning bp 0x%p for scp 0x%p, offset 0x%x",
846 bp, scp, offsetp->LowPart);
850 /* get a page, returning it held but unlocked. Make sure it is complete */
851 /* The scp must be unlocked when passed to this function */
852 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
856 osi_hyper_t pageOffset;
857 unsigned long tcount;
862 #endif /* DISKCACHE95 */
865 pageOffset.HighPart = offsetp->HighPart;
866 pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
870 buf_ValidateBufQueues();
873 bp = buf_Find(scp, &pageOffset);
875 /* lock it and break out */
876 lock_ObtainMutex(&bp->mx);
880 /* touch disk chunk to update LRU info */
881 diskcache_Touch(bp->dcp);
882 #endif /* DISKCACHE95 */
885 /* otherwise, we have to create a page */
886 code = buf_GetNewLocked(scp, &pageOffset, &bp);
888 /* check if the buffer was created in a race condition branch.
889 * If so, go around so we can hold a reference to it.
891 if (code == CM_BUF_EXISTS)
894 /* something else went wrong */
897 buf_ValidateBufQueues();
902 /* otherwise, we have a locked buffer that we just created */
905 } /* big while loop */
907 /* if we get here, we have a locked buffer that may have just been
908 * created, in which case it needs to be filled with data.
911 /* load the page; freshly created pages should be idle */
912 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
914 /* setup offset, event */
915 bp->over.Offset = bp->offset.LowPart;
916 bp->over.OffsetHigh = bp->offset.HighPart;
918 /* start the I/O; may drop lock */
919 bp->flags |= CM_BUF_READING;
920 code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
923 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
924 bp->dcp = dcp; /* pointer to disk cache struct. */
925 #endif /* DISKCACHE95 */
928 /* failure or queued */
929 if (code != ERROR_IO_PENDING) {
931 bp->flags |= CM_BUF_ERROR;
932 bp->flags &= ~CM_BUF_READING;
933 if (bp->flags & CM_BUF_WAITING) {
934 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
935 osi_Wakeup((LONG_PTR) bp);
937 lock_ReleaseMutex(&bp->mx);
940 buf_ValidateBufQueues();
945 /* otherwise, I/O completed instantly and we're done, except
946 * for padding the xfr out with 0s and checking for EOF
948 if (tcount < (unsigned long) cm_data.buf_blockSize) {
949 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
951 bp->flags |= CM_BUF_EOF;
953 bp->flags &= ~CM_BUF_READING;
954 if (bp->flags & CM_BUF_WAITING) {
955 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
956 osi_Wakeup((LONG_PTR) bp);
962 /* wait for reads, either that which we started above, or that someone
963 * else started. We don't care if we return a buffer being cleaned.
965 if (bp->flags & CM_BUF_READING)
968 /* once it has been read once, we can unlock it and return it, still
969 * with its refcount held.
971 lock_ReleaseMutex(&bp->mx);
974 /* now remove from queue; will be put in at the head (farthest from
975 * being recycled) when we're done in buf_Release.
977 lock_ObtainWrite(&buf_globalLock);
978 if (bp->flags & CM_BUF_INLRU) {
979 if (cm_data.buf_freeListEndp == bp)
980 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
981 osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
982 bp->flags &= ~CM_BUF_INLRU;
984 lock_ReleaseWrite(&buf_globalLock);
986 osi_Log3(buf_logp, "buf_Get returning bp 0x%p for scp 0x%p, offset 0x%x",
987 bp, scp, offsetp->LowPart);
989 buf_ValidateBufQueues();
994 /* count # of elements in the free list;
995 * we don't bother doing the proper locking for accessing dataVersion or flags
996 * since it is a pain, and this is really just an advisory call. If you need
997 * to do better at some point, rewrite this function.
999 long buf_CountFreeList(void)
1005 lock_ObtainRead(&buf_globalLock);
1006 for(bufp = cm_data.buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1007 /* if the buffer doesn't have an identity, or if the buffer
1008 * has been invalidate (by having its DV stomped upon), then
1009 * count it as free, since it isn't really being utilized.
1011 if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1014 lock_ReleaseRead(&buf_globalLock);
1018 /* clean a buffer synchronously */
1019 void buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1021 osi_assert(bp->magic == CM_BUF_MAGIC);
1023 lock_ObtainMutex(&bp->mx);
1024 buf_LockedCleanAsync(bp, reqp);
1025 lock_ReleaseMutex(&bp->mx);
1028 /* wait for a buffer's cleaning to finish */
1029 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp)
1031 osi_assert(bp->magic == CM_BUF_MAGIC);
1033 lock_ObtainMutex(&bp->mx);
1034 if (bp->flags & CM_BUF_WRITING) {
1035 buf_WaitIO(scp, bp);
1037 lock_ReleaseMutex(&bp->mx);
1040 /* set the dirty flag on a buffer, and set associated write-ahead log,
1041 * if there is one. Allow one to be added to a buffer, but not changed.
1043 * The buffer must be locked before calling this routine.
1045 void buf_SetDirty(cm_buf_t *bp)
1047 osi_assert(bp->magic == CM_BUF_MAGIC);
1048 osi_assert(bp->refCount > 0);
1050 osi_Log1(buf_logp, "buf_SetDirty 0x%p", bp);
1053 bp->flags |= CM_BUF_DIRTY;
1055 /* and turn off EOF flag, since it has associated data now */
1056 bp->flags &= ~CM_BUF_EOF;
1059 /* clean all buffers, reset log pointers and invalidate all buffers.
1060 * Called with no locks held, and returns with same.
1062 * This function is guaranteed to clean and remove the log ptr of all the
1063 * buffers that were dirty or had non-zero log ptrs before the call was
1064 * made. That's sufficient to clean up any garbage left around by recovery,
1065 * which is all we're counting on this for; there may be newly created buffers
1066 * added while we're running, but that should be OK.
1068 * In an environment where there are no transactions (artificially imposed, for
1069 * example, when switching the database to raw mode), this function is used to
1070 * make sure that all updates have been written to the disk. In that case, we don't
1071 * really require that we forget the log association between pages and logs, but
1072 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1073 * have to worry about invalidating data in the buffers.
1075 * This function is used at the end of recovery as paranoia to get the recovered
1076 * database out to disk. It removes all references to the recovery log and cleans
1079 long buf_CleanAndReset(void)
1085 lock_ObtainWrite(&buf_globalLock);
1086 for(i=0; i<cm_data.buf_hashSize; i++) {
1087 for(bp = cm_data.buf_hashTablepp[i]; bp; bp = bp->hashp) {
1088 if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1090 lock_ReleaseWrite(&buf_globalLock);
1092 /* now no locks are held; clean buffer and go on */
1094 buf_CleanAsync(bp, &req);
1095 buf_CleanWait(NULL, bp);
1097 /* relock and release buffer */
1098 lock_ObtainWrite(&buf_globalLock);
1099 buf_LockedRelease(bp);
1101 } /* over one bucket */
1102 } /* for loop over all hash buckets */
1105 lock_ReleaseWrite(&buf_globalLock);
1108 buf_ValidateBufQueues();
1109 #endif /* TESTING */
1111 /* and we're done */
1115 /* called without global lock being held, reserves buffers for callers
1116 * that need more than one held (not locked) at once.
1118 void buf_ReserveBuffers(afs_uint64 nbuffers)
1120 lock_ObtainWrite(&buf_globalLock);
1122 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1123 cm_data.buf_reserveWaiting = 1;
1124 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1125 osi_SleepW((LONG_PTR) &cm_data.buf_reservedBufs, &buf_globalLock);
1126 lock_ObtainWrite(&buf_globalLock);
1129 cm_data.buf_reservedBufs += nbuffers;
1133 lock_ReleaseWrite(&buf_globalLock);
1136 int buf_TryReserveBuffers(afs_uint64 nbuffers)
1140 lock_ObtainWrite(&buf_globalLock);
1141 if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1145 cm_data.buf_reservedBufs += nbuffers;
1148 lock_ReleaseWrite(&buf_globalLock);
1152 /* called without global lock held, releases reservation held by
1153 * buf_ReserveBuffers.
1155 void buf_UnreserveBuffers(afs_uint64 nbuffers)
1157 lock_ObtainWrite(&buf_globalLock);
1158 cm_data.buf_reservedBufs -= nbuffers;
1159 if (cm_data.buf_reserveWaiting) {
1160 cm_data.buf_reserveWaiting = 0;
1161 osi_Wakeup((LONG_PTR) &cm_data.buf_reservedBufs);
1163 lock_ReleaseWrite(&buf_globalLock);
1166 /* truncate the buffers past sizep, zeroing out the page, if we don't
1167 * end on a page boundary.
1169 * Requires cm_bufCreateLock to be write locked.
1171 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1175 cm_buf_t *nbufp; /* next buffer, if didRelease */
1182 /* assert that cm_bufCreateLock is held in write mode */
1183 lock_AssertWrite(&scp->bufCreateLock);
1185 i = BUF_FILEHASH(&scp->fid);
1187 lock_ObtainWrite(&buf_globalLock);
1188 bufp = cm_data.buf_fileHashTablepp[i];
1190 lock_ReleaseWrite(&buf_globalLock);
1195 lock_ReleaseWrite(&buf_globalLock);
1196 for(; bufp; bufp = nbufp) {
1198 lock_ObtainMutex(&bufp->mx);
1200 bufEnd.HighPart = 0;
1201 bufEnd.LowPart = cm_data.buf_blockSize;
1202 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1204 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1205 LargeIntegerLessThan(*sizep, bufEnd)) {
1206 buf_WaitIO(scp, bufp);
1208 lock_ObtainMutex(&scp->mx);
1210 /* make sure we have a callback (so we have the right value for
1211 * the length), and wait for it to be safe to do a truncate.
1213 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1214 CM_SCACHESYNC_NEEDCALLBACK
1215 | CM_SCACHESYNC_GETSTATUS
1216 | CM_SCACHESYNC_SETSIZE
1217 | CM_SCACHESYNC_BUFLOCKED);
1218 /* if we succeeded in our locking, and this applies to the right
1219 * file, and the truncate request overlaps the buffer either
1220 * totally or partially, then do something.
1222 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1223 && LargeIntegerLessThan(*sizep, bufEnd)) {
1225 lock_ObtainWrite(&buf_globalLock);
1227 /* destroy the buffer, turning off its dirty bit, if
1228 * we're truncating the whole buffer. Otherwise, set
1229 * the dirty bit, and clear out the tail of the buffer
1230 * if we just overlap some.
1232 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1233 /* truncating the entire page */
1234 bufp->flags &= ~CM_BUF_DIRTY;
1235 bufp->dataVersion = -1; /* known bad */
1236 bufp->dirtyCounter++;
1239 /* don't set dirty, since dirty implies
1240 * currently up-to-date. Don't need to do this,
1241 * since we'll update the length anyway.
1243 * Zero out remainder of the page, in case we
1244 * seek and write past EOF, and make this data
1247 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1248 osi_assert(bufferPos != 0);
1249 memset(bufp->datap + bufferPos, 0,
1250 cm_data.buf_blockSize - bufferPos);
1253 lock_ReleaseWrite(&buf_globalLock);
1256 lock_ReleaseMutex(&scp->mx);
1257 lock_ReleaseMutex(&bufp->mx);
1259 lock_ObtainWrite(&buf_globalLock);
1260 nbufp = bufp->fileHashp;
1261 if (nbufp) nbufp->refCount++;
1262 buf_LockedRelease(bufp);
1263 lock_ReleaseWrite(&buf_globalLock);
1266 /* bail out early if we fail */
1268 /* at this point, nbufp is held; bufp has already been
1275 buf_ValidateBufQueues();
1276 #endif /* TESTING */
1283 buf_ValidateBufQueues();
1284 #endif /* TESTING */
1290 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1293 cm_buf_t *bp; /* buffer we're hacking on */
1298 i = BUF_FILEHASH(&scp->fid);
1301 lock_ObtainWrite(&buf_globalLock);
1302 bp = cm_data.buf_fileHashTablepp[i];
1305 lock_ReleaseWrite(&buf_globalLock);
1306 for (; bp; bp = nbp) {
1307 didRelease = 0; /* haven't released this buffer yet */
1309 /* clean buffer synchronously */
1310 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1311 lock_ObtainMutex(&bp->mx);
1313 /* start cleaning the buffer, and wait for it to finish */
1314 buf_LockedCleanAsync(bp, reqp);
1315 buf_WaitIO(scp, bp);
1316 lock_ReleaseMutex(&bp->mx);
1318 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1322 lock_ObtainWrite(&buf_globalLock);
1323 /* actually, we only know that buffer is clean if ref
1324 * count is 1, since we don't have buffer itself locked.
1326 if (!(bp->flags & CM_BUF_DIRTY)) {
1327 if (bp->refCount == 1) { /* bp is held above */
1328 buf_LockedRelease(bp);
1329 nbp = bp->fileHashp;
1336 lock_ReleaseWrite(&buf_globalLock);
1338 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1343 lock_ObtainWrite(&buf_globalLock);
1344 if (nbp = bp->fileHashp)
1346 buf_LockedRelease(bp);
1347 lock_ReleaseWrite(&buf_globalLock);
1349 } /* for loop over a bunch of buffers */
1352 buf_ValidateBufQueues();
1353 #endif /* TESTING */
1359 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1362 cm_buf_t *bp; /* buffer we're hacking on */
1363 cm_buf_t *nbp; /* next one */
1366 i = BUF_FILEHASH(&scp->fid);
1369 lock_ObtainWrite(&buf_globalLock);
1370 bp = cm_data.buf_fileHashTablepp[i];
1373 lock_ReleaseWrite(&buf_globalLock);
1374 for (; bp; bp = nbp) {
1375 /* clean buffer synchronously */
1376 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1379 lock_ObtainMutex(&bp->mx);
1381 cm_ReleaseUser(bp->userp);
1383 lock_ReleaseMutex(&bp->mx);
1385 buf_CleanAsync(bp, reqp);
1386 buf_CleanWait(scp, bp);
1387 lock_ObtainMutex(&bp->mx);
1388 if (bp->flags & CM_BUF_ERROR) {
1389 if (code == 0 || code == -1)
1394 lock_ReleaseMutex(&bp->mx);
1397 lock_ObtainWrite(&buf_globalLock);
1398 buf_LockedRelease(bp);
1399 nbp = bp->fileHashp;
1402 lock_ReleaseWrite(&buf_globalLock);
1403 } /* for loop over a bunch of buffers */
1406 buf_ValidateBufQueues();
1407 #endif /* TESTING */
1415 buf_ValidateBufQueues(void)
1417 cm_buf_t * bp, *bpb, *bpf, *bpa;
1418 afs_uint32 countf=0, countb=0, counta=0;
1420 lock_ObtainRead(&buf_globalLock);
1421 for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1422 if (bp->magic != CM_BUF_MAGIC)
1428 for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
1429 if (bp->magic != CM_BUF_MAGIC)
1435 for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
1436 if (bp->magic != CM_BUF_MAGIC)
1441 lock_ReleaseRead(&buf_globalLock);
1443 if (countb != countf)
1446 if (counta != cm_data.buf_nbuffers)
1449 #endif /* TESTING */
1451 /* dump the contents of the buf_hashTablepp. */
1452 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
1459 if (cm_data.buf_hashTablepp == NULL)
1463 lock_ObtainRead(&buf_globalLock);
1465 StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\n",
1466 cookie, cm_data.buf_hashSize);
1467 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1469 for (i = 0; i < cm_data.buf_hashSize; i++)
1471 for (bp = cm_data.buf_hashTablepp[i]; bp; bp=bp->hashp)
1475 StringCbPrintfA(output, sizeof(output), "vnode=%d, unique=%d), size=%d refCount=%d\n",
1476 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
1477 bp->fid.vnode, bp->fid.unique, bp->size, bp->refCount);
1478 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1483 StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\n", cookie);
1484 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1487 lock_ReleaseRead(&buf_globalLock);
1491 void buf_ForceTrace(BOOL flush)
1500 len = GetTempPath(sizeof(buf)-10, buf);
1501 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
1502 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
1503 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1504 if (handle == INVALID_HANDLE_VALUE) {
1505 osi_panic("Cannot create log file", __FILE__, __LINE__);
1507 osi_LogPrint(buf_logp, handle);
1509 FlushFileBuffers(handle);
1510 CloseHandle(handle);