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;
87 /* buffer reservation variables */
88 long buf_reservedBufs;
89 long buf_maxReservedBufs;
90 int buf_reserveWaiting;
92 /* callouts for reading and writing data, etc */
93 cm_buf_ops_t *cm_buf_opsp;
95 /* pointer to hash table; size computed dynamically */
96 cm_buf_t **buf_hashTablepp;
98 /* another hash table */
99 cm_buf_t **buf_fileHashTablepp;
102 /* for experimental disk caching support in Win95 client */
103 cm_buf_t *buf_diskFreeListp;
104 cm_buf_t *buf_diskFreeListEndp;
105 cm_buf_t *buf_diskAllp;
106 extern int cm_diskCacheEnabled;
107 #endif /* DISKCACHE95 */
109 /* hold a reference to an already held buffer */
110 void buf_Hold(cm_buf_t *bp)
112 lock_ObtainWrite(&buf_globalLock);
114 lock_ReleaseWrite(&buf_globalLock);
117 /* incremental sync daemon. Writes 1/10th of all the buffers every 5000 ms */
118 void buf_IncrSyncer(long parm)
120 cm_buf_t *bp; /* buffer we're hacking on; held */
121 long i; /* counter */
122 long nAtOnce; /* how many to do at once */
125 lock_ObtainWrite(&buf_globalLock);
128 lock_ReleaseWrite(&buf_globalLock);
129 nAtOnce = buf_nbuffers / 10;
132 i = SleepEx(5000, 1);
133 if (i != 0) continue;
138 /* now go through our percentage of the buffers */
139 for(i=0; i<nAtOnce; i++) {
140 /* don't want its identity changing while we're
141 * messing with it, so must do all of this with
145 /* start cleaning the buffer; don't touch log pages since
146 * the log code counts on knowing exactly who is writing
147 * a log page at any given instant.
150 req.flags |= CM_REQ_NORETRY;
151 buf_CleanAsync(bp, &req);
153 /* now advance to the next buffer; the allp chain never changes,
154 * and so can be followed even when holding no locks.
156 lock_ObtainWrite(&buf_globalLock);
157 buf_LockedRelease(bp);
159 if (!bp) bp = buf_allp;
161 lock_ReleaseWrite(&buf_globalLock);
162 } /* for loop over a bunch of buffers */
163 } /* whole daemon's while loop */
167 /* Create a security attribute structure suitable for use when the cache file
168 * is created. What we mainly want is that only the administrator should be
169 * able to do anything with the file. We create an ACL with only one entry,
170 * an entry that grants all rights to the administrator.
172 PSECURITY_ATTRIBUTES CreateCacheFileSA()
174 PSECURITY_ATTRIBUTES psa;
175 PSECURITY_DESCRIPTOR psd;
176 SID_IDENTIFIER_AUTHORITY authority = SECURITY_NT_AUTHORITY;
178 DWORD AdminSIDlength;
182 /* Get Administrator SID */
183 AllocateAndInitializeSid(&authority, 2,
184 SECURITY_BUILTIN_DOMAIN_RID,
185 DOMAIN_ALIAS_RID_ADMINS,
189 /* Create Administrator-only ACL */
190 AdminSIDlength = GetLengthSid(AdminSID);
191 ACLlength = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE)
192 + AdminSIDlength - sizeof(DWORD);
193 AdminOnlyACL = GlobalAlloc(GMEM_FIXED, ACLlength);
194 InitializeAcl(AdminOnlyACL, ACLlength, ACL_REVISION);
195 AddAccessAllowedAce(AdminOnlyACL, ACL_REVISION,
196 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL,
199 /* Create security descriptor */
200 psd = GlobalAlloc(GMEM_FIXED, sizeof(SECURITY_DESCRIPTOR));
201 InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION);
202 SetSecurityDescriptorDacl(psd, TRUE, AdminOnlyACL, FALSE);
204 /* Create security attributes structure */
205 psa = GlobalAlloc(GMEM_FIXED, sizeof(SECURITY_ATTRIBUTES));
206 psa->nLength = sizeof(SECURITY_ATTRIBUTES);
207 psa->lpSecurityDescriptor = psd;
208 psa->bInheritHandle = TRUE;
215 /* Free a security attribute structure created by CreateCacheFileSA() */
216 VOID FreeCacheFileSA(PSECURITY_ATTRIBUTES psa)
221 GetSecurityDescriptorDacl(psa->lpSecurityDescriptor, &b1, &pAcl, &b2);
223 GlobalFree(psa->lpSecurityDescriptor);
228 /* initialize the buffer package; called with no locks
229 * held during the initialization phase.
231 long buf_Init(cm_buf_ops_t *opsp)
233 static osi_once_t once;
239 PSECURITY_ATTRIBUTES psa;
247 /* Get system info; all we really want is the allocation granularity */
248 GetSystemInfo(&sysInfo);
251 /* Have to be able to reserve a whole chunk */
252 if (((buf_nbuffers - 3) * buf_bufferSize) < cm_chunkSize)
253 return CM_ERROR_TOOFEWBUFS;
255 /* recall for callouts */
258 if (osi_Once(&once)) {
259 /* initialize global locks */
260 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock");
264 * Cache file mapping constrained by
265 * system allocation granularity;
266 * round up, assuming granularity is a power of two
268 cs = buf_nbuffers * buf_bufferSize;
269 cs = (cs + (sysInfo.dwAllocationGranularity - 1))
270 & ~(sysInfo.dwAllocationGranularity - 1);
271 if (cs != buf_nbuffers * buf_bufferSize) {
272 buf_nbuffers = cs / buf_bufferSize;
273 afsi_log("Cache size rounded up to %d buffers",
278 /* remember this for those who want to reset it */
279 buf_nOrigBuffers = buf_nbuffers;
281 /* lower hash size to a prime number */
282 buf_hashSize = osi_PrimeLessThan(buf_hashSize);
284 /* create hash table */
285 buf_hashTablepp = malloc(buf_hashSize * sizeof(cm_buf_t *));
286 memset((void *)buf_hashTablepp, 0,
287 buf_hashSize * sizeof(cm_buf_t *));
289 /* another hash table */
290 buf_fileHashTablepp = malloc(buf_hashSize * sizeof(cm_buf_t *));
291 memset((void *)buf_fileHashTablepp, 0,
292 buf_hashSize * sizeof(cm_buf_t *));
294 /* min value for which this works */
298 /* Reserve buffer space by mapping cache file */
299 psa = CreateCacheFileSA();
300 hf = CreateFile(cm_CachePath,
301 GENERIC_READ | GENERIC_WRITE,
302 FILE_SHARE_READ | FILE_SHARE_WRITE,
305 FILE_ATTRIBUTE_NORMAL,
307 if (hf == INVALID_HANDLE_VALUE) {
308 afsi_log("create file error %d", GetLastError());
309 return CM_ERROR_INVAL;
311 FreeCacheFileSA(psa);
313 hm = CreateFileMapping(hf,
316 0, buf_nbuffers * buf_bufferSize,
319 if (GetLastError() == ERROR_DISK_FULL) {
320 afsi_log("Error creating cache file mapping: disk full");
321 return CM_ERROR_TOOMANYBUFS;
323 return CM_ERROR_INVAL;
325 data = MapViewOfFile(hm,
328 buf_nbuffers * buf_bufferSize);
332 return CM_ERROR_INVAL;
336 /* djgpp doesn't support memory mapped files */
337 data = malloc(buf_nbuffers * buf_bufferSize);
340 /* create buffer headers and put in free list */
341 bp = malloc(buf_nbuffers * sizeof(cm_buf_t));
343 for(i=0; i<buf_nbuffers; i++) {
344 /* allocate and zero some storage */
345 memset(bp, 0, sizeof(cm_buf_t));
347 /* thread on list of all buffers */
351 osi_QAdd((osi_queue_t **)&buf_freeListp, &bp->q);
352 bp->flags |= CM_BUF_INLRU;
353 lock_InitializeMutex(&bp->mx, "Buffer mutex");
355 /* grab appropriate number of bytes from aligned zone */
358 /* setup last buffer pointer */
360 buf_freeListEndp = bp;
364 data += buf_bufferSize;
367 /* none reserved at first */
368 buf_reservedBufs = 0;
370 /* just for safety's sake */
371 buf_maxReservedBufs = buf_nbuffers - 3;
373 /* init the buffer trace log */
374 buf_logp = osi_LogCreate("buffer", 10);
378 /* and create the incr-syncer */
379 phandle = thrd_Create(0, 0,
380 (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
383 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
385 CloseHandle(phandle);
392 /* add nbuffers to the buffer pool, if possible.
393 * Called with no locks held.
395 long buf_AddBuffers(long nbuffers)
404 afsi_log("%d buffers being added to the existing cache of size %d",
405 nbuffers, buf_nbuffers);
408 * Cache file mapping constrained by
409 * system allocation granularity;
410 * round up, assuming granularity is a power of two;
411 * assume existing cache size is already rounded
413 cs = nbuffers * buf_bufferSize;
414 cs = (cs + (sysInfo.dwAllocationGranularity - 1))
415 & ~(sysInfo.dwAllocationGranularity - 1);
416 if (cs != nbuffers * buf_bufferSize) {
417 nbuffers = cs / buf_bufferSize;
420 /* Reserve additional buffer space by remapping cache file */
421 hm = CreateFileMapping(CacheHandle,
424 0, (buf_nbuffers + nbuffers) * buf_bufferSize,
427 if (GetLastError() == ERROR_DISK_FULL)
428 return CM_ERROR_TOOMANYBUFS;
430 return CM_ERROR_INVAL;
432 data = MapViewOfFile(hm,
434 0, buf_nbuffers * buf_bufferSize,
435 nbuffers * buf_bufferSize);
438 return CM_ERROR_INVAL;
442 data = malloc(buf_nbuffers * buf_bufferSize);
445 /* Create buffer headers and put in free list */
446 bp = malloc(nbuffers * sizeof(*bp));
448 for(i=0; i<nbuffers; i++) {
449 memset(bp, 0, sizeof(*bp));
451 lock_InitializeMutex(&bp->mx, "cm_buf_t");
453 /* grab appropriate number of bytes from aligned zone */
456 bp->flags |= CM_BUF_INLRU;
458 lock_ObtainWrite(&buf_globalLock);
459 /* note that buf_allp chain is covered by buf_globalLock now */
462 osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
463 if (!buf_freeListEndp) buf_freeListEndp = bp;
465 lock_ReleaseWrite(&buf_globalLock);
468 data += buf_bufferSize;
470 } /* for loop over all buffers */
475 /* interface to set the number of buffers to an exact figure.
476 * Called with no locks held.
478 long buf_SetNBuffers(long nbuffers)
480 if (nbuffers < 10) return CM_ERROR_INVAL;
481 if (nbuffers == buf_nbuffers) return 0;
482 else if (nbuffers > buf_nbuffers)
483 return buf_AddBuffers(nbuffers - buf_nbuffers);
484 else return CM_ERROR_INVAL;
487 /* release a buffer. Buffer must be referenced, but unlocked. */
488 void buf_Release(cm_buf_t *bp)
490 lock_ObtainWrite(&buf_globalLock);
491 buf_LockedRelease(bp);
492 lock_ReleaseWrite(&buf_globalLock);
495 /* wait for reading or writing to clear; called with write-locked
496 * buffer, and returns with locked buffer.
498 void buf_WaitIO(cm_buf_t *bp)
501 /* if no IO is happening, we're done */
502 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
505 /* otherwise I/O is happening, but some other thread is waiting for
506 * the I/O already. Wait for that guy to figure out what happened,
507 * and then check again.
509 bp->flags |= CM_BUF_WAITING;
510 osi_SleepM((long) bp, &bp->mx);
511 lock_ObtainMutex(&bp->mx);
512 osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%x", bp);
515 /* if we get here, the IO is done, but we may have to wakeup people waiting for
516 * the I/O to complete. Do so.
518 if (bp->flags & CM_BUF_WAITING) {
519 bp->flags &= ~CM_BUF_WAITING;
520 osi_Wakeup((long) bp);
522 osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%x", (long) bp);
525 /* code to drop reference count while holding buf_globalLock */
526 void buf_LockedRelease(cm_buf_t *bp)
528 /* ensure that we're in the LRU queue if our ref count is 0 */
529 osi_assert(bp->refCount > 0);
530 if (--bp->refCount == 0) {
531 if (!(bp->flags & CM_BUF_INLRU)) {
532 osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
534 /* watch for transition from empty to one element */
535 if (!buf_freeListEndp)
536 buf_freeListEndp = buf_freeListp;
537 bp->flags |= CM_BUF_INLRU;
542 /* find a buffer, if any, for a particular file ID and offset. Assumes
543 * that buf_globalLock is write locked when called.
545 cm_buf_t *buf_LockedFind(struct cm_scache *scp, osi_hyper_t *offsetp)
550 i = BUF_HASH(&scp->fid, offsetp);
551 for(bp = buf_hashTablepp[i]; bp; bp=bp->hashp) {
552 if (cm_FidCmp(&scp->fid, &bp->fid) == 0
553 && offsetp->LowPart == bp->offset.LowPart
554 && offsetp->HighPart == bp->offset.HighPart) {
560 /* return whatever we found, if anything */
564 /* find a buffer with offset *offsetp for vnode *scp. Called
565 * with no locks held.
567 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
571 lock_ObtainWrite(&buf_globalLock);
572 bp = buf_LockedFind(scp, offsetp);
573 lock_ReleaseWrite(&buf_globalLock);
578 /* start cleaning I/O on this buffer. Buffer must be write locked, and is returned
581 * Makes sure that there's only one person writing this block
582 * at any given time, and also ensures that the log is forced sufficiently far,
583 * if this buffer contains logged data.
585 void buf_LockedCleanAsync(cm_buf_t *bp, cm_req_t *reqp)
590 while ((bp->flags & (CM_BUF_WRITING | CM_BUF_DIRTY)) == CM_BUF_DIRTY) {
591 lock_ReleaseMutex(&bp->mx);
593 code = (*cm_buf_opsp->Writep)(&bp->fid, &bp->offset,
594 buf_bufferSize, 0, bp->userp,
597 lock_ObtainMutex(&bp->mx);
601 /* Disk cache support */
602 /* write buffer to disk cache (synchronous for now) */
603 diskcache_Update(bp->dcp, bp->datap, buf_bufferSize, bp->dataVersion);
604 #endif /* DISKCACHE95 */
607 /* do logging after call to GetLastError, or else */
608 osi_Log2(buf_logp, "buf_CleanAsync starts I/O on 0x%x, done=%d", bp, code);
610 /* if someone was waiting for the I/O that just completed or failed,
613 if (bp->flags & CM_BUF_WAITING) {
614 /* turn off flags and wakeup users */
615 bp->flags &= ~CM_BUF_WAITING;
616 osi_Wakeup((long) bp);
620 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
621 * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
622 * The buffer must already be clean, and no I/O should be happening to it.
624 void buf_Recycle(cm_buf_t *bp)
629 cm_buf_t *prevBp, *nextBp;
631 /* if we get here, we know that the buffer still has a 0 ref count,
632 * and that it is clean and has no currently pending I/O. This is
633 * the dude to return.
634 * Remember that as long as the ref count is 0, we know that we won't
635 * have any lock conflicts, so we can grab the buffer lock out of
636 * order in the locking hierarchy.
639 "buf_Recycle recycles 0x%x, off 0x%x",
640 bp, bp->offset.LowPart);
642 osi_assert(bp->refCount == 0);
643 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)));
644 lock_AssertWrite(&buf_globalLock);
646 if (bp->flags & CM_BUF_INHASH) {
647 /* Remove from hash */
649 i = BUF_HASH(&bp->fid, &bp->offset);
650 lbpp = &(buf_hashTablepp[i]);
651 for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
652 if (tbp == bp) break;
655 /* we better find it */
656 osi_assertx(tbp != NULL, "buf_GetNewLocked: hash table screwup");
658 *lbpp = bp->hashp; /* hash out */
660 /* Remove from file hash */
662 i = BUF_FILEHASH(&bp->fid);
663 prevBp = bp->fileHashBackp;
664 nextBp = bp->fileHashp;
666 prevBp->fileHashp = nextBp;
668 buf_fileHashTablepp[i] = nextBp;
670 nextBp->fileHashBackp = prevBp;
672 bp->flags &= ~CM_BUF_INHASH;
675 /* bump the soft reference counter now, to invalidate softRefs; no
676 * wakeup is required since people don't sleep waiting for this
681 /* make the fid unrecognizable */
682 memset(&bp->fid, 0, sizeof(bp->fid));
685 /* recycle a buffer, removing it from the free list, hashing in its new identity
686 * and returning it write-locked so that no one can use it. Called without
687 * any locks held, and can return an error if it loses the race condition and
688 * finds that someone else created the desired buffer.
690 * If success is returned, the buffer is returned write-locked.
692 * May be called with null scp and offsetp, if we're just trying to reclaim some
693 * space from the buffer pool. In that case, the buffer will be returned
694 * without being hashed into the hash table.
696 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
698 cm_buf_t *bp; /* buffer we're dealing with */
699 cm_buf_t *nextBp; /* next buffer in file hash chain */
703 cm_InitReq(&req); /* just in case */
707 lock_ObtainWrite(&buf_globalLock);
708 /* check to see if we lost the race */
710 if (bp = buf_LockedFind(scp, offsetp)) {
712 lock_ReleaseWrite(&buf_globalLock);
713 return CM_BUF_EXISTS;
717 /* for debugging, assert free list isn't empty, although we
718 * really should try waiting for a running tranasction to finish
719 * instead of this; or better, we should have a transaction
720 * throttler prevent us from entering this situation.
722 osi_assertx(buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
724 /* look at all buffers in free list, some of which may temp.
725 * have high refcounts and which then should be skipped,
726 * starting cleaning I/O for those which are dirty. If we find
727 * a clean buffer, we rehash it, lock it and return it.
729 for(bp = buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
730 /* check to see if it really has zero ref count. This
731 * code can bump refcounts, at least, so it may not be
734 if (bp->refCount > 0) continue;
736 /* we don't have to lock buffer itself, since the ref
737 * count is 0 and we know it will stay zero as long as
738 * we hold the global lock.
741 /* don't recycle someone in our own chunk */
742 if (!cm_FidCmp(&bp->fid, &scp->fid)
743 && (bp->offset.LowPart & (-cm_chunkSize))
744 == (offsetp->LowPart & (-cm_chunkSize)))
747 /* if this page is being filled (!) or cleaned, see if
748 * the I/O has completed. If not, skip it, otherwise
749 * do the final processing for the I/O.
751 if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
752 /* probably shouldn't do this much work while
753 * holding the big lock? Watch for contention
759 if (bp->flags & CM_BUF_DIRTY) {
760 /* if the buffer is dirty, start cleaning it and
761 * move on to the next buffer. We do this with
762 * just the lock required to minimize contention
766 lock_ReleaseWrite(&buf_globalLock);
768 /* grab required lock and clean; this only
769 * starts the I/O. By the time we're back,
770 * it'll still be marked dirty, but it will also
771 * have the WRITING flag set, so we won't get
774 buf_CleanAsync(bp, &req);
776 /* now put it back and go around again */
781 /* if we get here, we know that the buffer still has a 0
782 * ref count, and that it is clean and has no currently
783 * pending I/O. This is the dude to return.
784 * Remember that as long as the ref count is 0, we know
785 * that we won't have any lock conflicts, so we can grab
786 * the buffer lock out of order in the locking hierarchy.
790 /* clean up junk flags */
791 bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
792 bp->dataVersion = -1; /* unknown so far */
794 /* now hash in as our new buffer, and give it the
795 * appropriate label, if requested.
798 bp->flags |= CM_BUF_INHASH;
800 bp->offset = *offsetp;
801 i = BUF_HASH(&scp->fid, offsetp);
802 bp->hashp = buf_hashTablepp[i];
803 buf_hashTablepp[i] = bp;
804 i = BUF_FILEHASH(&scp->fid);
805 nextBp = buf_fileHashTablepp[i];
806 bp->fileHashp = nextBp;
807 bp->fileHashBackp = NULL;
809 nextBp->fileHashBackp = bp;
810 buf_fileHashTablepp[i] = bp;
813 /* prepare to return it. Start by giving it a good
817 /* and since it has a non-zero ref count, we should move
818 * it from the lru queue. It better be still there,
819 * since we've held the global (big) lock since we found
822 osi_assertx(bp->flags & CM_BUF_INLRU,
823 "buf_GetNewLocked: LRU screwup");
824 if (buf_freeListEndp == bp) {
825 /* we're the last guy in this queue, so maintain it */
826 buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
828 osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
829 bp->flags &= ~CM_BUF_INLRU;
831 /* finally, grab the mutex so that people don't use it
832 * before the caller fills it with data. Again, no one
833 * should have been able to get to this dude to lock it.
835 osi_assertx(lock_TryMutex(&bp->mx),
836 "buf_GetNewLocked: TryMutex failed");
838 lock_ReleaseWrite(&buf_globalLock);
841 } /* for all buffers in lru queue */
842 lock_ReleaseWrite(&buf_globalLock);
843 } /* while loop over everything */
847 /* get a page, returning it held but unlocked. Doesn't fill in the page
848 * with I/O, since we're going to write the whole thing new.
850 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
854 osi_hyper_t pageOffset;
858 pageOffset.HighPart = offsetp->HighPart;
859 pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
861 lock_ObtainWrite(&buf_globalLock);
862 bp = buf_LockedFind(scp, &pageOffset);
863 lock_ReleaseWrite(&buf_globalLock);
865 /* lock it and break out */
866 lock_ObtainMutex(&bp->mx);
870 /* otherwise, we have to create a page */
871 code = buf_GetNewLocked(scp, &pageOffset, &bp);
873 /* check if the buffer was created in a race condition branch.
874 * If so, go around so we can hold a reference to it.
876 if (code == CM_BUF_EXISTS) continue;
878 /* something else went wrong */
879 if (code != 0) return code;
881 /* otherwise, we have a locked buffer that we just created */
884 } /* big while loop */
887 if (bp->flags & CM_BUF_READING)
890 /* once it has been read once, we can unlock it and return it, still
891 * with its refcount held.
893 lock_ReleaseMutex(&bp->mx);
895 osi_Log3(buf_logp, "buf_GetNew returning bp 0x%x for file 0x%x, offset 0x%x",
896 bp, (long) scp, offsetp->LowPart);
900 /* get a page, returning it held but unlocked. Make sure it is complete */
901 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
905 osi_hyper_t pageOffset;
906 unsigned long tcount;
910 #endif /* DISKCACHE95 */
913 pageOffset.HighPart = offsetp->HighPart;
914 pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
916 lock_ObtainWrite(&buf_globalLock);
917 bp = buf_LockedFind(scp, &pageOffset);
918 lock_ReleaseWrite(&buf_globalLock);
920 /* lock it and break out */
921 lock_ObtainMutex(&bp->mx);
925 /* touch disk chunk to update LRU info */
926 diskcache_Touch(bp->dcp);
927 #endif /* DISKCACHE95 */
930 /* otherwise, we have to create a page */
931 code = buf_GetNewLocked(scp, &pageOffset, &bp);
933 /* check if the buffer was created in a race condition branch.
934 * If so, go around so we can hold a reference to it.
936 if (code == CM_BUF_EXISTS) continue;
938 /* something else went wrong */
939 if (code != 0) return code;
941 /* otherwise, we have a locked buffer that we just created */
944 } /* big while loop */
946 /* if we get here, we have a locked buffer that may have just been
947 * created, in which case it needs to be filled with data.
950 /* load the page; freshly created pages should be idle */
951 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
953 /* setup offset, event */
954 #ifndef DJGPP /* doesn't seem to be used */
955 bp->over.Offset = bp->offset.LowPart;
956 bp->over.OffsetHigh = bp->offset.HighPart;
959 /* start the I/O; may drop lock */
960 bp->flags |= CM_BUF_READING;
961 code = (*cm_buf_opsp->Readp)(bp, buf_bufferSize, &tcount, NULL);
964 code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, buf_bufferSize, &bp->dataVersion, &tcount, &dcp);
965 bp->dcp = dcp; /* pointer to disk cache struct. */
966 #endif /* DISKCACHE95 */
969 /* failure or queued */
970 #ifndef DJGPP /* cm_bufRead always returns 0 */
971 if (code != ERROR_IO_PENDING) {
974 bp->flags |= CM_BUF_ERROR;
975 bp->flags &= ~CM_BUF_READING;
976 if (bp->flags & CM_BUF_WAITING) {
977 bp->flags &= ~CM_BUF_WAITING;
978 osi_Wakeup((long) bp);
980 lock_ReleaseMutex(&bp->mx);
987 /* otherwise, I/O completed instantly and we're done, except
988 * for padding the xfr out with 0s and checking for EOF
990 if (tcount < (unsigned long) buf_bufferSize) {
991 memset(bp->datap+tcount, 0, buf_bufferSize - tcount);
993 bp->flags |= CM_BUF_EOF;
995 bp->flags &= ~CM_BUF_READING;
996 if (bp->flags & CM_BUF_WAITING) {
997 bp->flags &= ~CM_BUF_WAITING;
998 osi_Wakeup((long) bp);
1004 /* wait for reads, either that which we started above, or that someone
1005 * else started. We don't care if we return a buffer being cleaned.
1007 if (bp->flags & CM_BUF_READING)
1010 /* once it has been read once, we can unlock it and return it, still
1011 * with its refcount held.
1013 lock_ReleaseMutex(&bp->mx);
1016 /* now remove from queue; will be put in at the head (farthest from
1017 * being recycled) when we're done in buf_Release.
1019 lock_ObtainWrite(&buf_globalLock);
1020 if (bp->flags & CM_BUF_INLRU) {
1021 if (buf_freeListEndp == bp)
1022 buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1023 osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
1024 bp->flags &= ~CM_BUF_INLRU;
1026 lock_ReleaseWrite(&buf_globalLock);
1028 osi_Log3(buf_logp, "buf_Get returning bp 0x%x for file 0x%x, offset 0x%x",
1029 bp, (long) scp, offsetp->LowPart);
1033 /* count # of elements in the free list;
1034 * we don't bother doing the proper locking for accessing dataVersion or flags
1035 * since it is a pain, and this is really just an advisory call. If you need
1036 * to do better at some point, rewrite this function.
1038 long buf_CountFreeList(void)
1044 lock_ObtainRead(&buf_globalLock);
1045 for(bufp = buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1046 /* if the buffer doesn't have an identity, or if the buffer
1047 * has been invalidate (by having its DV stomped upon), then
1048 * count it as free, since it isn't really being utilized.
1050 if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1053 lock_ReleaseRead(&buf_globalLock);
1057 /* clean a buffer synchronously */
1058 void buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1060 lock_ObtainMutex(&bp->mx);
1061 buf_LockedCleanAsync(bp, reqp);
1062 lock_ReleaseMutex(&bp->mx);
1065 /* wait for a buffer's cleaning to finish */
1066 void buf_CleanWait(cm_buf_t *bp)
1068 lock_ObtainMutex(&bp->mx);
1069 if (bp->flags & CM_BUF_WRITING) {
1072 lock_ReleaseMutex(&bp->mx);
1075 /* set the dirty flag on a buffer, and set associated write-ahead log,
1076 * if there is one. Allow one to be added to a buffer, but not changed.
1078 * The buffer must be locked before calling this routine.
1080 void buf_SetDirty(cm_buf_t *bp)
1082 osi_assert(bp->refCount > 0);
1084 osi_Log1(buf_logp, "buf_SetDirty 0x%x", bp);
1087 bp->flags |= CM_BUF_DIRTY;
1089 /* and turn off EOF flag, since it has associated data now */
1090 bp->flags &= ~CM_BUF_EOF;
1093 /* clean all buffers, reset log pointers and invalidate all buffers.
1094 * Called with no locks held, and returns with same.
1096 * This function is guaranteed to clean and remove the log ptr of all the
1097 * buffers that were dirty or had non-zero log ptrs before the call was
1098 * made. That's sufficient to clean up any garbage left around by recovery,
1099 * which is all we're counting on this for; there may be newly created buffers
1100 * added while we're running, but that should be OK.
1102 * In an environment where there are no transactions (artificially imposed, for
1103 * example, when switching the database to raw mode), this function is used to
1104 * make sure that all updates have been written to the disk. In that case, we don't
1105 * really require that we forget the log association between pages and logs, but
1106 * it also doesn't hurt. Since raw mode I/O goes through this buffer package, we don't
1107 * have to worry about invalidating data in the buffers.
1109 * This function is used at the end of recovery as paranoia to get the recovered
1110 * database out to disk. It removes all references to the recovery log and cleans
1113 long buf_CleanAndReset(void)
1119 lock_ObtainWrite(&buf_globalLock);
1120 for(i=0; i<buf_hashSize; i++) {
1121 for(bp = buf_hashTablepp[i]; bp; bp = bp->hashp) {
1123 lock_ReleaseWrite(&buf_globalLock);
1125 /* now no locks are held; clean buffer and go on */
1127 buf_CleanAsync(bp, &req);
1130 /* relock and release buffer */
1131 lock_ObtainWrite(&buf_globalLock);
1132 buf_LockedRelease(bp);
1133 } /* over one bucket */
1134 } /* for loop over all hash buckets */
1137 lock_ReleaseWrite(&buf_globalLock);
1139 /* and we're done */
1143 /* called without global lock being held, reserves buffers for callers
1144 * that need more than one held (not locked) at once.
1146 void buf_ReserveBuffers(long nbuffers)
1148 lock_ObtainWrite(&buf_globalLock);
1150 if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1151 buf_reserveWaiting = 1;
1152 osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1153 osi_SleepW((long) &buf_reservedBufs, &buf_globalLock);
1154 lock_ObtainWrite(&buf_globalLock);
1157 buf_reservedBufs += nbuffers;
1161 lock_ReleaseWrite(&buf_globalLock);
1164 int buf_TryReserveBuffers(long nbuffers)
1168 lock_ObtainWrite(&buf_globalLock);
1169 if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1173 buf_reservedBufs += nbuffers;
1176 lock_ReleaseWrite(&buf_globalLock);
1180 /* called without global lock held, releases reservation held by
1181 * buf_ReserveBuffers.
1183 void buf_UnreserveBuffers(long nbuffers)
1185 lock_ObtainWrite(&buf_globalLock);
1186 buf_reservedBufs -= nbuffers;
1187 if (buf_reserveWaiting) {
1188 buf_reserveWaiting = 0;
1189 osi_Wakeup((long) &buf_reservedBufs);
1191 lock_ReleaseWrite(&buf_globalLock);
1194 /* truncate the buffers past sizep, zeroing out the page, if we don't
1195 * end on a page boundary.
1197 * Requires cm_bufCreateLock to be write locked.
1199 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1203 cm_buf_t *nbufp; /* next buffer, if didRelease */
1210 /* assert that cm_bufCreateLock is held in write mode */
1211 lock_AssertWrite(&scp->bufCreateLock);
1213 i = BUF_FILEHASH(&scp->fid);
1215 lock_ObtainWrite(&buf_globalLock);
1216 bufp = buf_fileHashTablepp[i];
1218 lock_ReleaseWrite(&buf_globalLock);
1223 lock_ReleaseWrite(&buf_globalLock);
1224 for(; bufp; bufp = nbufp) {
1226 lock_ObtainMutex(&bufp->mx);
1228 bufEnd.HighPart = 0;
1229 bufEnd.LowPart = buf_bufferSize;
1230 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1232 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1233 LargeIntegerLessThan(*sizep, bufEnd)) {
1236 lock_ObtainMutex(&scp->mx);
1238 /* make sure we have a callback (so we have the right value for
1239 * the length), and wait for it to be safe to do a truncate.
1241 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1242 CM_SCACHESYNC_NEEDCALLBACK
1243 | CM_SCACHESYNC_GETSTATUS
1244 | CM_SCACHESYNC_SETSIZE
1245 | CM_SCACHESYNC_BUFLOCKED);
1246 /* if we succeeded in our locking, and this applies to the right
1247 * file, and the truncate request overlaps the buffer either
1248 * totally or partially, then do something.
1250 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1251 && LargeIntegerLessThan(*sizep, bufEnd)) {
1253 lock_ObtainWrite(&buf_globalLock);
1255 /* destroy the buffer, turning off its dirty bit, if
1256 * we're truncating the whole buffer. Otherwise, set
1257 * the dirty bit, and clear out the tail of the buffer
1258 * if we just overlap some.
1260 if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1261 /* truncating the entire page */
1262 bufp->flags &= ~CM_BUF_DIRTY;
1263 bufp->dataVersion = -1; /* known bad */
1264 bufp->dirtyCounter++;
1267 /* don't set dirty, since dirty implies
1268 * currently up-to-date. Don't need to do this,
1269 * since we'll update the length anyway.
1271 * Zero out remainder of the page, in case we
1272 * seek and write past EOF, and make this data
1275 bufferPos = sizep->LowPart & (buf_bufferSize - 1);
1276 osi_assert(bufferPos != 0);
1277 memset(bufp->datap + bufferPos, 0,
1278 buf_bufferSize - bufferPos);
1281 lock_ReleaseWrite(&buf_globalLock);
1285 lock_ReleaseMutex(&scp->mx);
1286 lock_ReleaseMutex(&bufp->mx);
1288 lock_ObtainWrite(&buf_globalLock);
1289 nbufp = bufp->fileHashp;
1290 if (nbufp) nbufp->refCount++;
1291 buf_LockedRelease(bufp);
1292 lock_ReleaseWrite(&buf_globalLock);
1295 /* bail out early if we fail */
1297 /* at this point, nbufp is held; bufp has already been
1300 if (nbufp) buf_Release(nbufp);
1309 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1312 cm_buf_t *bp; /* buffer we're hacking on */
1317 i = BUF_FILEHASH(&scp->fid);
1320 lock_ObtainWrite(&buf_globalLock);
1321 bp = buf_fileHashTablepp[i];
1322 if (bp) bp->refCount++;
1323 lock_ReleaseWrite(&buf_globalLock);
1324 for(; bp; bp = nbp) {
1325 didRelease = 0; /* haven't released this buffer yet */
1327 /* clean buffer synchronously */
1328 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1329 lock_ObtainMutex(&bp->mx);
1331 /* start cleaning the buffer, and wait for it to finish */
1332 buf_LockedCleanAsync(bp, reqp);
1334 lock_ReleaseMutex(&bp->mx);
1336 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1337 if (code) goto skip;
1339 lock_ObtainWrite(&buf_globalLock);
1340 /* actually, we only know that buffer is clean if ref
1341 * count is 1, since we don't have buffer itself locked.
1343 if (!(bp->flags & CM_BUF_DIRTY)) {
1344 if (bp->refCount == 1) { /* bp is held above */
1345 buf_LockedRelease(bp);
1346 nbp = bp->fileHashp;
1347 if (nbp) nbp->refCount++;
1352 lock_ReleaseWrite(&buf_globalLock);
1354 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1359 lock_ObtainWrite(&buf_globalLock);
1360 if (nbp = bp->fileHashp) nbp->refCount++;
1361 buf_LockedRelease(bp);
1362 lock_ReleaseWrite(&buf_globalLock);
1364 } /* for loop over a bunch of buffers */
1370 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1373 cm_buf_t *bp; /* buffer we're hacking on */
1374 cm_buf_t *nbp; /* next one */
1377 i = BUF_FILEHASH(&scp->fid);
1380 lock_ObtainWrite(&buf_globalLock);
1381 bp = buf_fileHashTablepp[i];
1382 if (bp) bp->refCount++;
1383 lock_ReleaseWrite(&buf_globalLock);
1384 for(; bp; bp = nbp) {
1385 /* clean buffer synchronously */
1386 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1389 lock_ObtainMutex(&bp->mx);
1391 cm_ReleaseUser(bp->userp);
1393 lock_ReleaseMutex(&bp->mx);
1395 buf_CleanAsync(bp, reqp);
1397 lock_ObtainMutex(&bp->mx);
1398 if (bp->flags & CM_BUF_ERROR) {
1399 if (code == 0 || code == -1) code = bp->error;
1400 if (code == 0) code = -1;
1402 lock_ReleaseMutex(&bp->mx);
1405 lock_ObtainWrite(&buf_globalLock);
1406 buf_LockedRelease(bp);
1407 nbp = bp->fileHashp;
1408 if (nbp) nbp->refCount++;
1409 lock_ReleaseWrite(&buf_globalLock);
1410 } /* for loop over a bunch of buffers */
1416 /* dump the contents of the buf_hashTablepp. */
1417 int cm_DumpBufHashTable(FILE *outputFile, char *cookie)
1424 if (buf_hashTablepp == NULL)
1427 lock_ObtainRead(&buf_globalLock);
1429 sprintf(output, "%s - dumping buf_HashTable - buf_hashSize=%d\n", cookie, buf_hashSize);
1430 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1432 for (i = 0; i < buf_hashSize; i++)
1434 for(bp = buf_hashTablepp[i]; bp; bp=bp->hashp)
1438 sprintf(output, "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d,"
1439 "vnode=%d, unique=%d), size=%d refCount=%d\n",
1440 cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
1441 bp->fid.vnode, bp->fid.unique, bp->size, bp->refCount);
1442 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1447 sprintf(output, "%s - Done dumping buf_HashTable.\n", cookie);
1448 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1450 lock_ReleaseRead(&buf_globalLock);