virtual-cache-file-20040729
[openafs.git] / src / WINNT / afsd / cm_buf.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
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
8  */
9
10 /* Copyright (C) 1994 Cazamar Systems, Inc. */
11
12 #include <afs/param.h>
13 #include <afs/stds.h>
14
15 #ifndef DJGPP
16 #include <windows.h>
17 #endif
18 #include <osi.h>
19 #include <malloc.h>
20 #include <stdio.h>
21 #include <assert.h>
22
23 #include "afsd.h"
24
25 extern void afsi_log(char *pattern, ...);
26
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.
30  *
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.
33  *
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.
38  *
39  * The mutexes in the buffer structures protect the remaining fields in the
40  * buffers, as well the data itself.
41  * 
42  * The locking hierarchy here is this:
43  * 
44  * - resv multiple simul. buffers reservation
45  * - lock buffer I/O flags
46  * - lock buffer's mutex
47  * - lock buf_globalLock
48  *
49  */
50
51 /* global debugging log */
52 osi_log_t *buf_logp = NULL;
53
54 /* Global lock protecting hash tables and free lists */
55 osi_rwlock_t buf_globalLock;
56
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
60  * pointer manually
61  */
62 cm_buf_t *buf_freeListp;
63 cm_buf_t *buf_freeListEndp;
64
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
67  * the global lock.
68  */
69 cm_buf_t *buf_allp;
70
71 /* defaults setup; these variables may be manually assigned into
72  * before calling cm_Init, as a way of changing these defaults.
73  */
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;
79
80 #ifndef DJGPP
81 static
82 HANDLE CacheHandle;
83
84 static
85 SYSTEM_INFO sysInfo;
86 #endif /* !DJGPP */
87
88 /* buffer reservation variables */
89 long buf_reservedBufs;
90 long buf_maxReservedBufs;
91 int buf_reserveWaiting;
92
93 /* callouts for reading and writing data, etc */
94 cm_buf_ops_t *cm_buf_opsp;
95
96 /* pointer to hash table; size computed dynamically */
97 cm_buf_t **buf_hashTablepp;
98
99 /* another hash table */
100 cm_buf_t **buf_fileHashTablepp;
101
102 #ifdef DISKCACHE95
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 */
109
110 /* hold a reference to an already held buffer */
111 void buf_Hold(cm_buf_t *bp)
112 {
113         lock_ObtainWrite(&buf_globalLock);
114         bp->refCount++;
115         lock_ReleaseWrite(&buf_globalLock);
116 }
117
118 /* incremental sync daemon.  Writes 1/10th of all the buffers every 5000 ms */
119 void buf_IncrSyncer(long parm)
120 {
121         cm_buf_t *bp;                   /* buffer we're hacking on; held */
122         long i;                         /* counter */
123         long nAtOnce;                   /* how many to do at once */
124         cm_req_t req;
125
126         lock_ObtainWrite(&buf_globalLock);
127         bp = buf_allp;
128         bp->refCount++;
129         lock_ReleaseWrite(&buf_globalLock);
130         nAtOnce = buf_nbuffers / 10;
131         while (1) {
132 #ifndef DJGPP
133                 i = SleepEx(5000, 1);
134                 if (i != 0) continue;
135 #else
136                 thrd_Sleep(5000);
137 #endif /* DJGPP */
138                 
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
143                          * bp held.
144                          */
145
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.
149                          */
150                         cm_InitReq(&req);
151                         req.flags |= CM_REQ_NORETRY;
152                         buf_CleanAsync(bp, &req);
153
154                         /* now advance to the next buffer; the allp chain never changes,
155                          * and so can be followed even when holding no locks.
156                          */
157                         lock_ObtainWrite(&buf_globalLock);
158                         buf_LockedRelease(bp);
159                         bp = bp->allp;
160                         if (!bp) bp = buf_allp;
161                         bp->refCount++;
162                         lock_ReleaseWrite(&buf_globalLock);
163                 }       /* for loop over a bunch of buffers */
164         }               /* whole daemon's while loop */
165 }
166
167 #ifndef DJGPP
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.
172  */
173 PSECURITY_ATTRIBUTES CreateCacheFileSA()
174 {
175         PSECURITY_ATTRIBUTES psa;
176         PSECURITY_DESCRIPTOR psd;
177         SID_IDENTIFIER_AUTHORITY authority = SECURITY_NT_AUTHORITY;
178         PSID AdminSID;
179         DWORD AdminSIDlength;
180         PACL AdminOnlyACL;
181         DWORD ACLlength;
182
183         /* Get Administrator SID */
184         AllocateAndInitializeSid(&authority, 2,
185                                  SECURITY_BUILTIN_DOMAIN_RID,
186                                  DOMAIN_ALIAS_RID_ADMINS,
187                                  0, 0, 0, 0, 0, 0,
188                                  &AdminSID);
189
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,
198                             AdminSID);
199
200         /* Create security descriptor */
201         psd = GlobalAlloc(GMEM_FIXED, sizeof(SECURITY_DESCRIPTOR));
202         InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION);
203         SetSecurityDescriptorDacl(psd, TRUE, AdminOnlyACL, FALSE);
204
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;
210
211         return psa;
212 }
213 #endif /* !DJGPP */
214
215 #ifndef DJGPP
216 /* Free a security attribute structure created by CreateCacheFileSA() */
217 VOID FreeCacheFileSA(PSECURITY_ATTRIBUTES psa)
218 {
219         BOOL b1, b2;
220         PACL pAcl;
221
222         GetSecurityDescriptorDacl(psa->lpSecurityDescriptor, &b1, &pAcl, &b2);
223         GlobalFree(pAcl);
224         GlobalFree(psa->lpSecurityDescriptor);
225         GlobalFree(psa);
226 }
227 #endif /* !DJGPP */
228         
229 /* initialize the buffer package; called with no locks
230  * held during the initialization phase.
231  */
232 long buf_Init(cm_buf_ops_t *opsp)
233 {
234         static osi_once_t once;
235         cm_buf_t *bp;
236         long sectorSize;
237         thread_t phandle;
238 #ifndef DJGPP
239         HANDLE hf, hm;
240         PSECURITY_ATTRIBUTES psa;
241 #endif /* !DJGPP */
242         long i;
243         unsigned long pid;
244         char *data;
245         long cs;
246
247 #ifndef DJGPP
248         /* Get system info; all we really want is the allocation granularity */ 
249         GetSystemInfo(&sysInfo);
250 #endif /* !DJGPP */
251
252         /* Have to be able to reserve a whole chunk */
253         if (((buf_nbuffers - 3) * buf_bufferSize) < cm_chunkSize)
254                 return CM_ERROR_TOOFEWBUFS;
255
256         /* recall for callouts */
257         cm_buf_opsp = opsp;
258
259         if (osi_Once(&once)) {
260                 /* initialize global locks */
261                 lock_InitializeRWLock(&buf_globalLock, "Global buffer lock");
262
263 #ifndef DJGPP
264                 /*
265                  * Cache file mapping constrained by
266                  * system allocation granularity;
267                  * round up, assuming granularity is a power of two
268                  */
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",
275                                  buf_nbuffers);
276                 }
277 #endif /* !DJGPP */
278
279                 /* remember this for those who want to reset it */
280                 buf_nOrigBuffers = buf_nbuffers;
281
282                 /* lower hash size to a prime number */
283                 buf_hashSize = osi_PrimeLessThan(buf_hashSize);
284
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 *));
289
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 *));
294                 
295                 /* min value for which this works */
296                 sectorSize = 1;
297
298 #ifndef DJGPP
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,
305                         psa,
306                         OPEN_ALWAYS,
307                         FILE_ATTRIBUTE_NORMAL,
308                         NULL);
309                 if (hf == INVALID_HANDLE_VALUE) {
310                         afsi_log("create file error %d", GetLastError());
311                         return CM_ERROR_INVAL;
312                 }
313                 FreeCacheFileSA(psa);
314         } else { /* buf_cacheType == CM_BUF_CACHETYPE_VIRTUAL */
315             hf = INVALID_HANDLE_VALUE;
316         }
317                 CacheHandle = hf;
318                 hm = CreateFileMapping(hf,
319                         NULL,
320                         PAGE_READWRITE,
321                         0, buf_nbuffers * buf_bufferSize,
322                         NULL);
323                 if (hm == NULL) {
324                         if (GetLastError() == ERROR_DISK_FULL) {
325                                 afsi_log("Error creating cache file mapping: disk full");
326                                 return CM_ERROR_TOOMANYBUFS;
327                         }
328                         return CM_ERROR_INVAL;
329                 }
330                 data = MapViewOfFile(hm,
331                         FILE_MAP_ALL_ACCESS,
332                         0, 0,
333                         buf_nbuffers * buf_bufferSize);
334                 if (data == NULL) {
335                         if(hf != INVALID_HANDLE_VALUE) CloseHandle(hf);
336                         CloseHandle(hm);
337                         return CM_ERROR_INVAL;
338                 }
339                 CloseHandle(hm);
340 #else
341                 /* djgpp doesn't support memory mapped files */
342                 data = malloc(buf_nbuffers * buf_bufferSize);
343 #endif /* !DJGPP */
344
345                 /* create buffer headers and put in free list */
346                 bp = malloc(buf_nbuffers * sizeof(cm_buf_t));
347                 buf_allp = NULL;
348                 for(i=0; i<buf_nbuffers; i++) {
349                         /* allocate and zero some storage */
350                         memset(bp, 0, sizeof(cm_buf_t));
351
352                         /* thread on list of all buffers */
353                         bp->allp = buf_allp;
354                         buf_allp = bp;
355                         
356                         osi_QAdd((osi_queue_t **)&buf_freeListp, &bp->q);
357                         bp->flags |= CM_BUF_INLRU;
358                         lock_InitializeMutex(&bp->mx, "Buffer mutex");
359
360                         /* grab appropriate number of bytes from aligned zone */
361                         bp->datap = data;
362
363                         /* setup last buffer pointer */
364                         if (i == 0)
365                                 buf_freeListEndp = bp;
366
367                         /* next */
368                         bp++;
369                         data += buf_bufferSize;
370                 }
371                 
372                 /* none reserved at first */
373                 buf_reservedBufs = 0;
374                 
375                 /* just for safety's sake */
376                 buf_maxReservedBufs = buf_nbuffers - 3;
377                 
378                 /* init the buffer trace log */
379                 buf_logp = osi_LogCreate("buffer", 10);
380
381                 osi_EndOnce(&once);
382                 
383                 /* and create the incr-syncer */
384                 phandle = thrd_Create(0, 0,
385                                       (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
386                                       "buf_IncrSyncer");
387
388                 osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
389 #ifndef DJGPP
390                 CloseHandle(phandle);
391 #endif /* !DJGPP */
392         }
393
394         return 0;
395 }
396
397 /* add nbuffers to the buffer pool, if possible.
398  * Called with no locks held.
399  */
400 long buf_AddBuffers(long nbuffers)
401 {
402         cm_buf_t *bp;
403         int i;
404         char *data;
405 #ifndef DJGPP
406         HANDLE hm;
407         long cs;
408
409     afsi_log("%d buffers being added to the existing cache of size %d",
410               nbuffers, buf_nbuffers);
411
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.
417          */
418         return CM_ERROR_INVAL;
419     }
420
421         /*
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
426          */
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;
432         }
433
434         /* Reserve additional buffer space by remapping cache file */
435         hm = CreateFileMapping(CacheHandle,
436                 NULL,
437                 PAGE_READWRITE,
438                 0, (buf_nbuffers + nbuffers) * buf_bufferSize,
439                 NULL);
440         if (hm == NULL) {
441                 if (GetLastError() == ERROR_DISK_FULL)
442                         return CM_ERROR_TOOMANYBUFS;
443                 else
444                         return CM_ERROR_INVAL;
445         }
446         data = MapViewOfFile(hm,
447                 FILE_MAP_ALL_ACCESS,
448                 0, buf_nbuffers * buf_bufferSize,
449                 nbuffers * buf_bufferSize);
450         if (data == NULL) {
451                 CloseHandle(hm);
452                 return CM_ERROR_INVAL;
453         }
454         CloseHandle(hm);
455 #else
456         data = malloc(buf_nbuffers * buf_bufferSize);
457 #endif /* DJGPP */
458
459         /* Create buffer headers and put in free list */
460         bp = malloc(nbuffers * sizeof(*bp));
461
462         for(i=0; i<nbuffers; i++) {
463                 memset(bp, 0, sizeof(*bp));
464         
465                 lock_InitializeMutex(&bp->mx, "cm_buf_t");
466
467                 /* grab appropriate number of bytes from aligned zone */
468                 bp->datap = data;
469
470                 bp->flags |= CM_BUF_INLRU;
471                 
472                 lock_ObtainWrite(&buf_globalLock);
473                 /* note that buf_allp chain is covered by buf_globalLock now */
474                 bp->allp = buf_allp;
475                 buf_allp = bp;
476                 osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
477                 if (!buf_freeListEndp) buf_freeListEndp = bp;
478                 buf_nbuffers++;
479                 lock_ReleaseWrite(&buf_globalLock);
480
481                 bp++;
482                 data += buf_bufferSize;
483         
484         }        /* for loop over all buffers */
485
486         return 0;
487 }
488
489 /* interface to set the number of buffers to an exact figure.
490  * Called with no locks held.
491  */
492 long buf_SetNBuffers(long nbuffers)
493 {
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;
499 }
500
501 /* release a buffer.  Buffer must be referenced, but unlocked. */
502 void buf_Release(cm_buf_t *bp)
503 {
504         lock_ObtainWrite(&buf_globalLock);
505         buf_LockedRelease(bp);
506         lock_ReleaseWrite(&buf_globalLock);
507 }
508
509 /* wait for reading or writing to clear; called with write-locked
510  * buffer, and returns with locked buffer.
511  */
512 void buf_WaitIO(cm_buf_t *bp)
513 {
514         while (1) {
515                 /* if no IO is happening, we're done */
516                 if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
517                         break;
518                 
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.
522          */
523         if ( bp->flags & CM_BUF_WAITING ) 
524             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%x", bp);
525
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);
530     }
531         
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.
534      */
535     if (bp->flags & CM_BUF_WAITING) {
536                 bp->flags &= ~CM_BUF_WAITING;
537         osi_Wakeup((long) bp);
538     }
539     osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%x", (long) bp);
540 }
541
542 /* code to drop reference count while holding buf_globalLock */
543 void buf_LockedRelease(cm_buf_t *bp)
544 {
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);
550
551                         /* watch for transition from empty to one element */
552                         if (!buf_freeListEndp)
553                                 buf_freeListEndp = buf_freeListp;
554                         bp->flags |= CM_BUF_INLRU;
555                 }
556         }
557 }
558
559 /* find a buffer, if any, for a particular file ID and offset.  Assumes
560  * that buf_globalLock is write locked when called.
561  */
562 cm_buf_t *buf_LockedFind(struct cm_scache *scp, osi_hyper_t *offsetp)
563 {
564         long i;
565         cm_buf_t *bp;
566         
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) {
572                         bp->refCount++;
573                         break;
574                 }
575         }
576         
577         /* return whatever we found, if anything */
578         return bp;
579 }
580
581 /* find a buffer with offset *offsetp for vnode *scp.  Called
582  * with no locks held.
583  */
584 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
585 {
586         cm_buf_t *bp;
587
588         lock_ObtainWrite(&buf_globalLock);
589         bp = buf_LockedFind(scp, offsetp);
590         lock_ReleaseWrite(&buf_globalLock);
591
592         return bp;
593 }
594
595 /* start cleaning I/O on this buffer.  Buffer must be write locked, and is returned
596  * write-locked.
597  *
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.
601  */
602 void buf_LockedCleanAsync(cm_buf_t *bp, cm_req_t *reqp)
603 {
604         long code;
605
606         code = 0;
607         while ((bp->flags & (CM_BUF_WRITING | CM_BUF_DIRTY)) == CM_BUF_DIRTY) {
608                 lock_ReleaseMutex(&bp->mx);
609
610                 code = (*cm_buf_opsp->Writep)(&bp->fid, &bp->offset,
611                                                 buf_bufferSize, 0, bp->userp,
612                                                 reqp);
613                 
614                 lock_ObtainMutex(&bp->mx);
615                 if (code) break;
616
617 #ifdef DISKCACHE95
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 */
622         };
623
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);
626         
627         /* if someone was waiting for the I/O that just completed or failed,
628          * wake them up.
629          */
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);
634         }
635 }
636
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.
640  */
641 void buf_Recycle(cm_buf_t *bp)
642 {
643         int i;
644         cm_buf_t **lbpp;
645         cm_buf_t *tbp;
646         cm_buf_t *prevBp, *nextBp;
647
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.
654          */
655         osi_Log2(buf_logp,
656                 "buf_Recycle recycles 0x%x, off 0x%x",
657                 bp, bp->offset.LowPart);
658
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);
662
663         if (bp->flags & CM_BUF_INHASH) {
664                 /* Remove from hash */
665
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;
670                 }
671
672                 /* we better find it */
673                 osi_assertx(tbp != NULL, "buf_GetNewLocked: hash table screwup");
674
675                 *lbpp = bp->hashp;      /* hash out */
676
677                 /* Remove from file hash */
678
679                 i = BUF_FILEHASH(&bp->fid);
680                 prevBp = bp->fileHashBackp;
681                 nextBp = bp->fileHashp;
682                 if (prevBp)
683                         prevBp->fileHashp = nextBp;
684                 else
685                         buf_fileHashTablepp[i] = nextBp;
686                 if (nextBp)
687                         nextBp->fileHashBackp = prevBp;
688
689                 bp->flags &= ~CM_BUF_INHASH;
690         }
691                         
692         /* bump the soft reference counter now, to invalidate softRefs; no
693          * wakeup is required since people don't sleep waiting for this
694          * counter to change.
695          */
696         bp->idCounter++;
697
698         /* make the fid unrecognizable */
699         memset(&bp->fid, 0, sizeof(bp->fid));
700 }
701
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.
706  *
707  * If success is returned, the buffer is returned write-locked.
708  *
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.
712  */
713 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
714 {
715         cm_buf_t *bp;           /* buffer we're dealing with */
716         cm_buf_t *nextBp;       /* next buffer in file hash chain */
717         long i;                 /* temp */
718         cm_req_t req;
719
720         cm_InitReq(&req);       /* just in case */
721
722         while(1) {
723 retry:
724                 lock_ObtainWrite(&buf_globalLock);
725                 /* check to see if we lost the race */
726                 if (scp) {
727                         if (bp = buf_LockedFind(scp, offsetp)) {
728                                 bp->refCount--;
729                                 lock_ReleaseWrite(&buf_globalLock);
730                                 return CM_BUF_EXISTS;
731                         }
732                 }
733                 
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.
738                  */
739                 osi_assertx(buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
740
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.
745                  */
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
749                          * zero.
750                          */
751                         if (bp->refCount > 0) continue;
752                         
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.
756                          */
757
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)))
762                                 continue;
763
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.
767                          */
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
771                                  * here.
772                                  */
773                                 continue;
774                         }
775                         
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
780                                  * on the big lock.
781                                  */
782                                 bp->refCount++;
783                                 lock_ReleaseWrite(&buf_globalLock);
784
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
789                                  * back here.
790                                  */
791                                 buf_CleanAsync(bp, &req);
792                                 
793                                 /* now put it back and go around again */
794                                 buf_Release(bp);
795                                 goto retry;
796                         }
797                         
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.
804                          */
805                         buf_Recycle(bp);
806
807                         /* clean up junk flags */
808                         bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
809                         bp->dataVersion = -1;   /* unknown so far */
810
811                         /* now hash in as our new buffer, and give it the
812                          * appropriate label, if requested.
813                          */
814                         if (scp) {
815                                 bp->flags |= CM_BUF_INHASH;
816                                 bp->fid = scp->fid;
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;
825                                 if (nextBp)
826                                         nextBp->fileHashBackp = bp;
827                                 buf_fileHashTablepp[i] = bp;
828                         }
829                         
830                         /* prepare to return it.  Start by giving it a good
831                          * refcount */
832                         bp->refCount = 1;
833                         
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
837                          * it there.
838                          */
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);
844                         }
845                         osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
846                         bp->flags &= ~CM_BUF_INLRU;
847                         
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.
851                          */
852                         osi_assertx(lock_TryMutex(&bp->mx),
853                                     "buf_GetNewLocked: TryMutex failed");
854
855                         lock_ReleaseWrite(&buf_globalLock);
856                         *bufpp = bp;
857                         return 0;
858                 } /* for all buffers in lru queue */
859                 lock_ReleaseWrite(&buf_globalLock);
860         }       /* while loop over everything */
861         /* not reached */
862 } /* the proc */
863
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.
866  */
867 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
868 {
869         cm_buf_t *bp;
870         long code;
871         osi_hyper_t pageOffset;
872         int created;
873
874         created = 0;
875         pageOffset.HighPart = offsetp->HighPart;
876         pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
877         while (1) {
878                 lock_ObtainWrite(&buf_globalLock);
879                 bp = buf_LockedFind(scp, &pageOffset);
880                 lock_ReleaseWrite(&buf_globalLock);
881                 if (bp) {
882                         /* lock it and break out */
883                         lock_ObtainMutex(&bp->mx);
884                         break;
885                 }
886                 
887                 /* otherwise, we have to create a page */
888                 code = buf_GetNewLocked(scp, &pageOffset, &bp);
889
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. 
892                  */
893                 if (code == CM_BUF_EXISTS) continue;
894                 
895                 /* something else went wrong */
896                 if (code != 0) return code;
897                 
898                 /* otherwise, we have a locked buffer that we just created */
899                 created = 1;
900                 break;
901         } /* big while loop */
902         
903         /* wait for reads */
904         if (bp->flags & CM_BUF_READING)
905                 buf_WaitIO(bp);
906
907         /* once it has been read once, we can unlock it and return it, still
908          * with its refcount held.
909          */
910         lock_ReleaseMutex(&bp->mx);
911         *bufpp = bp;
912         osi_Log3(buf_logp, "buf_GetNew returning bp 0x%x for file 0x%x, offset 0x%x",
913                 bp, (long) scp, offsetp->LowPart);
914         return 0;
915 }
916
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)
919 {
920         cm_buf_t *bp;
921         long code;
922         osi_hyper_t pageOffset;
923         unsigned long tcount;
924         int created;
925 #ifdef DISKCACHE95
926         cm_diskcache_t *dcp;
927 #endif /* DISKCACHE95 */
928
929         created = 0;
930         pageOffset.HighPart = offsetp->HighPart;
931         pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
932         while (1) {
933                 lock_ObtainWrite(&buf_globalLock);
934                 bp = buf_LockedFind(scp, &pageOffset);
935                 lock_ReleaseWrite(&buf_globalLock);
936                 if (bp) {
937                         /* lock it and break out */
938                         lock_ObtainMutex(&bp->mx);
939                         break;
940
941 #ifdef DISKCACHE95
942                         /* touch disk chunk to update LRU info */
943                         diskcache_Touch(bp->dcp);
944 #endif /* DISKCACHE95 */
945                 }
946                 
947                 /* otherwise, we have to create a page */
948                 code = buf_GetNewLocked(scp, &pageOffset, &bp);
949
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. 
952                  */
953                 if (code == CM_BUF_EXISTS) continue;
954                 
955                 /* something else went wrong */
956                 if (code != 0) return code;
957                 
958                 /* otherwise, we have a locked buffer that we just created */
959                 created = 1;
960                 break;
961         } /* big while loop */
962         
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.
965          */
966         if (created) {
967                 /* load the page; freshly created pages should be idle */
968                 osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
969
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;
974 #endif /* !DJGPP */
975
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);
979
980 #ifdef DISKCACHE95
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 */
984
985                 if (code != 0) {
986                         /* failure or queued */
987 #ifndef DJGPP   /* cm_bufRead always returns 0 */
988                         if (code != ERROR_IO_PENDING) {
989 #endif
990                                 bp->error = code;
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);
996                                 }
997                                 lock_ReleaseMutex(&bp->mx);
998                                 buf_Release(bp);
999                                 return code;
1000 #ifndef DJGPP
1001                         }
1002 #endif
1003                 } else {
1004                         /* otherwise, I/O completed instantly and we're done, except
1005                          * for padding the xfr out with 0s and checking for EOF
1006                          */
1007                         if (tcount < (unsigned long) buf_bufferSize) {
1008                                 memset(bp->datap+tcount, 0, buf_bufferSize - tcount);
1009                                 if (tcount == 0)
1010                                         bp->flags |= CM_BUF_EOF;
1011                         }
1012                         bp->flags &= ~CM_BUF_READING;
1013                         if (bp->flags & CM_BUF_WAITING) {
1014                                 bp->flags &= ~CM_BUF_WAITING;
1015                                 osi_Wakeup((long) bp);
1016                         }
1017                 }
1018                         
1019         } /* if created */
1020         
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.
1023          */
1024         if (bp->flags & CM_BUF_READING)
1025                 buf_WaitIO(bp);
1026
1027         /* once it has been read once, we can unlock it and return it, still
1028          * with its refcount held.
1029          */
1030         lock_ReleaseMutex(&bp->mx);
1031         *bufpp = bp;
1032
1033         /* now remove from queue; will be put in at the head (farthest from
1034          * being recycled) when we're done in buf_Release.
1035          */
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;
1042         }
1043         lock_ReleaseWrite(&buf_globalLock);
1044
1045         osi_Log3(buf_logp, "buf_Get returning bp 0x%x for file 0x%x, offset 0x%x",
1046                 bp, (long) scp, offsetp->LowPart);
1047         return 0;
1048 }
1049
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.
1054  */
1055 long buf_CountFreeList(void)
1056 {
1057         long count;
1058         cm_buf_t *bufp;
1059
1060         count = 0;
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.
1066                  */
1067                 if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1068                         count++;
1069         }
1070         lock_ReleaseRead(&buf_globalLock);
1071         return count;
1072 }
1073
1074 /* clean a buffer synchronously */
1075 void buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1076 {
1077         lock_ObtainMutex(&bp->mx);
1078         buf_LockedCleanAsync(bp, reqp);
1079         lock_ReleaseMutex(&bp->mx);
1080 }
1081
1082 /* wait for a buffer's cleaning to finish */
1083 void buf_CleanWait(cm_buf_t *bp)
1084 {
1085         lock_ObtainMutex(&bp->mx);
1086         if (bp->flags & CM_BUF_WRITING) {
1087                 buf_WaitIO(bp);
1088         }
1089         lock_ReleaseMutex(&bp->mx);
1090 }
1091
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.
1094  *
1095  * The buffer must be locked before calling this routine.
1096  */
1097 void buf_SetDirty(cm_buf_t *bp)
1098 {
1099         osi_assert(bp->refCount > 0);
1100         
1101         osi_Log1(buf_logp, "buf_SetDirty 0x%x", bp);
1102
1103         /* set dirty bit */
1104         bp->flags |= CM_BUF_DIRTY;
1105
1106         /* and turn off EOF flag, since it has associated data now */
1107         bp->flags &= ~CM_BUF_EOF;
1108 }
1109
1110 /* clean all buffers, reset log pointers and invalidate all buffers.
1111  * Called with no locks held, and returns with same.
1112  *
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.
1118  *
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.
1125  *
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
1128  * all buffers.
1129  */
1130 long buf_CleanAndReset(void)
1131 {
1132         long i;
1133         cm_buf_t *bp;
1134         cm_req_t req;
1135
1136         lock_ObtainWrite(&buf_globalLock);
1137         for(i=0; i<buf_hashSize; i++) {
1138                 for(bp = buf_hashTablepp[i]; bp; bp = bp->hashp) {
1139                         bp->refCount++;
1140                         lock_ReleaseWrite(&buf_globalLock);
1141                         
1142                         /* now no locks are held; clean buffer and go on */
1143                         cm_InitReq(&req);
1144                         buf_CleanAsync(bp, &req);
1145                         buf_CleanWait(bp);
1146                         
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 */
1152         
1153         /* release locks */
1154         lock_ReleaseWrite(&buf_globalLock);
1155
1156         /* and we're done */
1157         return 0;
1158 }
1159
1160 /* called without global lock being held, reserves buffers for callers
1161  * that need more than one held (not locked) at once.
1162  */
1163 void buf_ReserveBuffers(long nbuffers)
1164 {
1165         lock_ObtainWrite(&buf_globalLock);
1166         while (1) {
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);
1172                 }
1173                 else {
1174                         buf_reservedBufs += nbuffers;
1175                         break;
1176                 }
1177         }
1178         lock_ReleaseWrite(&buf_globalLock);
1179 }
1180
1181 int buf_TryReserveBuffers(long nbuffers)
1182 {
1183         int code;
1184
1185         lock_ObtainWrite(&buf_globalLock);
1186         if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1187                 code = 0;
1188         }
1189         else {
1190                 buf_reservedBufs += nbuffers;
1191                 code = 1;
1192         }
1193         lock_ReleaseWrite(&buf_globalLock);
1194         return code;
1195 }
1196
1197 /* called without global lock held, releases reservation held by
1198  * buf_ReserveBuffers.
1199  */
1200 void buf_UnreserveBuffers(long nbuffers)
1201 {
1202         lock_ObtainWrite(&buf_globalLock);
1203         buf_reservedBufs -= nbuffers;
1204         if (buf_reserveWaiting) {
1205                 buf_reserveWaiting = 0;
1206                 osi_Wakeup((long) &buf_reservedBufs);
1207         }
1208         lock_ReleaseWrite(&buf_globalLock);
1209 }
1210
1211 /* truncate the buffers past sizep, zeroing out the page, if we don't
1212  * end on a page boundary.
1213  *
1214  * Requires cm_bufCreateLock to be write locked.
1215  */
1216 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1217         osi_hyper_t *sizep)
1218 {
1219         cm_buf_t *bufp;
1220         cm_buf_t *nbufp;                        /* next buffer, if didRelease */
1221         osi_hyper_t bufEnd;
1222         long code;
1223         long bufferPos;
1224         int didRelease;
1225         long i;
1226         
1227         /* assert that cm_bufCreateLock is held in write mode */
1228         lock_AssertWrite(&scp->bufCreateLock);
1229
1230         i = BUF_FILEHASH(&scp->fid);
1231
1232         lock_ObtainWrite(&buf_globalLock);
1233         bufp = buf_fileHashTablepp[i];
1234         if (bufp == NULL) {
1235                 lock_ReleaseWrite(&buf_globalLock);
1236                 return 0;
1237         }
1238
1239         bufp->refCount++;
1240         lock_ReleaseWrite(&buf_globalLock);
1241         for(; bufp; bufp = nbufp) {
1242                 didRelease = 0;
1243                 lock_ObtainMutex(&bufp->mx);
1244
1245                 bufEnd.HighPart = 0;
1246                 bufEnd.LowPart = buf_bufferSize;
1247                 bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1248
1249                 if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1250                         LargeIntegerLessThan(*sizep, bufEnd)) {
1251                         buf_WaitIO(bufp);
1252                 }
1253                 lock_ObtainMutex(&scp->mx);
1254         
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.
1257                  */
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.
1266                  */
1267                 if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1268                         && LargeIntegerLessThan(*sizep, bufEnd)) {
1269                         
1270                         lock_ObtainWrite(&buf_globalLock);
1271
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.
1276                          */
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++;
1282                         }
1283                         else {
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.
1287                                  *
1288                                  * Zero out remainder of the page, in case we
1289                                  * seek and write past EOF, and make this data
1290                                  * visible again.
1291                                  */
1292                                 bufferPos = sizep->LowPart & (buf_bufferSize - 1);
1293                                 osi_assert(bufferPos != 0);
1294                                 memset(bufp->datap + bufferPos, 0,
1295                                         buf_bufferSize - bufferPos);
1296                         }
1297
1298                         lock_ReleaseWrite(&buf_globalLock);
1299
1300                 }
1301                 
1302                 lock_ReleaseMutex(&scp->mx);
1303                 lock_ReleaseMutex(&bufp->mx);
1304                 if (!didRelease) {
1305                         lock_ObtainWrite(&buf_globalLock);
1306                         nbufp = bufp->fileHashp;
1307                         if (nbufp) nbufp->refCount++;
1308                         buf_LockedRelease(bufp);
1309                         lock_ReleaseWrite(&buf_globalLock);
1310                 }
1311
1312                 /* bail out early if we fail */
1313                 if (code) {
1314                         /* at this point, nbufp is held; bufp has already been
1315                          * released.
1316                          */
1317                         if (nbufp) buf_Release(nbufp);
1318                         return code;
1319                 }
1320         }
1321         
1322         /* success */
1323         return 0;
1324 }
1325
1326 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1327 {
1328         long code;
1329         cm_buf_t *bp;           /* buffer we're hacking on */
1330         cm_buf_t *nbp;
1331         int didRelease;
1332         long i;
1333
1334         i = BUF_FILEHASH(&scp->fid);
1335
1336         code = 0;
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 */
1343
1344                 /* clean buffer synchronously */
1345                 if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1346                         lock_ObtainMutex(&bp->mx);
1347
1348                         /* start cleaning the buffer, and wait for it to finish */
1349                         buf_LockedCleanAsync(bp, reqp);
1350                         buf_WaitIO(bp);
1351                         lock_ReleaseMutex(&bp->mx);
1352
1353                         code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1354                         if (code) goto skip;
1355
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.
1359                          */
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++;
1365                                         didRelease = 1;
1366                                         buf_Recycle(bp);
1367                                 }
1368                         }
1369                         lock_ReleaseWrite(&buf_globalLock);
1370
1371                         (*cm_buf_opsp->Unstabilizep)(scp, userp);
1372                 }
1373
1374 skip:
1375                 if (!didRelease) {
1376                         lock_ObtainWrite(&buf_globalLock);
1377                         if (nbp = bp->fileHashp) nbp->refCount++;
1378                         buf_LockedRelease(bp);
1379                         lock_ReleaseWrite(&buf_globalLock);
1380                 }
1381         }       /* for loop over a bunch of buffers */
1382         
1383         /* done */
1384         return code;
1385 }
1386
1387 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1388 {
1389         long code;
1390         cm_buf_t *bp;           /* buffer we're hacking on */
1391     cm_buf_t *nbp;              /* next one */
1392         long i;
1393
1394         i = BUF_FILEHASH(&scp->fid);
1395
1396         code = 0;
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) {
1404                         if (userp) {
1405                 cm_HoldUser(userp);
1406                                 lock_ObtainMutex(&bp->mx);
1407                                 if (bp->userp) 
1408                     cm_ReleaseUser(bp->userp);
1409                 bp->userp = userp;
1410                                 lock_ReleaseMutex(&bp->mx);
1411             }
1412                         buf_CleanAsync(bp, reqp);
1413             buf_CleanWait(bp);
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;
1418             }
1419             lock_ReleaseMutex(&bp->mx);
1420                 }
1421
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 */
1428         
1429     /* done */
1430         return code;
1431 }
1432
1433 /* dump the contents of the buf_hashTablepp. */
1434 int cm_DumpBufHashTable(FILE *outputFile, char *cookie)
1435 {
1436     int zilch;
1437     cm_buf_t *bp;
1438     char output[1024];
1439     int i;
1440   
1441         if (buf_hashTablepp == NULL)
1442                 return -1;
1443
1444     lock_ObtainRead(&buf_globalLock);
1445   
1446     sprintf(output, "%s - dumping buf_HashTable - buf_hashSize=%d\n", cookie, buf_hashSize);
1447     WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1448   
1449     for (i = 0; i < buf_hashSize; i++)
1450     {
1451         for(bp = buf_hashTablepp[i]; bp; bp=bp->hashp) 
1452         {
1453             if (bp->refCount)
1454             {
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);
1460             }
1461         }
1462     }
1463   
1464     sprintf(output, "%s - Done dumping buf_HashTable.\n", cookie);
1465     WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1466
1467     lock_ReleaseRead(&buf_globalLock);
1468     return 0;
1469 }
1470