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("Error creating cache file \"%s\" error %d",
311 cm_CachePath, GetLastError());
312 return CM_ERROR_INVAL;
314 FreeCacheFileSA(psa);
315 } else { /* buf_cacheType == CM_BUF_CACHETYPE_VIRTUAL */
316 hf = INVALID_HANDLE_VALUE;
319 hm = CreateFileMapping(hf,
322 0, buf_nbuffers * buf_bufferSize,
325 if (GetLastError() == ERROR_DISK_FULL) {
326 afsi_log("Error creating cache file \"%s\" mapping: disk full",
328 return CM_ERROR_TOOMANYBUFS;
330 return CM_ERROR_INVAL;
332 data = MapViewOfFile(hm,
335 buf_nbuffers * buf_bufferSize);
337 if (hf != INVALID_HANDLE_VALUE)
340 return CM_ERROR_INVAL;
344 /* djgpp doesn't support memory mapped files */
345 data = malloc(buf_nbuffers * buf_bufferSize);
348 /* create buffer headers and put in free list */
349 bp = malloc(buf_nbuffers * sizeof(cm_buf_t));
351 for(i=0; i<buf_nbuffers; i++) {
352 /* allocate and zero some storage */
353 memset(bp, 0, sizeof(cm_buf_t));
355 /* thread on list of all buffers */
359 osi_QAdd((osi_queue_t **)&buf_freeListp, &bp->q);
360 bp->flags |= CM_BUF_INLRU;
361 lock_InitializeMutex(&bp->mx, "Buffer mutex");
363 /* grab appropriate number of bytes from aligned zone */
366 /* setup last buffer pointer */
368 buf_freeListEndp = bp;
372 data += buf_bufferSize;
375 /* none reserved at first */
376 buf_reservedBufs = 0;
378 /* just for safety's sake */
379 buf_maxReservedBufs = buf_nbuffers - 3;
381 /* init the buffer trace log */
382 buf_logp = osi_LogCreate("buffer", 10);
386 /* and create the incr-syncer */
387 phandle = thrd_Create(0, 0,
388 (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
391 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
393 CloseHandle(phandle);
400 /* add nbuffers to the buffer pool, if possible.
401 * Called with no locks held.
403 long buf_AddBuffers(long nbuffers)
412 afsi_log("%d buffers being added to the existing cache of size %d",
413 nbuffers, buf_nbuffers);
415 if (buf_cacheType == CM_BUF_CACHETYPE_VIRTUAL) {
416 /* The size of a virtual cache cannot be changed after it has
417 * been created. Subsequent calls to MapViewofFile() with
418 * an existing mapping object name would not allow the
419 * object to be resized. Return failure immediately.
421 return CM_ERROR_INVAL;
425 * Cache file mapping constrained by
426 * system allocation granularity;
427 * round up, assuming granularity is a power of two;
428 * assume existing cache size is already rounded
430 cs = nbuffers * buf_bufferSize;
431 cs = (cs + (sysInfo.dwAllocationGranularity - 1))
432 & ~(sysInfo.dwAllocationGranularity - 1);
433 if (cs != nbuffers * buf_bufferSize) {
434 nbuffers = cs / buf_bufferSize;
437 /* Reserve additional buffer space by remapping cache file */
438 hm = CreateFileMapping(CacheHandle,
441 0, (buf_nbuffers + nbuffers) * buf_bufferSize,
444 if (GetLastError() == ERROR_DISK_FULL)
445 return CM_ERROR_TOOMANYBUFS;
447 return CM_ERROR_INVAL;
449 data = MapViewOfFile(hm,
451 0, buf_nbuffers * buf_bufferSize,
452 nbuffers * buf_bufferSize);
455 return CM_ERROR_INVAL;
459 data = malloc(buf_nbuffers * buf_bufferSize);
462 /* Create buffer headers and put in free list */
463 bp = malloc(nbuffers * sizeof(*bp));
465 for(i=0; i<nbuffers; i++) {
466 memset(bp, 0, sizeof(*bp));
468 lock_InitializeMutex(&bp->mx, "cm_buf_t");
470 /* grab appropriate number of bytes from aligned zone */
473 bp->flags |= CM_BUF_INLRU;
475 lock_ObtainWrite(&buf_globalLock);
476 /* note that buf_allp chain is covered by buf_globalLock now */
479 osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
480 if (!buf_freeListEndp) buf_freeListEndp = bp;
482 lock_ReleaseWrite(&buf_globalLock);
485 data += buf_bufferSize;
487 } /* for loop over all buffers */
492 /* interface to set the number of buffers to an exact figure.
493 * Called with no locks held.
495 long buf_SetNBuffers(long nbuffers)
498 return CM_ERROR_INVAL;
499 if (nbuffers == buf_nbuffers)
501 else if (nbuffers > buf_nbuffers)
502 return buf_AddBuffers(nbuffers - buf_nbuffers);
504 return CM_ERROR_INVAL;
507 /* release a buffer. Buffer must be referenced, but unlocked. */
508 void buf_Release(cm_buf_t *bp)
510 lock_ObtainWrite(&buf_globalLock);
511 buf_LockedRelease(bp);
512 lock_ReleaseWrite(&buf_globalLock);
515 /* wait for reading or writing to clear; called with write-locked
516 * buffer, and returns with locked buffer.
518 void buf_WaitIO(cm_buf_t *bp)
521 /* if no IO is happening, we're done */
522 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
525 /* otherwise I/O is happening, but some other thread is waiting for
526 * the I/O already. Wait for that guy to figure out what happened,
527 * and then check again.
529 if ( bp->flags & CM_BUF_WAITING )
530 osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%x", bp);
532 bp->flags |= CM_BUF_WAITING;
533 osi_SleepM((long) bp, &bp->mx);
534 lock_ObtainMutex(&bp->mx);
535 osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%x", bp);
538 /* if we get here, the IO is done, but we may have to wakeup people waiting for
539 * the I/O to complete. Do so.
541 if (bp->flags & CM_BUF_WAITING) {
542 bp->flags &= ~CM_BUF_WAITING;
543 osi_Wakeup((long) bp);
545 osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%x", (long) bp);
548 /* code to drop reference count while holding buf_globalLock */
549 void buf_LockedRelease(cm_buf_t *bp)
551 /* ensure that we're in the LRU queue if our ref count is 0 */
552 osi_assert(bp->refCount > 0);
553 if (--bp->refCount == 0) {
554 if (!(bp->flags & CM_BUF_INLRU)) {
555 osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
557 /* watch for transition from empty to one element */
558 if (!buf_freeListEndp)
559 buf_freeListEndp = buf_freeListp;
560 bp->flags |= CM_BUF_INLRU;
565 /* find a buffer, if any, for a particular file ID and offset. Assumes
566 * that buf_globalLock is write locked when called.
568 cm_buf_t *buf_LockedFind(struct cm_scache *scp, osi_hyper_t *offsetp)
573 i = BUF_HASH(&scp->fid, offsetp);
574 for(bp = buf_hashTablepp[i]; bp; bp=bp->hashp) {
575 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
576 && offsetp->LowPart == bp->offset.LowPart
577 && offsetp->HighPart == bp->offset.HighPart) {
583 /* return whatever we found, if anything */
587 /* find a buffer with offset *offsetp for vnode *scp. Called
588 * with no locks held.
590 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
594 lock_ObtainWrite(&buf_globalLock);
595 bp = buf_LockedFind(scp, offsetp);
596 lock_ReleaseWrite(&buf_globalLock);
601 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
604 * Makes sure that there's only one person writing this block
605 * at any given time, and also ensures that the log is forced sufficiently far,
606 * if this buffer contains logged data.
608 void buf_LockedCleanAsync(cm_buf_t *bp, cm_req_t *reqp)
613 while ((bp->flags & (CM_BUF_WRITING | CM_BUF_DIRTY)) == CM_BUF_DIRTY) {
614 lock_ReleaseMutex(&bp->mx);
616 code = (*cm_buf_opsp->Writep)(&bp->fid, &bp->offset,
617 buf_bufferSize, 0, bp->userp,
620 lock_ObtainMutex(&bp->mx);
625 /* Disk cache support */
626 /* write buffer to disk cache (synchronous for now) */
627 diskcache_Update(bp->dcp, bp->datap, buf_bufferSize, bp->dataVersion);
628 #endif /* DISKCACHE95 */
631 /* do logging after call to GetLastError, or else */
632 osi_Log2(buf_logp, "buf_CleanAsync starts I/O on 0x%x, done=%d", bp, code);
634 /* if someone was waiting for the I/O that just completed or failed,
637 if (bp->flags & CM_BUF_WAITING) {
638 /* turn off flags and wakeup users */
639 bp->flags &= ~CM_BUF_WAITING;
640 osi_Wakeup((long) bp);
644 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
645 * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
646 * The buffer must already be clean, and no I/O should be happening to it.
648 void buf_Recycle(cm_buf_t *bp)
653 cm_buf_t *prevBp, *nextBp;
655 /* if we get here, we know that the buffer still has a 0 ref count,
656 * and that it is clean and has no currently pending I/O. This is
657 * the dude to return.
658 * Remember that as long as the ref count is 0, we know that we won't
659 * have any lock conflicts, so we can grab the buffer lock out of
660 * order in the locking hierarchy.
662 osi_Log2( buf_logp, "buf_Recycle recycles 0x%x, off 0x%x",
663 bp, bp->offset.LowPart);
665 osi_assert(bp->refCount == 0);
666 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)));
667 lock_AssertWrite(&buf_globalLock);
669 if (bp->flags & CM_BUF_INHASH) {
670 /* Remove from hash */
672 i = BUF_HASH(&bp->fid, &bp->offset);
673 lbpp = &(buf_hashTablepp[i]);
674 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
675 if (tbp == bp) break;
678 /* we better find it */
679 osi_assertx(tbp != NULL, "buf_GetNewLocked: hash table screwup");
681 *lbpp = bp->hashp; /* hash out */
683 /* Remove from file hash */
685 i = BUF_FILEHASH(&bp->fid);
686 prevBp = bp->fileHashBackp;
687 nextBp = bp->fileHashp;
689 prevBp->fileHashp = nextBp;
691 buf_fileHashTablepp[i] = nextBp;
693 nextBp->fileHashBackp = prevBp;
695 bp->flags &= ~CM_BUF_INHASH;
698 /* bump the soft reference counter now, to invalidate softRefs; no
699 * wakeup is required since people don't sleep waiting for this
704 /* make the fid unrecognizable */
705 memset(&bp->fid, 0, sizeof(bp->fid));
708 /* recycle a buffer, removing it from the free list, hashing in its new identity
709 * and returning it write-locked so that no one can use it. Called without
710 * any locks held, and can return an error if it loses the race condition and
711 * finds that someone else created the desired buffer.
713 * If success is returned, the buffer is returned write-locked.
715 * May be called with null scp and offsetp, if we're just trying to reclaim some
716 * space from the buffer pool. In that case, the buffer will be returned
717 * without being hashed into the hash table.
719 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
721 cm_buf_t *bp; /* buffer we're dealing with */
722 cm_buf_t *nextBp; /* next buffer in file hash chain */
726 cm_InitReq(&req); /* just in case */
730 lock_ObtainWrite(&buf_globalLock);
731 /* check to see if we lost the race */
733 if (bp = buf_LockedFind(scp, offsetp)) {
735 lock_ReleaseWrite(&buf_globalLock);
736 return CM_BUF_EXISTS;
740 /* for debugging, assert free list isn't empty, although we
741 * really should try waiting for a running tranasction to finish
742 * instead of this; or better, we should have a transaction
743 * throttler prevent us from entering this situation.
745 osi_assertx(buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
747 /* look at all buffers in free list, some of which may temp.
748 * have high refcounts and which then should be skipped,
749 * starting cleaning I/O for those which are dirty. If we find
750 * a clean buffer, we rehash it, lock it and return it.
752 for(bp = buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
753 /* check to see if it really has zero ref count. This
754 * code can bump refcounts, at least, so it may not be
757 if (bp->refCount > 0)
760 /* we don't have to lock buffer itself, since the ref
761 * count is 0 and we know it will stay zero as long as
762 * we hold the global lock.
765 /* don't recycle someone in our own chunk */
766 if (!cm_FidCmp(&bp->fid, &scp->fid)
767 && (bp->offset.LowPart & (-cm_chunkSize))
768 == (offsetp->LowPart & (-cm_chunkSize)))
771 /* if this page is being filled (!) or cleaned, see if
772 * the I/O has completed. If not, skip it, otherwise
773 * do the final processing for the I/O.
775 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
776 /* probably shouldn't do this much work while
777 * holding the big lock? Watch for contention
783 if (bp->flags & CM_BUF_DIRTY) {
784 /* if the buffer is dirty, start cleaning it and
785 * move on to the next buffer. We do this with
786 * just the lock required to minimize contention
790 lock_ReleaseWrite(&buf_globalLock);
792 /* grab required lock and clean; this only
793 * starts the I/O. By the time we're back,
794 * it'll still be marked dirty, but it will also
795 * have the WRITING flag set, so we won't get
798 buf_CleanAsync(bp, &req);
800 /* now put it back and go around again */
805 /* if we get here, we know that the buffer still has a 0
806 * ref count, and that it is clean and has no currently
807 * pending I/O. This is the dude to return.
808 * Remember that as long as the ref count is 0, we know
809 * that we won't have any lock conflicts, so we can grab
810 * the buffer lock out of order in the locking hierarchy.
814 /* clean up junk flags */
815 bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
816 bp->dataVersion = -1; /* unknown so far */
818 /* now hash in as our new buffer, and give it the
819 * appropriate label, if requested.
822 bp->flags |= CM_BUF_INHASH;
824 bp->offset = *offsetp;
825 i = BUF_HASH(&scp->fid, offsetp);
826 bp->hashp = buf_hashTablepp[i];
827 buf_hashTablepp[i] = bp;
828 i = BUF_FILEHASH(&scp->fid);
829 nextBp = buf_fileHashTablepp[i];
830 bp->fileHashp = nextBp;
831 bp->fileHashBackp = NULL;
833 nextBp->fileHashBackp = bp;
834 buf_fileHashTablepp[i] = bp;
837 /* prepare to return it. Start by giving it a good
841 /* and since it has a non-zero ref count, we should move
842 * it from the lru queue. It better be still there,
843 * since we've held the global (big) lock since we found
846 osi_assertx(bp->flags & CM_BUF_INLRU,
847 "buf_GetNewLocked: LRU screwup");
848 if (buf_freeListEndp == bp) {
849 /* we're the last guy in this queue, so maintain it */
850 buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
852 osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
853 bp->flags &= ~CM_BUF_INLRU;
855 /* finally, grab the mutex so that people don't use it
856 * before the caller fills it with data. Again, no one
857 * should have been able to get to this dude to lock it.
859 osi_assertx(lock_TryMutex(&bp->mx),
860 "buf_GetNewLocked: TryMutex failed");
862 lock_ReleaseWrite(&buf_globalLock);
865 } /* for all buffers in lru queue */
866 lock_ReleaseWrite(&buf_globalLock);
867 } /* while loop over everything */
871 /* get a page, returning it held but unlocked. Doesn't fill in the page
872 * with I/O, since we're going to write the whole thing new.
874 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
878 osi_hyper_t pageOffset;
882 pageOffset.HighPart = offsetp->HighPart;
883 pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
885 lock_ObtainWrite(&buf_globalLock);
886 bp = buf_LockedFind(scp, &pageOffset);
887 lock_ReleaseWrite(&buf_globalLock);
889 /* lock it and break out */
890 lock_ObtainMutex(&bp->mx);
894 /* otherwise, we have to create a page */
895 code = buf_GetNewLocked(scp, &pageOffset, &bp);
897 /* check if the buffer was created in a race condition branch.
898 * If so, go around so we can hold a reference to it.
900 if (code == CM_BUF_EXISTS)
903 /* something else went wrong */
907 /* otherwise, we have a locked buffer that we just created */
910 } /* big while loop */
913 if (bp->flags & CM_BUF_READING)
916 /* once it has been read once, we can unlock it and return it, still
917 * with its refcount held.
919 lock_ReleaseMutex(&bp->mx);
921 osi_Log3(buf_logp, "buf_GetNew returning bp 0x%x for file 0x%x, offset 0x%x",
922 bp, (long) scp, offsetp->LowPart);
926 /* get a page, returning it held but unlocked. Make sure it is complete */
927 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
931 osi_hyper_t pageOffset;
932 unsigned long tcount;
936 #endif /* DISKCACHE95 */
939 pageOffset.HighPart = offsetp->HighPart;
940 pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
942 lock_ObtainWrite(&buf_globalLock);
943 bp = buf_LockedFind(scp, &pageOffset);
944 lock_ReleaseWrite(&buf_globalLock);
946 /* lock it and break out */
947 lock_ObtainMutex(&bp->mx);
951 /* touch disk chunk to update LRU info */
952 diskcache_Touch(bp->dcp);
953 #endif /* DISKCACHE95 */
956 /* otherwise, we have to create a page */
957 code = buf_GetNewLocked(scp, &pageOffset, &bp);
959 /* check if the buffer was created in a race condition branch.
960 * If so, go around so we can hold a reference to it.
962 if (code == CM_BUF_EXISTS)
965 /* something else went wrong */
969 /* otherwise, we have a locked buffer that we just created */
972 } /* big while loop */
974 /* if we get here, we have a locked buffer that may have just been
975 * created, in which case it needs to be filled with data.
978 /* load the page; freshly created pages should be idle */
979 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
981 /* setup offset, event */
982 #ifndef DJGPP /* doesn't seem to be used */
983 bp->over.Offset = bp->offset.LowPart;
984 bp->over.OffsetHigh = bp->offset.HighPart;
987 /* start the I/O; may drop lock */
988 bp->flags |= CM_BUF_READING;
989 code = (*cm_buf_opsp->Readp)(bp, buf_bufferSize, &tcount, NULL);
992 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, buf_bufferSize, &bp->dataVersion, &tcount, &dcp);
993 bp->dcp = dcp; /* pointer to disk cache struct. */
994 #endif /* DISKCACHE95 */
997 /* failure or queued */
998 #ifndef DJGPP /* cm_bufRead always returns 0 */
999 if (code != ERROR_IO_PENDING) {
1002 bp->flags |= CM_BUF_ERROR;
1003 bp->flags &= ~CM_BUF_READING;
1004 if (bp->flags & CM_BUF_WAITING) {
1005 bp->flags &= ~CM_BUF_WAITING;
1006 osi_Wakeup((long) bp);
1008 lock_ReleaseMutex(&bp->mx);
1015 /* otherwise, I/O completed instantly and we're done, except
1016 * for padding the xfr out with 0s and checking for EOF
1018 if (tcount < (unsigned long) buf_bufferSize) {
1019 memset(bp->datap+tcount, 0, buf_bufferSize - tcount);
1021 bp->flags |= CM_BUF_EOF;
1023 bp->flags &= ~CM_BUF_READING;
1024 if (bp->flags & CM_BUF_WAITING) {
1025 bp->flags &= ~CM_BUF_WAITING;
1026 osi_Wakeup((long) bp);
1032 /* wait for reads, either that which we started above, or that someone
1033 * else started. We don't care if we return a buffer being cleaned.
1035 if (bp->flags & CM_BUF_READING)
1038 /* once it has been read once, we can unlock it and return it, still
1039 * with its refcount held.
1041 lock_ReleaseMutex(&bp->mx);
1044 /* now remove from queue; will be put in at the head (farthest from
1045 * being recycled) when we're done in buf_Release.
1047 lock_ObtainWrite(&buf_globalLock);
1048 if (bp->flags & CM_BUF_INLRU) {
1049 if (buf_freeListEndp == bp)
1050 buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1051 osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
1052 bp->flags &= ~CM_BUF_INLRU;
1054 lock_ReleaseWrite(&buf_globalLock);
1056 osi_Log3(buf_logp, "buf_Get returning bp 0x%x for file 0x%x, offset 0x%x",
1057 bp, (long) scp, offsetp->LowPart);
1061 /* count # of elements in the free list;
1062 * we don't bother doing the proper locking for accessing dataVersion or flags
1063 * since it is a pain, and this is really just an advisory call. If you need
1064 * to do better at some point, rewrite this function.
1066 long buf_CountFreeList(void)
1072 lock_ObtainRead(&buf_globalLock);
1073 for(bufp = buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1074 /* if the buffer doesn't have an identity, or if the buffer
1075 * has been invalidate (by having its DV stomped upon), then
1076 * count it as free, since it isn't really being utilized.
1078 if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1081 lock_ReleaseRead(&buf_globalLock);
1085 /* clean a buffer synchronously */
1086 void buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1088 lock_ObtainMutex(&bp->mx);
1089 buf_LockedCleanAsync(bp, reqp);
1090 lock_ReleaseMutex(&bp->mx);
1093 /* wait for a buffer's cleaning to finish */
1094 void buf_CleanWait(cm_buf_t *bp)
1096 lock_ObtainMutex(&bp->mx);
1097 if (bp->flags & CM_BUF_WRITING) {
1100 lock_ReleaseMutex(&bp->mx);
1103 /* set the dirty flag on a buffer, and set associated write-ahead log,
1104 * if there is one. Allow one to be added to a buffer, but not changed.
1106 * The buffer must be locked before calling this routine.
1108 void buf_SetDirty(cm_buf_t *bp)
1110 osi_assert(bp->refCount > 0);
1112 osi_Log1(buf_logp, "buf_SetDirty 0x%x", bp);
1115 bp->flags |= CM_BUF_DIRTY;
1117 /* and turn off EOF flag, since it has associated data now */
1118 bp->flags &= ~CM_BUF_EOF;
1121 /* clean all buffers, reset log pointers and invalidate all buffers.
1122 * Called with no locks held, and returns with same.
1124 * This function is guaranteed to clean and remove the log ptr of all the
1125 * buffers that were dirty or had non-zero log ptrs before the call was
1126 * made. That's sufficient to clean up any garbage left around by recovery,
1127 * which is all we're counting on this for; there may be newly created buffers
1128 * added while we're running, but that should be OK.
1130 * In an environment where there are no transactions (artificially imposed, for
1131 * example, when switching the database to raw mode), this function is used to
1132 * make sure that all updates have been written to the disk. In that case, we don't
1133 * really require that we forget the log association between pages and logs, but
1134 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1135 * have to worry about invalidating data in the buffers.
1137 * This function is used at the end of recovery as paranoia to get the recovered
1138 * database out to disk. It removes all references to the recovery log and cleans
1141 long buf_CleanAndReset(void)
1147 lock_ObtainWrite(&buf_globalLock);
1148 for(i=0; i<buf_hashSize; i++) {
1149 for(bp = buf_hashTablepp[i]; bp; bp = bp->hashp) {
1151 lock_ReleaseWrite(&buf_globalLock);
1153 /* now no locks are held; clean buffer and go on */
1155 buf_CleanAsync(bp, &req);
1158 /* relock and release buffer */
1159 lock_ObtainWrite(&buf_globalLock);
1160 buf_LockedRelease(bp);
1161 } /* over one bucket */
1162 } /* for loop over all hash buckets */
1165 lock_ReleaseWrite(&buf_globalLock);
1167 /* and we're done */
1171 /* called without global lock being held, reserves buffers for callers
1172 * that need more than one held (not locked) at once.
1174 void buf_ReserveBuffers(long nbuffers)
1176 lock_ObtainWrite(&buf_globalLock);
1178 if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1179 buf_reserveWaiting = 1;
1180 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1181 osi_SleepW((long) &buf_reservedBufs, &buf_globalLock);
1182 lock_ObtainWrite(&buf_globalLock);
1185 buf_reservedBufs += nbuffers;
1189 lock_ReleaseWrite(&buf_globalLock);
1192 int buf_TryReserveBuffers(long nbuffers)
1196 lock_ObtainWrite(&buf_globalLock);
1197 if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1201 buf_reservedBufs += nbuffers;
1204 lock_ReleaseWrite(&buf_globalLock);
1208 /* called without global lock held, releases reservation held by
1209 * buf_ReserveBuffers.
1211 void buf_UnreserveBuffers(long nbuffers)
1213 lock_ObtainWrite(&buf_globalLock);
1214 buf_reservedBufs -= nbuffers;
1215 if (buf_reserveWaiting) {
1216 buf_reserveWaiting = 0;
1217 osi_Wakeup((long) &buf_reservedBufs);
1219 lock_ReleaseWrite(&buf_globalLock);
1222 /* truncate the buffers past sizep, zeroing out the page, if we don't
1223 * end on a page boundary.
1225 * Requires cm_bufCreateLock to be write locked.
1227 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1231 cm_buf_t *nbufp; /* next buffer, if didRelease */
1238 /* assert that cm_bufCreateLock is held in write mode */
1239 lock_AssertWrite(&scp->bufCreateLock);
1241 i = BUF_FILEHASH(&scp->fid);
1243 lock_ObtainWrite(&buf_globalLock);
1244 bufp = buf_fileHashTablepp[i];
1246 lock_ReleaseWrite(&buf_globalLock);
1251 lock_ReleaseWrite(&buf_globalLock);
1252 for(; bufp; bufp = nbufp) {
1254 lock_ObtainMutex(&bufp->mx);
1256 bufEnd.HighPart = 0;
1257 bufEnd.LowPart = buf_bufferSize;
1258 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1260 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1261 LargeIntegerLessThan(*sizep, bufEnd)) {
1264 lock_ObtainMutex(&scp->mx);
1266 /* make sure we have a callback (so we have the right value for
1267 * the length), and wait for it to be safe to do a truncate.
1269 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1270 CM_SCACHESYNC_NEEDCALLBACK
1271 | CM_SCACHESYNC_GETSTATUS
1272 | CM_SCACHESYNC_SETSIZE
1273 | CM_SCACHESYNC_BUFLOCKED);
1274 /* if we succeeded in our locking, and this applies to the right
1275 * file, and the truncate request overlaps the buffer either
1276 * totally or partially, then do something.
1278 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1279 && LargeIntegerLessThan(*sizep, bufEnd)) {
1281 lock_ObtainWrite(&buf_globalLock);
1283 /* destroy the buffer, turning off its dirty bit, if
1284 * we're truncating the whole buffer. Otherwise, set
1285 * the dirty bit, and clear out the tail of the buffer
1286 * if we just overlap some.
1288 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1289 /* truncating the entire page */
1290 bufp->flags &= ~CM_BUF_DIRTY;
1291 bufp->dataVersion = -1; /* known bad */
1292 bufp->dirtyCounter++;
1295 /* don't set dirty, since dirty implies
1296 * currently up-to-date. Don't need to do this,
1297 * since we'll update the length anyway.
1299 * Zero out remainder of the page, in case we
1300 * seek and write past EOF, and make this data
1303 bufferPos = sizep->LowPart & (buf_bufferSize - 1);
1304 osi_assert(bufferPos != 0);
1305 memset(bufp->datap + bufferPos, 0,
1306 buf_bufferSize - bufferPos);
1309 lock_ReleaseWrite(&buf_globalLock);
1312 lock_ReleaseMutex(&scp->mx);
1313 lock_ReleaseMutex(&bufp->mx);
1315 lock_ObtainWrite(&buf_globalLock);
1316 nbufp = bufp->fileHashp;
1317 if (nbufp) nbufp->refCount++;
1318 buf_LockedRelease(bufp);
1319 lock_ReleaseWrite(&buf_globalLock);
1322 /* bail out early if we fail */
1324 /* at this point, nbufp is held; bufp has already been
1337 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1340 cm_buf_t *bp; /* buffer we're hacking on */
1345 i = BUF_FILEHASH(&scp->fid);
1348 lock_ObtainWrite(&buf_globalLock);
1349 bp = buf_fileHashTablepp[i];
1350 if (bp) bp->refCount++;
1351 lock_ReleaseWrite(&buf_globalLock);
1352 for(; bp; bp = nbp) {
1353 didRelease = 0; /* haven't released this buffer yet */
1355 /* clean buffer synchronously */
1356 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1357 lock_ObtainMutex(&bp->mx);
1359 /* start cleaning the buffer, and wait for it to finish */
1360 buf_LockedCleanAsync(bp, reqp);
1362 lock_ReleaseMutex(&bp->mx);
1364 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1365 if (code) goto skip;
1367 lock_ObtainWrite(&buf_globalLock);
1368 /* actually, we only know that buffer is clean if ref
1369 * count is 1, since we don't have buffer itself locked.
1371 if (!(bp->flags & CM_BUF_DIRTY)) {
1372 if (bp->refCount == 1) { /* bp is held above */
1373 buf_LockedRelease(bp);
1374 nbp = bp->fileHashp;
1375 if (nbp) nbp->refCount++;
1380 lock_ReleaseWrite(&buf_globalLock);
1382 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1387 lock_ObtainWrite(&buf_globalLock);
1388 if (nbp = bp->fileHashp) nbp->refCount++;
1389 buf_LockedRelease(bp);
1390 lock_ReleaseWrite(&buf_globalLock);
1392 } /* for loop over a bunch of buffers */
1398 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1401 cm_buf_t *bp; /* buffer we're hacking on */
1402 cm_buf_t *nbp; /* next one */
1405 i = BUF_FILEHASH(&scp->fid);
1408 lock_ObtainWrite(&buf_globalLock);
1409 bp = buf_fileHashTablepp[i];
1410 if (bp) bp->refCount++;
1411 lock_ReleaseWrite(&buf_globalLock);
1412 for(; bp; bp = nbp) {
1413 /* clean buffer synchronously */
1414 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1417 lock_ObtainMutex(&bp->mx);
1419 cm_ReleaseUser(bp->userp);
1421 lock_ReleaseMutex(&bp->mx);
1423 buf_CleanAsync(bp, reqp);
1425 lock_ObtainMutex(&bp->mx);
1426 if (bp->flags & CM_BUF_ERROR) {
1427 if (code == 0 || code == -1)
1432 lock_ReleaseMutex(&bp->mx);
1435 lock_ObtainWrite(&buf_globalLock);
1436 buf_LockedRelease(bp);
1437 nbp = bp->fileHashp;
1438 if (nbp) nbp->refCount++;
1439 lock_ReleaseWrite(&buf_globalLock);
1440 } /* for loop over a bunch of buffers */
1446 /* dump the contents of the buf_hashTablepp. */
1447 int cm_DumpBufHashTable(FILE *outputFile, char *cookie)
1454 if (buf_hashTablepp == NULL)
1457 lock_ObtainRead(&buf_globalLock);
1459 sprintf(output, "%s - dumping buf_HashTable - buf_hashSize=%d\n", cookie, buf_hashSize);
1460 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1462 for (i = 0; i < buf_hashSize; i++)
1464 for(bp = buf_hashTablepp[i]; bp; bp=bp->hashp)
1468 sprintf(output, "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d,"
1469 "vnode=%d, unique=%d), size=%d refCount=%d\n",
1470 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
1471 bp->fid.vnode, bp->fid.unique, bp->size, bp->refCount);
1472 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1477 sprintf(output, "%s - Done dumping buf_HashTable.\n", cookie);
1478 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1480 lock_ReleaseRead(&buf_globalLock);