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 extern void afsi_log(char *pattern, ...);
27 /* This module implements the buffer package used by the local transaction
28 * system (cm). It is initialized by calling cm_Init, which calls buf_Init;
29 * it must be initalized before any of its main routines are called.
31 * Each buffer is hashed into a hash table by file ID and offset, and if its
32 * reference count is zero, it is also in a free list.
34 * There are two locks involved in buffer processing. The global lock
35 * buf_globalLock protects all of the global variables defined in this module,
36 * the reference counts and hash pointers in the actual cm_buf_t structures,
37 * and the LRU queue pointers in the buffer structures.
39 * The mutexes in the buffer structures protect the remaining fields in the
40 * buffers, as well the data itself.
42 * The locking hierarchy here is this:
44 * - resv multiple simul. buffers reservation
45 * - lock buffer I/O flags
46 * - lock buffer's mutex
47 * - lock buf_globalLock
51 /* global debugging log */
52 osi_log_t *buf_logp = NULL;
54 /* Global lock protecting hash tables and free lists */
55 osi_rwlock_t buf_globalLock;
57 /* ptr to head of the free list (most recently used) and the
58 * tail (the guy to remove first). We use osi_Q* functions
59 * to put stuff in buf_freeListp, and maintain the end
62 cm_buf_t *buf_freeListp;
63 cm_buf_t *buf_freeListEndp;
65 /* a pointer to a list of all buffers, just so that we can find them
66 * easily for debugging, and for the incr syncer. Locked under
71 /* defaults setup; these variables may be manually assigned into
72 * before calling cm_Init, as a way of changing these defaults.
74 long buf_nbuffers = CM_BUF_BUFFERS;
75 long buf_nOrigBuffers;
76 long buf_bufferSize = CM_BUF_SIZE;
77 long buf_hashSize = CM_BUF_HASHSIZE;
78 int buf_cacheType = CM_BUF_CACHETYPE_FILE;
88 /* buffer reservation variables */
89 long buf_reservedBufs;
90 long buf_maxReservedBufs;
91 int buf_reserveWaiting;
93 /* callouts for reading and writing data, etc */
94 cm_buf_ops_t *cm_buf_opsp;
96 /* pointer to hash table; size computed dynamically */
97 cm_buf_t **buf_hashTablepp;
99 /* another hash table */
100 cm_buf_t **buf_fileHashTablepp;
103 /* for experimental disk caching support in Win95 client */
104 cm_buf_t *buf_diskFreeListp;
105 cm_buf_t *buf_diskFreeListEndp;
106 cm_buf_t *buf_diskAllp;
107 extern int cm_diskCacheEnabled;
108 #endif /* DISKCACHE95 */
110 /* hold a reference to an already held buffer */
111 void buf_Hold(cm_buf_t *bp)
113 lock_ObtainWrite(&buf_globalLock);
115 lock_ReleaseWrite(&buf_globalLock);
118 /* incremental sync daemon. Writes 1/10th of all the buffers every 5000 ms */
119 void buf_IncrSyncer(long parm)
121 cm_buf_t *bp; /* buffer we're hacking on; held */
122 long i; /* counter */
123 long nAtOnce; /* how many to do at once */
126 lock_ObtainWrite(&buf_globalLock);
129 lock_ReleaseWrite(&buf_globalLock);
130 nAtOnce = buf_nbuffers / 10;
133 i = SleepEx(5000, 1);
134 if (i != 0) continue;
139 /* now go through our percentage of the buffers */
140 for(i=0; i<nAtOnce; i++) {
141 /* don't want its identity changing while we're
142 * messing with it, so must do all of this with
146 /* start cleaning the buffer; don't touch log pages since
147 * the log code counts on knowing exactly who is writing
148 * a log page at any given instant.
151 req.flags |= CM_REQ_NORETRY;
152 buf_CleanAsync(bp, &req);
154 /* now advance to the next buffer; the allp chain never changes,
155 * and so can be followed even when holding no locks.
157 lock_ObtainWrite(&buf_globalLock);
158 buf_LockedRelease(bp);
160 if (!bp) bp = buf_allp;
162 lock_ReleaseWrite(&buf_globalLock);
163 } /* for loop over a bunch of buffers */
164 } /* whole daemon's while loop */
168 /* Create a security attribute structure suitable for use when the cache file
169 * is created. What we mainly want is that only the administrator should be
170 * able to do anything with the file. We create an ACL with only one entry,
171 * an entry that grants all rights to the administrator.
173 PSECURITY_ATTRIBUTES CreateCacheFileSA()
175 PSECURITY_ATTRIBUTES psa;
176 PSECURITY_DESCRIPTOR psd;
177 SID_IDENTIFIER_AUTHORITY authority = SECURITY_NT_AUTHORITY;
179 DWORD AdminSIDlength;
183 /* Get Administrator SID */
184 AllocateAndInitializeSid(&authority, 2,
185 SECURITY_BUILTIN_DOMAIN_RID,
186 DOMAIN_ALIAS_RID_ADMINS,
190 /* Create Administrator-only ACL */
191 AdminSIDlength = GetLengthSid(AdminSID);
192 ACLlength = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE)
193 + AdminSIDlength - sizeof(DWORD);
194 AdminOnlyACL = GlobalAlloc(GMEM_FIXED, ACLlength);
195 InitializeAcl(AdminOnlyACL, ACLlength, ACL_REVISION);
196 AddAccessAllowedAce(AdminOnlyACL, ACL_REVISION,
197 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL,
200 /* Create security descriptor */
201 psd = GlobalAlloc(GMEM_FIXED, sizeof(SECURITY_DESCRIPTOR));
202 InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION);
203 SetSecurityDescriptorDacl(psd, TRUE, AdminOnlyACL, FALSE);
205 /* Create security attributes structure */
206 psa = GlobalAlloc(GMEM_FIXED, sizeof(SECURITY_ATTRIBUTES));
207 psa->nLength = sizeof(SECURITY_ATTRIBUTES);
208 psa->lpSecurityDescriptor = psd;
209 psa->bInheritHandle = TRUE;
216 /* Free a security attribute structure created by CreateCacheFileSA() */
217 VOID FreeCacheFileSA(PSECURITY_ATTRIBUTES psa)
222 GetSecurityDescriptorDacl(psa->lpSecurityDescriptor, &b1, &pAcl, &b2);
224 GlobalFree(psa->lpSecurityDescriptor);
229 /* initialize the buffer package; called with no locks
230 * held during the initialization phase.
232 long buf_Init(cm_buf_ops_t *opsp)
234 static osi_once_t once;
240 PSECURITY_ATTRIBUTES psa;
248 /* Get system info; all we really want is the allocation granularity */
249 GetSystemInfo(&sysInfo);
252 /* Have to be able to reserve a whole chunk */
253 if (((buf_nbuffers - 3) * buf_bufferSize) < cm_chunkSize)
254 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");
265 * Cache file mapping constrained by
266 * system allocation granularity;
267 * round up, assuming granularity is a power of two
269 cs = buf_nbuffers * buf_bufferSize;
270 cs = (cs + (sysInfo.dwAllocationGranularity - 1))
271 & ~(sysInfo.dwAllocationGranularity - 1);
272 if (cs != buf_nbuffers * buf_bufferSize) {
273 buf_nbuffers = cs / buf_bufferSize;
274 afsi_log("Cache size rounded up to %d buffers",
279 /* remember this for those who want to reset it */
280 buf_nOrigBuffers = buf_nbuffers;
282 /* lower hash size to a prime number */
283 buf_hashSize = osi_PrimeLessThan(buf_hashSize);
285 /* create hash table */
286 buf_hashTablepp = malloc(buf_hashSize * sizeof(cm_buf_t *));
287 memset((void *)buf_hashTablepp, 0,
288 buf_hashSize * sizeof(cm_buf_t *));
290 /* another hash table */
291 buf_fileHashTablepp = malloc(buf_hashSize * sizeof(cm_buf_t *));
292 memset((void *)buf_fileHashTablepp, 0,
293 buf_hashSize * sizeof(cm_buf_t *));
295 /* min value for which this works */
299 if(buf_cacheType == CM_BUF_CACHETYPE_FILE) {
300 /* Reserve buffer space by mapping cache file */
301 psa = CreateCacheFileSA();
302 hf = CreateFile(cm_CachePath,
303 GENERIC_READ | GENERIC_WRITE,
304 FILE_SHARE_READ | FILE_SHARE_WRITE,
307 FILE_ATTRIBUTE_NORMAL,
309 if (hf == INVALID_HANDLE_VALUE) {
310 afsi_log("create file error %d", GetLastError());
311 return CM_ERROR_INVAL;
313 FreeCacheFileSA(psa);
314 } else { /* buf_cacheType == CM_BUF_CACHETYPE_VIRTUAL */
315 hf = INVALID_HANDLE_VALUE;
318 hm = CreateFileMapping(hf,
321 0, buf_nbuffers * buf_bufferSize,
324 if (GetLastError() == ERROR_DISK_FULL) {
325 afsi_log("Error creating cache file mapping: disk full");
326 return CM_ERROR_TOOMANYBUFS;
328 return CM_ERROR_INVAL;
330 data = MapViewOfFile(hm,
333 buf_nbuffers * buf_bufferSize);
335 if(hf != INVALID_HANDLE_VALUE) CloseHandle(hf);
337 return CM_ERROR_INVAL;
341 /* djgpp doesn't support memory mapped files */
342 data = malloc(buf_nbuffers * buf_bufferSize);
345 /* create buffer headers and put in free list */
346 bp = malloc(buf_nbuffers * sizeof(cm_buf_t));
348 for(i=0; i<buf_nbuffers; i++) {
349 /* allocate and zero some storage */
350 memset(bp, 0, sizeof(cm_buf_t));
352 /* thread on list of all buffers */
356 osi_QAdd((osi_queue_t **)&buf_freeListp, &bp->q);
357 bp->flags |= CM_BUF_INLRU;
358 lock_InitializeMutex(&bp->mx, "Buffer mutex");
360 /* grab appropriate number of bytes from aligned zone */
363 /* setup last buffer pointer */
365 buf_freeListEndp = bp;
369 data += buf_bufferSize;
372 /* none reserved at first */
373 buf_reservedBufs = 0;
375 /* just for safety's sake */
376 buf_maxReservedBufs = buf_nbuffers - 3;
378 /* init the buffer trace log */
379 buf_logp = osi_LogCreate("buffer", 10);
383 /* and create the incr-syncer */
384 phandle = thrd_Create(0, 0,
385 (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
388 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
390 CloseHandle(phandle);
397 /* add nbuffers to the buffer pool, if possible.
398 * Called with no locks held.
400 long buf_AddBuffers(long nbuffers)
409 afsi_log("%d buffers being added to the existing cache of size %d",
410 nbuffers, buf_nbuffers);
412 if (buf_cacheType == CM_BUF_CACHETYPE_VIRTUAL) {
413 /* The size of a virtual cache cannot be changed after it has
414 * been created. Subsequent calls to MapViewofFile() with
415 * an existing mapping object name would not allow the
416 * object to be resized. Return failure immediately.
418 return CM_ERROR_INVAL;
422 * Cache file mapping constrained by
423 * system allocation granularity;
424 * round up, assuming granularity is a power of two;
425 * assume existing cache size is already rounded
427 cs = nbuffers * buf_bufferSize;
428 cs = (cs + (sysInfo.dwAllocationGranularity - 1))
429 & ~(sysInfo.dwAllocationGranularity - 1);
430 if (cs != nbuffers * buf_bufferSize) {
431 nbuffers = cs / buf_bufferSize;
434 /* Reserve additional buffer space by remapping cache file */
435 hm = CreateFileMapping(CacheHandle,
438 0, (buf_nbuffers + nbuffers) * buf_bufferSize,
441 if (GetLastError() == ERROR_DISK_FULL)
442 return CM_ERROR_TOOMANYBUFS;
444 return CM_ERROR_INVAL;
446 data = MapViewOfFile(hm,
448 0, buf_nbuffers * buf_bufferSize,
449 nbuffers * buf_bufferSize);
452 return CM_ERROR_INVAL;
456 data = malloc(buf_nbuffers * buf_bufferSize);
459 /* Create buffer headers and put in free list */
460 bp = malloc(nbuffers * sizeof(*bp));
462 for(i=0; i<nbuffers; i++) {
463 memset(bp, 0, sizeof(*bp));
465 lock_InitializeMutex(&bp->mx, "cm_buf_t");
467 /* grab appropriate number of bytes from aligned zone */
470 bp->flags |= CM_BUF_INLRU;
472 lock_ObtainWrite(&buf_globalLock);
473 /* note that buf_allp chain is covered by buf_globalLock now */
476 osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
477 if (!buf_freeListEndp) buf_freeListEndp = bp;
479 lock_ReleaseWrite(&buf_globalLock);
482 data += buf_bufferSize;
484 } /* for loop over all buffers */
489 /* interface to set the number of buffers to an exact figure.
490 * Called with no locks held.
492 long buf_SetNBuffers(long nbuffers)
494 if (nbuffers < 10) return CM_ERROR_INVAL;
495 if (nbuffers == buf_nbuffers) return 0;
496 else if (nbuffers > buf_nbuffers)
497 return buf_AddBuffers(nbuffers - buf_nbuffers);
498 else return CM_ERROR_INVAL;
501 /* release a buffer. Buffer must be referenced, but unlocked. */
502 void buf_Release(cm_buf_t *bp)
504 lock_ObtainWrite(&buf_globalLock);
505 buf_LockedRelease(bp);
506 lock_ReleaseWrite(&buf_globalLock);
509 /* wait for reading or writing to clear; called with write-locked
510 * buffer, and returns with locked buffer.
512 void buf_WaitIO(cm_buf_t *bp)
515 /* if no IO is happening, we're done */
516 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
519 /* otherwise I/O is happening, but some other thread is waiting for
520 * the I/O already. Wait for that guy to figure out what happened,
521 * and then check again.
523 if ( bp->flags & CM_BUF_WAITING )
524 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%x", bp);
526 bp->flags |= CM_BUF_WAITING;
527 osi_SleepM((long) bp, &bp->mx);
528 lock_ObtainMutex(&bp->mx);
529 osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%x", bp);
532 /* if we get here, the IO is done, but we may have to wakeup people waiting for
533 * the I/O to complete. Do so.
535 if (bp->flags & CM_BUF_WAITING) {
536 bp->flags &= ~CM_BUF_WAITING;
537 osi_Wakeup((long) bp);
539 osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%x", (long) bp);
542 /* code to drop reference count while holding buf_globalLock */
543 void buf_LockedRelease(cm_buf_t *bp)
545 /* ensure that we're in the LRU queue if our ref count is 0 */
546 osi_assert(bp->refCount > 0);
547 if (--bp->refCount == 0) {
548 if (!(bp->flags & CM_BUF_INLRU)) {
549 osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
551 /* watch for transition from empty to one element */
552 if (!buf_freeListEndp)
553 buf_freeListEndp = buf_freeListp;
554 bp->flags |= CM_BUF_INLRU;
559 /* find a buffer, if any, for a particular file ID and offset. Assumes
560 * that buf_globalLock is write locked when called.
562 cm_buf_t *buf_LockedFind(struct cm_scache *scp, osi_hyper_t *offsetp)
567 i = BUF_HASH(&scp->fid, offsetp);
568 for(bp = buf_hashTablepp[i]; bp; bp=bp->hashp) {
569 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
570 && offsetp->LowPart == bp->offset.LowPart
571 && offsetp->HighPart == bp->offset.HighPart) {
577 /* return whatever we found, if anything */
581 /* find a buffer with offset *offsetp for vnode *scp. Called
582 * with no locks held.
584 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
588 lock_ObtainWrite(&buf_globalLock);
589 bp = buf_LockedFind(scp, offsetp);
590 lock_ReleaseWrite(&buf_globalLock);
595 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
598 * Makes sure that there's only one person writing this block
599 * at any given time, and also ensures that the log is forced sufficiently far,
600 * if this buffer contains logged data.
602 void buf_LockedCleanAsync(cm_buf_t *bp, cm_req_t *reqp)
607 while ((bp->flags & (CM_BUF_WRITING | CM_BUF_DIRTY)) == CM_BUF_DIRTY) {
608 lock_ReleaseMutex(&bp->mx);
610 code = (*cm_buf_opsp->Writep)(&bp->fid, &bp->offset,
611 buf_bufferSize, 0, bp->userp,
614 lock_ObtainMutex(&bp->mx);
618 /* Disk cache support */
619 /* write buffer to disk cache (synchronous for now) */
620 diskcache_Update(bp->dcp, bp->datap, buf_bufferSize, bp->dataVersion);
621 #endif /* DISKCACHE95 */
624 /* do logging after call to GetLastError, or else */
625 osi_Log2(buf_logp, "buf_CleanAsync starts I/O on 0x%x, done=%d", bp, code);
627 /* if someone was waiting for the I/O that just completed or failed,
630 if (bp->flags & CM_BUF_WAITING) {
631 /* turn off flags and wakeup users */
632 bp->flags &= ~CM_BUF_WAITING;
633 osi_Wakeup((long) bp);
637 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
638 * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
639 * The buffer must already be clean, and no I/O should be happening to it.
641 void buf_Recycle(cm_buf_t *bp)
646 cm_buf_t *prevBp, *nextBp;
648 /* if we get here, we know that the buffer still has a 0 ref count,
649 * and that it is clean and has no currently pending I/O. This is
650 * the dude to return.
651 * Remember that as long as the ref count is 0, we know that we won't
652 * have any lock conflicts, so we can grab the buffer lock out of
653 * order in the locking hierarchy.
656 "buf_Recycle recycles 0x%x, off 0x%x",
657 bp, bp->offset.LowPart);
659 osi_assert(bp->refCount == 0);
660 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)));
661 lock_AssertWrite(&buf_globalLock);
663 if (bp->flags & CM_BUF_INHASH) {
664 /* Remove from hash */
666 i = BUF_HASH(&bp->fid, &bp->offset);
667 lbpp = &(buf_hashTablepp[i]);
668 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
669 if (tbp == bp) break;
672 /* we better find it */
673 osi_assertx(tbp != NULL, "buf_GetNewLocked: hash table screwup");
675 *lbpp = bp->hashp; /* hash out */
677 /* Remove from file hash */
679 i = BUF_FILEHASH(&bp->fid);
680 prevBp = bp->fileHashBackp;
681 nextBp = bp->fileHashp;
683 prevBp->fileHashp = nextBp;
685 buf_fileHashTablepp[i] = nextBp;
687 nextBp->fileHashBackp = prevBp;
689 bp->flags &= ~CM_BUF_INHASH;
692 /* bump the soft reference counter now, to invalidate softRefs; no
693 * wakeup is required since people don't sleep waiting for this
698 /* make the fid unrecognizable */
699 memset(&bp->fid, 0, sizeof(bp->fid));
702 /* recycle a buffer, removing it from the free list, hashing in its new identity
703 * and returning it write-locked so that no one can use it. Called without
704 * any locks held, and can return an error if it loses the race condition and
705 * finds that someone else created the desired buffer.
707 * If success is returned, the buffer is returned write-locked.
709 * May be called with null scp and offsetp, if we're just trying to reclaim some
710 * space from the buffer pool. In that case, the buffer will be returned
711 * without being hashed into the hash table.
713 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
715 cm_buf_t *bp; /* buffer we're dealing with */
716 cm_buf_t *nextBp; /* next buffer in file hash chain */
720 cm_InitReq(&req); /* just in case */
724 lock_ObtainWrite(&buf_globalLock);
725 /* check to see if we lost the race */
727 if (bp = buf_LockedFind(scp, offsetp)) {
729 lock_ReleaseWrite(&buf_globalLock);
730 return CM_BUF_EXISTS;
734 /* for debugging, assert free list isn't empty, although we
735 * really should try waiting for a running tranasction to finish
736 * instead of this; or better, we should have a transaction
737 * throttler prevent us from entering this situation.
739 osi_assertx(buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
741 /* look at all buffers in free list, some of which may temp.
742 * have high refcounts and which then should be skipped,
743 * starting cleaning I/O for those which are dirty. If we find
744 * a clean buffer, we rehash it, lock it and return it.
746 for(bp = buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
747 /* check to see if it really has zero ref count. This
748 * code can bump refcounts, at least, so it may not be
751 if (bp->refCount > 0) continue;
753 /* we don't have to lock buffer itself, since the ref
754 * count is 0 and we know it will stay zero as long as
755 * we hold the global lock.
758 /* don't recycle someone in our own chunk */
759 if (!cm_FidCmp(&bp->fid, &scp->fid)
760 && (bp->offset.LowPart & (-cm_chunkSize))
761 == (offsetp->LowPart & (-cm_chunkSize)))
764 /* if this page is being filled (!) or cleaned, see if
765 * the I/O has completed. If not, skip it, otherwise
766 * do the final processing for the I/O.
768 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
769 /* probably shouldn't do this much work while
770 * holding the big lock? Watch for contention
776 if (bp->flags & CM_BUF_DIRTY) {
777 /* if the buffer is dirty, start cleaning it and
778 * move on to the next buffer. We do this with
779 * just the lock required to minimize contention
783 lock_ReleaseWrite(&buf_globalLock);
785 /* grab required lock and clean; this only
786 * starts the I/O. By the time we're back,
787 * it'll still be marked dirty, but it will also
788 * have the WRITING flag set, so we won't get
791 buf_CleanAsync(bp, &req);
793 /* now put it back and go around again */
798 /* if we get here, we know that the buffer still has a 0
799 * ref count, and that it is clean and has no currently
800 * pending I/O. This is the dude to return.
801 * Remember that as long as the ref count is 0, we know
802 * that we won't have any lock conflicts, so we can grab
803 * the buffer lock out of order in the locking hierarchy.
807 /* clean up junk flags */
808 bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
809 bp->dataVersion = -1; /* unknown so far */
811 /* now hash in as our new buffer, and give it the
812 * appropriate label, if requested.
815 bp->flags |= CM_BUF_INHASH;
817 bp->offset = *offsetp;
818 i = BUF_HASH(&scp->fid, offsetp);
819 bp->hashp = buf_hashTablepp[i];
820 buf_hashTablepp[i] = bp;
821 i = BUF_FILEHASH(&scp->fid);
822 nextBp = buf_fileHashTablepp[i];
823 bp->fileHashp = nextBp;
824 bp->fileHashBackp = NULL;
826 nextBp->fileHashBackp = bp;
827 buf_fileHashTablepp[i] = bp;
830 /* prepare to return it. Start by giving it a good
834 /* and since it has a non-zero ref count, we should move
835 * it from the lru queue. It better be still there,
836 * since we've held the global (big) lock since we found
839 osi_assertx(bp->flags & CM_BUF_INLRU,
840 "buf_GetNewLocked: LRU screwup");
841 if (buf_freeListEndp == bp) {
842 /* we're the last guy in this queue, so maintain it */
843 buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
845 osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
846 bp->flags &= ~CM_BUF_INLRU;
848 /* finally, grab the mutex so that people don't use it
849 * before the caller fills it with data. Again, no one
850 * should have been able to get to this dude to lock it.
852 osi_assertx(lock_TryMutex(&bp->mx),
853 "buf_GetNewLocked: TryMutex failed");
855 lock_ReleaseWrite(&buf_globalLock);
858 } /* for all buffers in lru queue */
859 lock_ReleaseWrite(&buf_globalLock);
860 } /* while loop over everything */
864 /* get a page, returning it held but unlocked. Doesn't fill in the page
865 * with I/O, since we're going to write the whole thing new.
867 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
871 osi_hyper_t pageOffset;
875 pageOffset.HighPart = offsetp->HighPart;
876 pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
878 lock_ObtainWrite(&buf_globalLock);
879 bp = buf_LockedFind(scp, &pageOffset);
880 lock_ReleaseWrite(&buf_globalLock);
882 /* lock it and break out */
883 lock_ObtainMutex(&bp->mx);
887 /* otherwise, we have to create a page */
888 code = buf_GetNewLocked(scp, &pageOffset, &bp);
890 /* check if the buffer was created in a race condition branch.
891 * If so, go around so we can hold a reference to it.
893 if (code == CM_BUF_EXISTS) continue;
895 /* something else went wrong */
896 if (code != 0) return code;
898 /* otherwise, we have a locked buffer that we just created */
901 } /* big while loop */
904 if (bp->flags & CM_BUF_READING)
907 /* once it has been read once, we can unlock it and return it, still
908 * with its refcount held.
910 lock_ReleaseMutex(&bp->mx);
912 osi_Log3(buf_logp, "buf_GetNew returning bp 0x%x for file 0x%x, offset 0x%x",
913 bp, (long) scp, offsetp->LowPart);
917 /* get a page, returning it held but unlocked. Make sure it is complete */
918 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
922 osi_hyper_t pageOffset;
923 unsigned long tcount;
927 #endif /* DISKCACHE95 */
930 pageOffset.HighPart = offsetp->HighPart;
931 pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
933 lock_ObtainWrite(&buf_globalLock);
934 bp = buf_LockedFind(scp, &pageOffset);
935 lock_ReleaseWrite(&buf_globalLock);
937 /* lock it and break out */
938 lock_ObtainMutex(&bp->mx);
942 /* touch disk chunk to update LRU info */
943 diskcache_Touch(bp->dcp);
944 #endif /* DISKCACHE95 */
947 /* otherwise, we have to create a page */
948 code = buf_GetNewLocked(scp, &pageOffset, &bp);
950 /* check if the buffer was created in a race condition branch.
951 * If so, go around so we can hold a reference to it.
953 if (code == CM_BUF_EXISTS) continue;
955 /* something else went wrong */
956 if (code != 0) return code;
958 /* otherwise, we have a locked buffer that we just created */
961 } /* big while loop */
963 /* if we get here, we have a locked buffer that may have just been
964 * created, in which case it needs to be filled with data.
967 /* load the page; freshly created pages should be idle */
968 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
970 /* setup offset, event */
971 #ifndef DJGPP /* doesn't seem to be used */
972 bp->over.Offset = bp->offset.LowPart;
973 bp->over.OffsetHigh = bp->offset.HighPart;
976 /* start the I/O; may drop lock */
977 bp->flags |= CM_BUF_READING;
978 code = (*cm_buf_opsp->Readp)(bp, buf_bufferSize, &tcount, NULL);
981 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, buf_bufferSize, &bp->dataVersion, &tcount, &dcp);
982 bp->dcp = dcp; /* pointer to disk cache struct. */
983 #endif /* DISKCACHE95 */
986 /* failure or queued */
987 #ifndef DJGPP /* cm_bufRead always returns 0 */
988 if (code != ERROR_IO_PENDING) {
991 bp->flags |= CM_BUF_ERROR;
992 bp->flags &= ~CM_BUF_READING;
993 if (bp->flags & CM_BUF_WAITING) {
994 bp->flags &= ~CM_BUF_WAITING;
995 osi_Wakeup((long) bp);
997 lock_ReleaseMutex(&bp->mx);
1004 /* otherwise, I/O completed instantly and we're done, except
1005 * for padding the xfr out with 0s and checking for EOF
1007 if (tcount < (unsigned long) buf_bufferSize) {
1008 memset(bp->datap+tcount, 0, buf_bufferSize - tcount);
1010 bp->flags |= CM_BUF_EOF;
1012 bp->flags &= ~CM_BUF_READING;
1013 if (bp->flags & CM_BUF_WAITING) {
1014 bp->flags &= ~CM_BUF_WAITING;
1015 osi_Wakeup((long) bp);
1021 /* wait for reads, either that which we started above, or that someone
1022 * else started. We don't care if we return a buffer being cleaned.
1024 if (bp->flags & CM_BUF_READING)
1027 /* once it has been read once, we can unlock it and return it, still
1028 * with its refcount held.
1030 lock_ReleaseMutex(&bp->mx);
1033 /* now remove from queue; will be put in at the head (farthest from
1034 * being recycled) when we're done in buf_Release.
1036 lock_ObtainWrite(&buf_globalLock);
1037 if (bp->flags & CM_BUF_INLRU) {
1038 if (buf_freeListEndp == bp)
1039 buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1040 osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
1041 bp->flags &= ~CM_BUF_INLRU;
1043 lock_ReleaseWrite(&buf_globalLock);
1045 osi_Log3(buf_logp, "buf_Get returning bp 0x%x for file 0x%x, offset 0x%x",
1046 bp, (long) scp, offsetp->LowPart);
1050 /* count # of elements in the free list;
1051 * we don't bother doing the proper locking for accessing dataVersion or flags
1052 * since it is a pain, and this is really just an advisory call. If you need
1053 * to do better at some point, rewrite this function.
1055 long buf_CountFreeList(void)
1061 lock_ObtainRead(&buf_globalLock);
1062 for(bufp = buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1063 /* if the buffer doesn't have an identity, or if the buffer
1064 * has been invalidate (by having its DV stomped upon), then
1065 * count it as free, since it isn't really being utilized.
1067 if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1070 lock_ReleaseRead(&buf_globalLock);
1074 /* clean a buffer synchronously */
1075 void buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1077 lock_ObtainMutex(&bp->mx);
1078 buf_LockedCleanAsync(bp, reqp);
1079 lock_ReleaseMutex(&bp->mx);
1082 /* wait for a buffer's cleaning to finish */
1083 void buf_CleanWait(cm_buf_t *bp)
1085 lock_ObtainMutex(&bp->mx);
1086 if (bp->flags & CM_BUF_WRITING) {
1089 lock_ReleaseMutex(&bp->mx);
1092 /* set the dirty flag on a buffer, and set associated write-ahead log,
1093 * if there is one. Allow one to be added to a buffer, but not changed.
1095 * The buffer must be locked before calling this routine.
1097 void buf_SetDirty(cm_buf_t *bp)
1099 osi_assert(bp->refCount > 0);
1101 osi_Log1(buf_logp, "buf_SetDirty 0x%x", bp);
1104 bp->flags |= CM_BUF_DIRTY;
1106 /* and turn off EOF flag, since it has associated data now */
1107 bp->flags &= ~CM_BUF_EOF;
1110 /* clean all buffers, reset log pointers and invalidate all buffers.
1111 * Called with no locks held, and returns with same.
1113 * This function is guaranteed to clean and remove the log ptr of all the
1114 * buffers that were dirty or had non-zero log ptrs before the call was
1115 * made. That's sufficient to clean up any garbage left around by recovery,
1116 * which is all we're counting on this for; there may be newly created buffers
1117 * added while we're running, but that should be OK.
1119 * In an environment where there are no transactions (artificially imposed, for
1120 * example, when switching the database to raw mode), this function is used to
1121 * make sure that all updates have been written to the disk. In that case, we don't
1122 * really require that we forget the log association between pages and logs, but
1123 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1124 * have to worry about invalidating data in the buffers.
1126 * This function is used at the end of recovery as paranoia to get the recovered
1127 * database out to disk. It removes all references to the recovery log and cleans
1130 long buf_CleanAndReset(void)
1136 lock_ObtainWrite(&buf_globalLock);
1137 for(i=0; i<buf_hashSize; i++) {
1138 for(bp = buf_hashTablepp[i]; bp; bp = bp->hashp) {
1140 lock_ReleaseWrite(&buf_globalLock);
1142 /* now no locks are held; clean buffer and go on */
1144 buf_CleanAsync(bp, &req);
1147 /* relock and release buffer */
1148 lock_ObtainWrite(&buf_globalLock);
1149 buf_LockedRelease(bp);
1150 } /* over one bucket */
1151 } /* for loop over all hash buckets */
1154 lock_ReleaseWrite(&buf_globalLock);
1156 /* and we're done */
1160 /* called without global lock being held, reserves buffers for callers
1161 * that need more than one held (not locked) at once.
1163 void buf_ReserveBuffers(long nbuffers)
1165 lock_ObtainWrite(&buf_globalLock);
1167 if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1168 buf_reserveWaiting = 1;
1169 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1170 osi_SleepW((long) &buf_reservedBufs, &buf_globalLock);
1171 lock_ObtainWrite(&buf_globalLock);
1174 buf_reservedBufs += nbuffers;
1178 lock_ReleaseWrite(&buf_globalLock);
1181 int buf_TryReserveBuffers(long nbuffers)
1185 lock_ObtainWrite(&buf_globalLock);
1186 if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1190 buf_reservedBufs += nbuffers;
1193 lock_ReleaseWrite(&buf_globalLock);
1197 /* called without global lock held, releases reservation held by
1198 * buf_ReserveBuffers.
1200 void buf_UnreserveBuffers(long nbuffers)
1202 lock_ObtainWrite(&buf_globalLock);
1203 buf_reservedBufs -= nbuffers;
1204 if (buf_reserveWaiting) {
1205 buf_reserveWaiting = 0;
1206 osi_Wakeup((long) &buf_reservedBufs);
1208 lock_ReleaseWrite(&buf_globalLock);
1211 /* truncate the buffers past sizep, zeroing out the page, if we don't
1212 * end on a page boundary.
1214 * Requires cm_bufCreateLock to be write locked.
1216 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1220 cm_buf_t *nbufp; /* next buffer, if didRelease */
1227 /* assert that cm_bufCreateLock is held in write mode */
1228 lock_AssertWrite(&scp->bufCreateLock);
1230 i = BUF_FILEHASH(&scp->fid);
1232 lock_ObtainWrite(&buf_globalLock);
1233 bufp = buf_fileHashTablepp[i];
1235 lock_ReleaseWrite(&buf_globalLock);
1240 lock_ReleaseWrite(&buf_globalLock);
1241 for(; bufp; bufp = nbufp) {
1243 lock_ObtainMutex(&bufp->mx);
1245 bufEnd.HighPart = 0;
1246 bufEnd.LowPart = buf_bufferSize;
1247 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1249 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1250 LargeIntegerLessThan(*sizep, bufEnd)) {
1253 lock_ObtainMutex(&scp->mx);
1255 /* make sure we have a callback (so we have the right value for
1256 * the length), and wait for it to be safe to do a truncate.
1258 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1259 CM_SCACHESYNC_NEEDCALLBACK
1260 | CM_SCACHESYNC_GETSTATUS
1261 | CM_SCACHESYNC_SETSIZE
1262 | CM_SCACHESYNC_BUFLOCKED);
1263 /* if we succeeded in our locking, and this applies to the right
1264 * file, and the truncate request overlaps the buffer either
1265 * totally or partially, then do something.
1267 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1268 && LargeIntegerLessThan(*sizep, bufEnd)) {
1270 lock_ObtainWrite(&buf_globalLock);
1272 /* destroy the buffer, turning off its dirty bit, if
1273 * we're truncating the whole buffer. Otherwise, set
1274 * the dirty bit, and clear out the tail of the buffer
1275 * if we just overlap some.
1277 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1278 /* truncating the entire page */
1279 bufp->flags &= ~CM_BUF_DIRTY;
1280 bufp->dataVersion = -1; /* known bad */
1281 bufp->dirtyCounter++;
1284 /* don't set dirty, since dirty implies
1285 * currently up-to-date. Don't need to do this,
1286 * since we'll update the length anyway.
1288 * Zero out remainder of the page, in case we
1289 * seek and write past EOF, and make this data
1292 bufferPos = sizep->LowPart & (buf_bufferSize - 1);
1293 osi_assert(bufferPos != 0);
1294 memset(bufp->datap + bufferPos, 0,
1295 buf_bufferSize - bufferPos);
1298 lock_ReleaseWrite(&buf_globalLock);
1302 lock_ReleaseMutex(&scp->mx);
1303 lock_ReleaseMutex(&bufp->mx);
1305 lock_ObtainWrite(&buf_globalLock);
1306 nbufp = bufp->fileHashp;
1307 if (nbufp) nbufp->refCount++;
1308 buf_LockedRelease(bufp);
1309 lock_ReleaseWrite(&buf_globalLock);
1312 /* bail out early if we fail */
1314 /* at this point, nbufp is held; bufp has already been
1317 if (nbufp) buf_Release(nbufp);
1326 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1329 cm_buf_t *bp; /* buffer we're hacking on */
1334 i = BUF_FILEHASH(&scp->fid);
1337 lock_ObtainWrite(&buf_globalLock);
1338 bp = buf_fileHashTablepp[i];
1339 if (bp) bp->refCount++;
1340 lock_ReleaseWrite(&buf_globalLock);
1341 for(; bp; bp = nbp) {
1342 didRelease = 0; /* haven't released this buffer yet */
1344 /* clean buffer synchronously */
1345 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1346 lock_ObtainMutex(&bp->mx);
1348 /* start cleaning the buffer, and wait for it to finish */
1349 buf_LockedCleanAsync(bp, reqp);
1351 lock_ReleaseMutex(&bp->mx);
1353 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1354 if (code) goto skip;
1356 lock_ObtainWrite(&buf_globalLock);
1357 /* actually, we only know that buffer is clean if ref
1358 * count is 1, since we don't have buffer itself locked.
1360 if (!(bp->flags & CM_BUF_DIRTY)) {
1361 if (bp->refCount == 1) { /* bp is held above */
1362 buf_LockedRelease(bp);
1363 nbp = bp->fileHashp;
1364 if (nbp) nbp->refCount++;
1369 lock_ReleaseWrite(&buf_globalLock);
1371 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1376 lock_ObtainWrite(&buf_globalLock);
1377 if (nbp = bp->fileHashp) nbp->refCount++;
1378 buf_LockedRelease(bp);
1379 lock_ReleaseWrite(&buf_globalLock);
1381 } /* for loop over a bunch of buffers */
1387 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1390 cm_buf_t *bp; /* buffer we're hacking on */
1391 cm_buf_t *nbp; /* next one */
1394 i = BUF_FILEHASH(&scp->fid);
1397 lock_ObtainWrite(&buf_globalLock);
1398 bp = buf_fileHashTablepp[i];
1399 if (bp) bp->refCount++;
1400 lock_ReleaseWrite(&buf_globalLock);
1401 for(; bp; bp = nbp) {
1402 /* clean buffer synchronously */
1403 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1406 lock_ObtainMutex(&bp->mx);
1408 cm_ReleaseUser(bp->userp);
1410 lock_ReleaseMutex(&bp->mx);
1412 buf_CleanAsync(bp, reqp);
1414 lock_ObtainMutex(&bp->mx);
1415 if (bp->flags & CM_BUF_ERROR) {
1416 if (code == 0 || code == -1) code = bp->error;
1417 if (code == 0) code = -1;
1419 lock_ReleaseMutex(&bp->mx);
1422 lock_ObtainWrite(&buf_globalLock);
1423 buf_LockedRelease(bp);
1424 nbp = bp->fileHashp;
1425 if (nbp) nbp->refCount++;
1426 lock_ReleaseWrite(&buf_globalLock);
1427 } /* for loop over a bunch of buffers */
1433 /* dump the contents of the buf_hashTablepp. */
1434 int cm_DumpBufHashTable(FILE *outputFile, char *cookie)
1441 if (buf_hashTablepp == NULL)
1444 lock_ObtainRead(&buf_globalLock);
1446 sprintf(output, "%s - dumping buf_HashTable - buf_hashSize=%d\n", cookie, buf_hashSize);
1447 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1449 for (i = 0; i < buf_hashSize; i++)
1451 for(bp = buf_hashTablepp[i]; bp; bp=bp->hashp)
1455 sprintf(output, "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d,"
1456 "vnode=%d, unique=%d), size=%d refCount=%d\n",
1457 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
1458 bp->fid.vnode, bp->fid.unique, bp->size, bp->refCount);
1459 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1464 sprintf(output, "%s - Done dumping buf_HashTable.\n", cookie);
1465 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1467 lock_ReleaseRead(&buf_globalLock);