windows-cb-deadlock-20050104
[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 #include <strsafe.h>
23
24 #include "afsd.h"
25
26 #ifdef DEBUG
27 #define TRACE_BUFFER 1
28 #endif
29
30 extern void afsi_log(char *pattern, ...);
31
32 /* This module implements the buffer package used by the local transaction
33  * system (cm).  It is initialized by calling cm_Init, which calls buf_Init;
34  * it must be initalized before any of its main routines are called.
35  *
36  * Each buffer is hashed into a hash table by file ID and offset, and if its
37  * reference count is zero, it is also in a free list.
38  *
39  * There are two locks involved in buffer processing.  The global lock
40  * buf_globalLock protects all of the global variables defined in this module,
41  * the reference counts and hash pointers in the actual cm_buf_t structures,
42  * and the LRU queue pointers in the buffer structures.
43  *
44  * The mutexes in the buffer structures protect the remaining fields in the
45  * buffers, as well the data itself.
46  * 
47  * The locking hierarchy here is this:
48  * 
49  * - resv multiple simul. buffers reservation
50  * - lock buffer I/O flags
51  * - lock buffer's mutex
52  * - lock buf_globalLock
53  *
54  */
55
56 /* global debugging log */
57 osi_log_t *buf_logp = NULL;
58
59 /* Global lock protecting hash tables and free lists */
60 osi_rwlock_t buf_globalLock;
61
62 /* ptr to head of the free list (most recently used) and the
63  * tail (the guy to remove first).  We use osi_Q* functions
64  * to put stuff in buf_freeListp, and maintain the end
65  * pointer manually
66  */
67 cm_buf_t *buf_freeListp;
68 cm_buf_t *buf_freeListEndp;
69
70 /* a pointer to a list of all buffers, just so that we can find them
71  * easily for debugging, and for the incr syncer.  Locked under
72  * the global lock.
73  */
74 cm_buf_t *buf_allp;
75
76 /* defaults setup; these variables may be manually assigned into
77  * before calling cm_Init, as a way of changing these defaults.
78  */
79 long buf_nbuffers = CM_BUF_BUFFERS;
80 long buf_nOrigBuffers;
81 long buf_bufferSize = CM_BUF_SIZE;
82 long buf_hashSize = CM_BUF_HASHSIZE;
83 int buf_cacheType = CM_BUF_CACHETYPE_FILE;
84
85 #ifndef DJGPP
86 static
87 HANDLE CacheHandle;
88
89 static 
90 VOID * ViewOfFile;
91
92 static
93 SYSTEM_INFO sysInfo;
94 #endif /* !DJGPP */
95
96 /* buffer reservation variables */
97 long buf_reservedBufs;
98 long buf_maxReservedBufs;
99 int buf_reserveWaiting;
100
101 /* callouts for reading and writing data, etc */
102 cm_buf_ops_t *cm_buf_opsp;
103
104 /* pointer to hash table; size computed dynamically */
105 cm_buf_t **buf_hashTablepp;
106
107 /* another hash table */
108 cm_buf_t **buf_fileHashTablepp;
109
110 #ifdef DISKCACHE95
111 /* for experimental disk caching support in Win95 client */
112 cm_buf_t *buf_diskFreeListp;
113 cm_buf_t *buf_diskFreeListEndp;
114 cm_buf_t *buf_diskAllp;
115 extern int cm_diskCacheEnabled;
116 #endif /* DISKCACHE95 */
117
118 /* hold a reference to an already held buffer */
119 void buf_Hold(cm_buf_t *bp)
120 {
121     lock_ObtainWrite(&buf_globalLock);
122     bp->refCount++;
123     lock_ReleaseWrite(&buf_globalLock);
124 }
125
126 /* incremental sync daemon.  Writes 1/10th of all the buffers every 5000 ms */
127 void buf_IncrSyncer(long parm)
128 {
129     cm_buf_t *bp;                       /* buffer we're hacking on; held */
130     long i;                             /* counter */
131     long nAtOnce;                       /* how many to do at once */
132     cm_req_t req;
133
134     lock_ObtainWrite(&buf_globalLock);
135     bp = buf_allp;
136     bp->refCount++;
137     lock_ReleaseWrite(&buf_globalLock);
138     nAtOnce = buf_nbuffers / 10;
139     while (1) {
140 #ifndef DJGPP
141         i = SleepEx(5000, 1);
142         if (i != 0) continue;
143 #else
144         thrd_Sleep(5000);
145 #endif /* DJGPP */
146                 
147         /* now go through our percentage of the buffers */
148         for(i=0; i<nAtOnce; i++) {
149             /* don't want its identity changing while we're
150              * messing with it, so must do all of this with
151              * bp held.
152              */
153
154             /* start cleaning the buffer; don't touch log pages since
155              * the log code counts on knowing exactly who is writing
156              * a log page at any given instant.
157              */
158             cm_InitReq(&req);
159             req.flags |= CM_REQ_NORETRY;
160             buf_CleanAsync(bp, &req);
161
162             /* now advance to the next buffer; the allp chain never changes,
163              * and so can be followed even when holding no locks.
164              */
165             lock_ObtainWrite(&buf_globalLock);
166             buf_LockedRelease(bp);
167             bp = bp->allp;
168             if (!bp) bp = buf_allp;
169             bp->refCount++;
170             lock_ReleaseWrite(&buf_globalLock);
171         }       /* for loop over a bunch of buffers */
172     }           /* whole daemon's while loop */
173 }
174
175 #ifndef DJGPP
176 /* Create a security attribute structure suitable for use when the cache file
177  * is created.  What we mainly want is that only the administrator should be
178  * able to do anything with the file.  We create an ACL with only one entry,
179  * an entry that grants all rights to the administrator.
180  */
181 PSECURITY_ATTRIBUTES CreateCacheFileSA()
182 {
183     PSECURITY_ATTRIBUTES psa;
184     PSECURITY_DESCRIPTOR psd;
185     SID_IDENTIFIER_AUTHORITY authority = SECURITY_NT_AUTHORITY;
186     PSID AdminSID;
187     DWORD AdminSIDlength;
188     PACL AdminOnlyACL;
189     DWORD ACLlength;
190
191     /* Get Administrator SID */
192     AllocateAndInitializeSid(&authority, 2,
193                               SECURITY_BUILTIN_DOMAIN_RID,
194                               DOMAIN_ALIAS_RID_ADMINS,
195                               0, 0, 0, 0, 0, 0,
196                               &AdminSID);
197
198     /* Create Administrator-only ACL */
199     AdminSIDlength = GetLengthSid(AdminSID);
200     ACLlength = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE)
201         + AdminSIDlength - sizeof(DWORD);
202     AdminOnlyACL = GlobalAlloc(GMEM_FIXED, ACLlength);
203     InitializeAcl(AdminOnlyACL, ACLlength, ACL_REVISION);
204     AddAccessAllowedAce(AdminOnlyACL, ACL_REVISION,
205                          STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL,
206                          AdminSID);
207
208     /* Create security descriptor */
209     psd = GlobalAlloc(GMEM_FIXED, sizeof(SECURITY_DESCRIPTOR));
210     InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION);
211     SetSecurityDescriptorDacl(psd, TRUE, AdminOnlyACL, FALSE);
212
213     /* Create security attributes structure */
214     psa = GlobalAlloc(GMEM_FIXED, sizeof(SECURITY_ATTRIBUTES));
215     psa->nLength = sizeof(SECURITY_ATTRIBUTES);
216     psa->lpSecurityDescriptor = psd;
217     psa->bInheritHandle = TRUE;
218
219     return psa;
220 }       
221 #endif /* !DJGPP */
222
223 #ifndef DJGPP
224 /* Free a security attribute structure created by CreateCacheFileSA() */
225 VOID FreeCacheFileSA(PSECURITY_ATTRIBUTES psa)
226 {
227     BOOL b1, b2;
228     PACL pAcl;
229
230     GetSecurityDescriptorDacl(psa->lpSecurityDescriptor, &b1, &pAcl, &b2);
231     GlobalFree(pAcl);
232     GlobalFree(psa->lpSecurityDescriptor);
233     GlobalFree(psa);
234 }       
235 #endif /* !DJGPP */
236         
237 /* initialize the buffer package; called with no locks
238  * held during the initialization phase.
239  */
240 long buf_Init(cm_buf_ops_t *opsp)
241 {
242     static osi_once_t once;
243     cm_buf_t *bp;
244     long sectorSize;
245     thread_t phandle;
246 #ifndef DJGPP
247     HANDLE hf, hm;
248     PSECURITY_ATTRIBUTES psa;
249 #endif /* !DJGPP */
250     long i;
251     unsigned long pid;
252     char *data;
253     long cs;
254
255 #ifndef DJGPP
256     /* Get system info; all we really want is the allocation granularity */ 
257     GetSystemInfo(&sysInfo);
258 #endif /* !DJGPP */
259
260     /* Have to be able to reserve a whole chunk */
261     if (((buf_nbuffers - 3) * buf_bufferSize) < cm_chunkSize)
262         return CM_ERROR_TOOFEWBUFS;
263
264     /* recall for callouts */
265     cm_buf_opsp = opsp;
266
267     if (osi_Once(&once)) {
268         /* initialize global locks */
269         lock_InitializeRWLock(&buf_globalLock, "Global buffer lock");
270
271 #ifndef DJGPP
272         /*
273         * Cache file mapping constrained by
274          * system allocation granularity;
275          * round up, assuming granularity is a power of two
276          */
277         cs = buf_nbuffers * buf_bufferSize;
278         cs = (cs + (sysInfo.dwAllocationGranularity - 1))
279             & ~(sysInfo.dwAllocationGranularity - 1);
280         if (cs != buf_nbuffers * buf_bufferSize) {
281             buf_nbuffers = cs / buf_bufferSize;
282             afsi_log("Cache size rounded up to %d buffers",
283                       buf_nbuffers);
284         }
285 #endif /* !DJGPP */
286
287         /* remember this for those who want to reset it */
288         buf_nOrigBuffers = buf_nbuffers;
289
290         /* lower hash size to a prime number */
291         buf_hashSize = osi_PrimeLessThan(buf_hashSize);
292
293         /* create hash table */
294         buf_hashTablepp = malloc(buf_hashSize * sizeof(cm_buf_t *));
295         memset((void *)buf_hashTablepp, 0,
296                 buf_hashSize * sizeof(cm_buf_t *));
297
298         /* another hash table */
299         buf_fileHashTablepp = malloc(buf_hashSize * sizeof(cm_buf_t *));
300         memset((void *)buf_fileHashTablepp, 0,
301                 buf_hashSize * sizeof(cm_buf_t *));
302                 
303         /* min value for which this works */
304         sectorSize = 1;
305
306 #ifndef DJGPP
307         if (buf_cacheType == CM_BUF_CACHETYPE_FILE) {
308             /* Reserve buffer space by mapping cache file */
309             psa = CreateCacheFileSA();
310             hf = CreateFile(cm_CachePath,
311                              GENERIC_READ | GENERIC_WRITE,
312                              FILE_SHARE_READ | FILE_SHARE_WRITE,
313                              psa,
314                              OPEN_ALWAYS,
315                              FILE_ATTRIBUTE_NORMAL,
316                              NULL);
317             FreeCacheFileSA(psa);
318             if (hf == INVALID_HANDLE_VALUE) {
319                 afsi_log("Error creating cache file \"%s\" error %d", 
320                           cm_CachePath, GetLastError());
321                 return CM_ERROR_INVAL;
322             } else if (GetLastError() == ERROR_ALREADY_EXISTS) {
323                 BY_HANDLE_FILE_INFORMATION fileInfo;
324
325                 afsi_log("Cache File \"%s\" already exists", cm_CachePath);
326                 if ( GetFileInformationByHandle(hf, &fileInfo) )
327                     afsi_log("Existing File Size: %08X:%08X",
328                               fileInfo.nFileSizeHigh,
329                               fileInfo.nFileSizeLow);
330             }
331         } else { /* buf_cacheType == CM_BUF_CACHETYPE_VIRTUAL */
332             hf = INVALID_HANDLE_VALUE;
333         }
334         afsi_log("File Mapping Size: %08X", buf_nbuffers * buf_bufferSize);
335
336         CacheHandle = hf;
337         hm = CreateFileMapping(hf,
338                                 NULL,
339                                 PAGE_READWRITE,
340                                 0, buf_nbuffers * buf_bufferSize,
341                                 NULL);
342         if (hm == NULL) {
343             if (GetLastError() == ERROR_DISK_FULL) {
344                 afsi_log("Error creating cache file mapping: disk full");
345                 return CM_ERROR_TOOMANYBUFS;
346             }
347             return CM_ERROR_INVAL;
348         }
349         ViewOfFile = MapViewOfFile(hm,
350                                    FILE_MAP_ALL_ACCESS,
351                                    0, 0,   
352                                    buf_nbuffers * buf_bufferSize);
353         if (ViewOfFile == NULL) {
354             afsi_log("Error mapping view of file: 0x%X", GetLastError());
355             if (hf != INVALID_HANDLE_VALUE)
356                 CloseHandle(hf);
357             CloseHandle(hm);
358             return CM_ERROR_INVAL;
359         }
360         CloseHandle(hm);
361
362         data = ViewOfFile;
363 #else   
364         /* djgpp doesn't support memory mapped files */
365         data = malloc(buf_nbuffers * buf_bufferSize);
366 #endif /* !DJGPP */
367
368         /* create buffer headers and put in free list */
369         bp = malloc(buf_nbuffers * sizeof(cm_buf_t));
370         buf_allp = NULL;
371         for(i=0; i<buf_nbuffers; i++) {
372             /* allocate and zero some storage */
373             memset(bp, 0, sizeof(cm_buf_t));
374
375             /* thread on list of all buffers */
376             bp->allp = buf_allp;
377             buf_allp = bp;
378
379             osi_QAdd((osi_queue_t **)&buf_freeListp, &bp->q);
380             bp->flags |= CM_BUF_INLRU;
381             lock_InitializeMutex(&bp->mx, "Buffer mutex");
382
383             /* grab appropriate number of bytes from aligned zone */
384             bp->datap = data;
385
386             /* setup last buffer pointer */
387             if (i == 0)
388                 buf_freeListEndp = bp;
389
390             /* next */
391             bp++;
392             data += buf_bufferSize;
393         }
394
395         /* none reserved at first */
396         buf_reservedBufs = 0;
397
398         /* just for safety's sake */
399         buf_maxReservedBufs = buf_nbuffers - 3;
400
401 #ifdef TRACE_BUFFER
402         /* init the buffer trace log */
403         buf_logp = osi_LogCreate("buffer", 1000);
404         osi_LogEnable(buf_logp);
405 #endif
406
407         osi_EndOnce(&once);
408
409         /* and create the incr-syncer */
410         phandle = thrd_Create(0, 0,
411                                (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
412                                "buf_IncrSyncer");
413
414         osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
415 #ifndef DJGPP
416         CloseHandle(phandle);
417 #endif /* !DJGPP */
418     }
419
420     return 0;
421 }
422
423 void
424 buf_Shutdown(void)
425 {
426     UnmapViewOfFile(ViewOfFile);
427     CloseHandle(CacheHandle);
428 }
429
430 /* add nbuffers to the buffer pool, if possible.
431  * Called with no locks held.
432  */
433 long buf_AddBuffers(long nbuffers)
434 {
435     cm_buf_t *bp;
436     int i;
437     char *data;
438 #ifndef DJGPP
439     HANDLE hm;
440     long cs;
441
442     afsi_log("%d buffers being added to the existing cache of size %d",
443               nbuffers, buf_nbuffers);
444
445     if (buf_cacheType == CM_BUF_CACHETYPE_VIRTUAL) {
446         /* The size of a virtual cache cannot be changed after it has
447          * been created.  Subsequent calls to MapViewofFile() with
448          * an existing mapping object name would not allow the 
449          * object to be resized.  Return failure immediately.
450          */
451         return CM_ERROR_INVAL;
452     }
453
454     /*
455      * Cache file mapping constrained by
456      * system allocation granularity;
457      * round up, assuming granularity is a power of two;
458      * assume existing cache size is already rounded
459      */
460     cs = nbuffers * buf_bufferSize;
461     cs = (cs + (sysInfo.dwAllocationGranularity - 1))
462         & ~(sysInfo.dwAllocationGranularity - 1);
463     if (cs != nbuffers * buf_bufferSize) {
464         nbuffers = cs / buf_bufferSize;
465     }
466
467     /* Reserve additional buffer space by remapping cache file */
468     hm = CreateFileMapping(CacheHandle,
469                             NULL,
470                             PAGE_READWRITE,
471                             0, (buf_nbuffers + nbuffers) * buf_bufferSize,
472                             NULL);
473     if (hm == NULL) {
474         if (GetLastError() == ERROR_DISK_FULL)
475             return CM_ERROR_TOOMANYBUFS;
476         else
477             return CM_ERROR_INVAL;
478     }
479     data = MapViewOfFile(hm,
480                           FILE_MAP_ALL_ACCESS,
481                           0, buf_nbuffers * buf_bufferSize,
482                           nbuffers * buf_bufferSize);
483     if (data == NULL) {
484         CloseHandle(hm);
485         return CM_ERROR_INVAL;
486     }
487     CloseHandle(hm);
488 #else
489     data = malloc(buf_nbuffers * buf_bufferSize);
490 #endif /* DJGPP */
491
492     /* Create buffer headers and put in free list */
493     bp = malloc(nbuffers * sizeof(*bp));
494
495     for(i=0; i<nbuffers; i++) {
496         memset(bp, 0, sizeof(*bp));
497         
498         lock_InitializeMutex(&bp->mx, "cm_buf_t");
499
500         /* grab appropriate number of bytes from aligned zone */
501         bp->datap = data;
502
503         bp->flags |= CM_BUF_INLRU;
504
505         lock_ObtainWrite(&buf_globalLock);
506         /* note that buf_allp chain is covered by buf_globalLock now */
507         bp->allp = buf_allp;
508         buf_allp = bp;
509         osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
510         if (!buf_freeListEndp) buf_freeListEndp = bp;
511         buf_nbuffers++;
512         lock_ReleaseWrite(&buf_globalLock);
513
514         bp++;
515         data += buf_bufferSize;
516         
517     }    /* for loop over all buffers */
518
519     return 0;
520 }       
521
522 /* interface to set the number of buffers to an exact figure.
523  * Called with no locks held.
524  */
525 long buf_SetNBuffers(long nbuffers)
526 {
527     if (nbuffers < 10) 
528         return CM_ERROR_INVAL;
529     if (nbuffers == buf_nbuffers) 
530         return 0;
531     else if (nbuffers > buf_nbuffers)
532         return buf_AddBuffers(nbuffers - buf_nbuffers);
533     else 
534         return CM_ERROR_INVAL;
535 }
536
537 /* release a buffer.  Buffer must be referenced, but unlocked. */
538 void buf_Release(cm_buf_t *bp)
539 {
540     lock_ObtainWrite(&buf_globalLock);
541     buf_LockedRelease(bp);
542     lock_ReleaseWrite(&buf_globalLock);
543 }
544
545 /* wait for reading or writing to clear; called with write-locked
546  * buffer, and returns with locked buffer.
547  */
548 void buf_WaitIO(cm_buf_t *bp)
549 {
550     while (1) {
551         /* if no IO is happening, we're done */
552         if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
553             break;
554                 
555         /* otherwise I/O is happening, but some other thread is waiting for
556          * the I/O already.  Wait for that guy to figure out what happened,
557          * and then check again.
558          */
559         if ( bp->flags & CM_BUF_WAITING ) 
560             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%x", bp);
561
562         bp->flags |= CM_BUF_WAITING;
563         osi_SleepM((long) bp, &bp->mx);
564         lock_ObtainMutex(&bp->mx);
565         osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%x", bp);
566     }
567         
568     /* if we get here, the IO is done, but we may have to wakeup people waiting for
569      * the I/O to complete.  Do so.
570      */
571     if (bp->flags & CM_BUF_WAITING) {
572         bp->flags &= ~CM_BUF_WAITING;
573         osi_Wakeup((long) bp);
574     }
575     osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%x", (long) bp);
576 }
577
578 /* code to drop reference count while holding buf_globalLock */
579 void buf_LockedRelease(cm_buf_t *bp)
580 {
581     /* ensure that we're in the LRU queue if our ref count is 0 */
582     osi_assert(bp->refCount > 0);
583     if (--bp->refCount == 0) {
584         if (!(bp->flags & CM_BUF_INLRU)) {
585             osi_QAdd((osi_queue_t **) &buf_freeListp, &bp->q);
586
587             /* watch for transition from empty to one element */
588             if (!buf_freeListEndp)
589                 buf_freeListEndp = buf_freeListp;
590             bp->flags |= CM_BUF_INLRU;
591         }
592     }
593 }       
594
595 /* find a buffer, if any, for a particular file ID and offset.  Assumes
596  * that buf_globalLock is write locked when called.
597  */
598 cm_buf_t *buf_LockedFind(struct cm_scache *scp, osi_hyper_t *offsetp)
599 {
600     long i;
601     cm_buf_t *bp;
602
603     i = BUF_HASH(&scp->fid, offsetp);
604     for(bp = buf_hashTablepp[i]; bp; bp=bp->hashp) {
605         if (cm_FidCmp(&scp->fid, &bp->fid) == 0
606              && offsetp->LowPart == bp->offset.LowPart
607              && offsetp->HighPart == bp->offset.HighPart) {
608             bp->refCount++;
609             break;
610         }
611     }
612         
613     /* return whatever we found, if anything */
614     return bp;
615 }
616
617 /* find a buffer with offset *offsetp for vnode *scp.  Called
618  * with no locks held.
619  */
620 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
621 {
622     cm_buf_t *bp;
623
624     lock_ObtainWrite(&buf_globalLock);
625     bp = buf_LockedFind(scp, offsetp);
626     lock_ReleaseWrite(&buf_globalLock);
627
628     return bp;
629 }       
630
631 /* start cleaning I/O on this buffer.  Buffer must be write locked, and is returned
632  * write-locked.
633  *
634  * Makes sure that there's only one person writing this block
635  * at any given time, and also ensures that the log is forced sufficiently far,
636  * if this buffer contains logged data.
637  */
638 void buf_LockedCleanAsync(cm_buf_t *bp, cm_req_t *reqp)
639 {
640     long code;
641
642     code = 0;
643     while ((bp->flags & (CM_BUF_WRITING | CM_BUF_DIRTY)) == CM_BUF_DIRTY) {
644         lock_ReleaseMutex(&bp->mx);
645
646         code = (*cm_buf_opsp->Writep)(&bp->fid, &bp->offset,
647                                        buf_bufferSize, 0, bp->userp,
648                                        reqp);
649                 
650         lock_ObtainMutex(&bp->mx);
651         if (code) 
652             break;
653
654 #ifdef DISKCACHE95
655         /* Disk cache support */
656         /* write buffer to disk cache (synchronous for now) */
657         diskcache_Update(bp->dcp, bp->datap, buf_bufferSize, bp->dataVersion);
658 #endif /* DISKCACHE95 */
659     };
660
661     /* do logging after call to GetLastError, or else */
662     osi_Log2(buf_logp, "buf_CleanAsync starts I/O on 0x%x, done=%d", bp, code);
663         
664     /* if someone was waiting for the I/O that just completed or failed,
665      * wake them up.
666      */
667     if (bp->flags & CM_BUF_WAITING) {
668         /* turn off flags and wakeup users */
669         bp->flags &= ~CM_BUF_WAITING;
670         osi_Wakeup((long) bp);
671     }
672 }
673
674 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
675  * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
676  * The buffer must already be clean, and no I/O should be happening to it.
677  */
678 void buf_Recycle(cm_buf_t *bp)
679 {
680     int i;
681     cm_buf_t **lbpp;
682     cm_buf_t *tbp;
683     cm_buf_t *prevBp, *nextBp;
684
685     /* if we get here, we know that the buffer still has a 0 ref count,
686      * and that it is clean and has no currently pending I/O.  This is
687      * the dude to return.
688      * Remember that as long as the ref count is 0, we know that we won't
689      * have any lock conflicts, so we can grab the buffer lock out of
690      * order in the locking hierarchy.
691      */
692     osi_Log2( buf_logp, "buf_Recycle recycles 0x%x, off 0x%x",
693               bp, bp->offset.LowPart);
694
695     osi_assert(bp->refCount == 0);
696     osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)));
697     lock_AssertWrite(&buf_globalLock);
698
699     if (bp->flags & CM_BUF_INHASH) {
700         /* Remove from hash */
701
702         i = BUF_HASH(&bp->fid, &bp->offset);
703         lbpp = &(buf_hashTablepp[i]);
704         for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
705             if (tbp == bp) break;
706         }
707
708         /* we better find it */
709         osi_assertx(tbp != NULL, "buf_GetNewLocked: hash table screwup");
710
711         *lbpp = bp->hashp;      /* hash out */
712
713         /* Remove from file hash */
714
715         i = BUF_FILEHASH(&bp->fid);
716         prevBp = bp->fileHashBackp;
717         nextBp = bp->fileHashp;
718         if (prevBp)
719             prevBp->fileHashp = nextBp;
720         else
721             buf_fileHashTablepp[i] = nextBp;
722         if (nextBp)
723             nextBp->fileHashBackp = prevBp;
724
725         bp->flags &= ~CM_BUF_INHASH;
726     }
727
728     /* bump the soft reference counter now, to invalidate softRefs; no
729      * wakeup is required since people don't sleep waiting for this
730      * counter to change.
731      */
732     bp->idCounter++;
733
734     /* make the fid unrecognizable */
735     memset(&bp->fid, 0, sizeof(bp->fid));
736 }       
737
738 /* recycle a buffer, removing it from the free list, hashing in its new identity
739  * and returning it write-locked so that no one can use it.  Called without
740  * any locks held, and can return an error if it loses the race condition and 
741  * finds that someone else created the desired buffer.
742  *
743  * If success is returned, the buffer is returned write-locked.
744  *
745  * May be called with null scp and offsetp, if we're just trying to reclaim some
746  * space from the buffer pool.  In that case, the buffer will be returned
747  * without being hashed into the hash table.
748  */
749 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
750 {
751     cm_buf_t *bp;               /* buffer we're dealing with */
752     cm_buf_t *nextBp;   /* next buffer in file hash chain */
753     long i;                     /* temp */
754     cm_req_t req;
755
756     cm_InitReq(&req);   /* just in case */
757
758     while(1) {
759       retry:
760         lock_ObtainWrite(&buf_globalLock);
761         /* check to see if we lost the race */
762         if (scp) {
763             if (bp = buf_LockedFind(scp, offsetp)) {
764                 bp->refCount--;
765                 lock_ReleaseWrite(&buf_globalLock);
766                 return CM_BUF_EXISTS;
767             }
768         }
769
770         /* for debugging, assert free list isn't empty, although we
771          * really should try waiting for a running tranasction to finish
772          * instead of this; or better, we should have a transaction
773          * throttler prevent us from entering this situation.
774          */
775         osi_assertx(buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
776
777         /* look at all buffers in free list, some of which may temp.
778          * have high refcounts and which then should be skipped,
779          * starting cleaning I/O for those which are dirty.  If we find
780          * a clean buffer, we rehash it, lock it and return it.
781          */
782         for(bp = buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
783             /* check to see if it really has zero ref count.  This
784              * code can bump refcounts, at least, so it may not be
785              * zero.
786              */
787             if (bp->refCount > 0) 
788                 continue;
789                         
790             /* we don't have to lock buffer itself, since the ref
791              * count is 0 and we know it will stay zero as long as
792              * we hold the global lock.
793              */
794
795             /* don't recycle someone in our own chunk */
796             if (!cm_FidCmp(&bp->fid, &scp->fid)
797                  && (bp->offset.LowPart & (-cm_chunkSize))
798                  == (offsetp->LowPart & (-cm_chunkSize)))
799                 continue;
800
801             /* if this page is being filled (!) or cleaned, see if
802              * the I/O has completed.  If not, skip it, otherwise
803              * do the final processing for the I/O.
804              */
805             if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
806                 /* probably shouldn't do this much work while
807                  * holding the big lock?  Watch for contention
808                  * here.
809                  */
810                 continue;
811             }
812                         
813             if (bp->flags & CM_BUF_DIRTY) {
814                 /* if the buffer is dirty, start cleaning it and
815                  * move on to the next buffer.  We do this with
816                  * just the lock required to minimize contention
817                  * on the big lock.
818                  */
819                 bp->refCount++;
820                 lock_ReleaseWrite(&buf_globalLock);
821
822                 /* grab required lock and clean; this only
823                  * starts the I/O.  By the time we're back,
824                  * it'll still be marked dirty, but it will also
825                  * have the WRITING flag set, so we won't get
826                  * back here.
827                  */
828                 buf_CleanAsync(bp, &req);
829
830                 /* now put it back and go around again */
831                 buf_Release(bp);
832                 goto retry;
833             }
834
835             /* if we get here, we know that the buffer still has a 0
836              * ref count, and that it is clean and has no currently
837              * pending I/O.  This is the dude to return.
838              * Remember that as long as the ref count is 0, we know
839              * that we won't have any lock conflicts, so we can grab
840              * the buffer lock out of order in the locking hierarchy.
841              */
842             buf_Recycle(bp);
843
844             /* clean up junk flags */
845             bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
846             bp->dataVersion = -1;       /* unknown so far */
847
848             /* now hash in as our new buffer, and give it the
849              * appropriate label, if requested.
850              */
851             if (scp) {
852                 bp->flags |= CM_BUF_INHASH;
853                 bp->fid = scp->fid;
854                 bp->offset = *offsetp;
855                 i = BUF_HASH(&scp->fid, offsetp);
856                 bp->hashp = buf_hashTablepp[i];
857                 buf_hashTablepp[i] = bp;
858                 i = BUF_FILEHASH(&scp->fid);
859                 nextBp = buf_fileHashTablepp[i];
860                 bp->fileHashp = nextBp;
861                 bp->fileHashBackp = NULL;
862                 if (nextBp)
863                     nextBp->fileHashBackp = bp;
864                 buf_fileHashTablepp[i] = bp;
865             }
866
867             /* prepare to return it.  Start by giving it a good
868              * refcount */
869             bp->refCount = 1;
870                         
871             /* and since it has a non-zero ref count, we should move
872              * it from the lru queue.  It better be still there,
873              * since we've held the global (big) lock since we found
874              * it there.
875              */
876             osi_assertx(bp->flags & CM_BUF_INLRU,
877                          "buf_GetNewLocked: LRU screwup");
878             if (buf_freeListEndp == bp) {
879                 /* we're the last guy in this queue, so maintain it */
880                 buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
881             }
882             osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
883             bp->flags &= ~CM_BUF_INLRU;
884
885             /* finally, grab the mutex so that people don't use it
886              * before the caller fills it with data.  Again, no one     
887              * should have been able to get to this dude to lock it.
888              */
889             osi_assertx(lock_TryMutex(&bp->mx),
890                          "buf_GetNewLocked: TryMutex failed");
891
892             lock_ReleaseWrite(&buf_globalLock);
893             *bufpp = bp;
894             return 0;
895         } /* for all buffers in lru queue */
896         lock_ReleaseWrite(&buf_globalLock);
897     }   /* while loop over everything */
898     /* not reached */
899 } /* the proc */
900
901 /* get a page, returning it held but unlocked.  Doesn't fill in the page
902  * with I/O, since we're going to write the whole thing new.
903  */
904 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
905 {
906     cm_buf_t *bp;
907     long code;
908     osi_hyper_t pageOffset;
909     int created;
910
911     created = 0;
912     pageOffset.HighPart = offsetp->HighPart;
913     pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
914     while (1) {
915         lock_ObtainWrite(&buf_globalLock);
916         bp = buf_LockedFind(scp, &pageOffset);
917         lock_ReleaseWrite(&buf_globalLock);
918         if (bp) {
919             /* lock it and break out */
920             lock_ObtainMutex(&bp->mx);
921             break;
922         }
923
924         /* otherwise, we have to create a page */
925         code = buf_GetNewLocked(scp, &pageOffset, &bp);
926
927         /* check if the buffer was created in a race condition branch.
928          * If so, go around so we can hold a reference to it. 
929          */
930         if (code == CM_BUF_EXISTS) 
931             continue;
932
933         /* something else went wrong */
934         if (code != 0) 
935             return code;
936
937         /* otherwise, we have a locked buffer that we just created */
938         created = 1;
939         break;
940     } /* big while loop */
941
942     /* wait for reads */
943     if (bp->flags & CM_BUF_READING)
944         buf_WaitIO(bp);
945
946     /* once it has been read once, we can unlock it and return it, still
947      * with its refcount held.
948      */
949     lock_ReleaseMutex(&bp->mx);
950     *bufpp = bp;
951     osi_Log3(buf_logp, "buf_GetNew returning bp 0x%x for file 0x%x, offset 0x%x",
952               bp, (long) scp, offsetp->LowPart);
953     return 0;
954 }
955
956 /* get a page, returning it held but unlocked.  Make sure it is complete */
957 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
958 {
959     cm_buf_t *bp;
960     long code;
961     osi_hyper_t pageOffset;
962     unsigned long tcount;
963     int created;
964 #ifdef DISKCACHE95
965     cm_diskcache_t *dcp;
966 #endif /* DISKCACHE95 */
967
968     created = 0;
969     pageOffset.HighPart = offsetp->HighPart;
970     pageOffset.LowPart = offsetp->LowPart & ~(buf_bufferSize-1);
971     while (1) {
972         lock_ObtainWrite(&buf_globalLock);
973         bp = buf_LockedFind(scp, &pageOffset);
974         lock_ReleaseWrite(&buf_globalLock);
975         if (bp) {
976             /* lock it and break out */
977             lock_ObtainMutex(&bp->mx);
978             break;
979
980 #ifdef DISKCACHE95
981             /* touch disk chunk to update LRU info */
982             diskcache_Touch(bp->dcp);
983 #endif /* DISKCACHE95 */
984         }
985
986         /* otherwise, we have to create a page */
987         code = buf_GetNewLocked(scp, &pageOffset, &bp);
988
989         /* check if the buffer was created in a race condition branch.
990          * If so, go around so we can hold a reference to it. 
991          */
992         if (code == CM_BUF_EXISTS) 
993             continue;
994
995         /* something else went wrong */
996         if (code != 0) 
997             return code;
998                 
999         /* otherwise, we have a locked buffer that we just created */
1000         created = 1;
1001         break;
1002     } /* big while loop */
1003
1004     /* if we get here, we have a locked buffer that may have just been
1005      * created, in which case it needs to be filled with data.
1006      */
1007     if (created) {
1008         /* load the page; freshly created pages should be idle */
1009         osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
1010
1011         /* setup offset, event */
1012 #ifndef DJGPP  /* doesn't seem to be used */
1013         bp->over.Offset = bp->offset.LowPart;
1014         bp->over.OffsetHigh = bp->offset.HighPart;
1015 #endif /* !DJGPP */
1016
1017         /* start the I/O; may drop lock */
1018         bp->flags |= CM_BUF_READING;
1019         code = (*cm_buf_opsp->Readp)(bp, buf_bufferSize, &tcount, NULL);
1020
1021 #ifdef DISKCACHE95
1022         code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, buf_bufferSize, &bp->dataVersion, &tcount, &dcp);
1023         bp->dcp = dcp;    /* pointer to disk cache struct. */
1024 #endif /* DISKCACHE95 */
1025
1026         if (code != 0) {
1027             /* failure or queued */
1028 #ifndef DJGPP   /* cm_bufRead always returns 0 */
1029             if (code != ERROR_IO_PENDING) {
1030 #endif
1031                 bp->error = code;
1032                 bp->flags |= CM_BUF_ERROR;
1033                 bp->flags &= ~CM_BUF_READING;
1034                 if (bp->flags & CM_BUF_WAITING) {
1035                     bp->flags &= ~CM_BUF_WAITING;
1036                     osi_Wakeup((long) bp);
1037                 }
1038                 lock_ReleaseMutex(&bp->mx);
1039                 buf_Release(bp);
1040                 return code;
1041 #ifndef DJGPP
1042             }
1043 #endif
1044         } else {
1045             /* otherwise, I/O completed instantly and we're done, except
1046              * for padding the xfr out with 0s and checking for EOF
1047              */
1048             if (tcount < (unsigned long) buf_bufferSize) {
1049                 memset(bp->datap+tcount, 0, buf_bufferSize - tcount);
1050                 if (tcount == 0)
1051                     bp->flags |= CM_BUF_EOF;
1052             }
1053             bp->flags &= ~CM_BUF_READING;
1054             if (bp->flags & CM_BUF_WAITING) {
1055                 bp->flags &= ~CM_BUF_WAITING;
1056                 osi_Wakeup((long) bp);
1057             }
1058         }
1059
1060     } /* if created */
1061
1062     /* wait for reads, either that which we started above, or that someone
1063      * else started.  We don't care if we return a buffer being cleaned.
1064      */
1065     if (bp->flags & CM_BUF_READING)
1066         buf_WaitIO(bp);
1067
1068     /* once it has been read once, we can unlock it and return it, still
1069      * with its refcount held.
1070      */
1071     lock_ReleaseMutex(&bp->mx);
1072     *bufpp = bp;
1073
1074     /* now remove from queue; will be put in at the head (farthest from
1075      * being recycled) when we're done in buf_Release.
1076      */
1077     lock_ObtainWrite(&buf_globalLock);
1078     if (bp->flags & CM_BUF_INLRU) {
1079         if (buf_freeListEndp == bp)
1080             buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1081         osi_QRemove((osi_queue_t **) &buf_freeListp, &bp->q);
1082         bp->flags &= ~CM_BUF_INLRU;
1083     }
1084     lock_ReleaseWrite(&buf_globalLock);
1085
1086     osi_Log3(buf_logp, "buf_Get returning bp 0x%x for file 0x%x, offset 0x%x",
1087               bp, (long) scp, offsetp->LowPart);
1088     return 0;
1089 }
1090
1091 /* count # of elements in the free list;
1092  * we don't bother doing the proper locking for accessing dataVersion or flags
1093  * since it is a pain, and this is really just an advisory call.  If you need
1094  * to do better at some point, rewrite this function.
1095  */
1096 long buf_CountFreeList(void)
1097 {
1098     long count;
1099     cm_buf_t *bufp;
1100
1101     count = 0;
1102     lock_ObtainRead(&buf_globalLock);
1103     for(bufp = buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1104         /* if the buffer doesn't have an identity, or if the buffer
1105          * has been invalidate (by having its DV stomped upon), then
1106          * count it as free, since it isn't really being utilized.
1107          */
1108         if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1109             count++;
1110     }       
1111     lock_ReleaseRead(&buf_globalLock);
1112     return count;
1113 }
1114
1115 /* clean a buffer synchronously */
1116 void buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1117 {
1118     lock_ObtainMutex(&bp->mx);
1119     buf_LockedCleanAsync(bp, reqp);
1120     lock_ReleaseMutex(&bp->mx);
1121 }       
1122
1123 /* wait for a buffer's cleaning to finish */
1124 void buf_CleanWait(cm_buf_t *bp)
1125 {
1126     lock_ObtainMutex(&bp->mx);
1127     if (bp->flags & CM_BUF_WRITING) {
1128         buf_WaitIO(bp);
1129     }
1130     lock_ReleaseMutex(&bp->mx);
1131 }       
1132
1133 /* set the dirty flag on a buffer, and set associated write-ahead log,
1134  * if there is one.  Allow one to be added to a buffer, but not changed.
1135  *
1136  * The buffer must be locked before calling this routine.
1137  */
1138 void buf_SetDirty(cm_buf_t *bp)
1139 {
1140     osi_assert(bp->refCount > 0);
1141         
1142     osi_Log1(buf_logp, "buf_SetDirty 0x%x", bp);
1143
1144     /* set dirty bit */
1145     bp->flags |= CM_BUF_DIRTY;
1146
1147     /* and turn off EOF flag, since it has associated data now */
1148     bp->flags &= ~CM_BUF_EOF;
1149 }
1150
1151 /* clean all buffers, reset log pointers and invalidate all buffers.
1152  * Called with no locks held, and returns with same.
1153  *
1154  * This function is guaranteed to clean and remove the log ptr of all the
1155  * buffers that were dirty or had non-zero log ptrs before the call was
1156  * made.  That's sufficient to clean up any garbage left around by recovery,
1157  * which is all we're counting on this for; there may be newly created buffers
1158  * added while we're running, but that should be OK.
1159  *
1160  * In an environment where there are no transactions (artificially imposed, for
1161  * example, when switching the database to raw mode), this function is used to
1162  * make sure that all updates have been written to the disk.  In that case, we don't
1163  * really require that we forget the log association between pages and logs, but
1164  * it also doesn't hurt.  Since raw mode I/O goes through this buffer package, we don't
1165  * have to worry about invalidating data in the buffers.
1166  *
1167  * This function is used at the end of recovery as paranoia to get the recovered
1168  * database out to disk.  It removes all references to the recovery log and cleans
1169  * all buffers.
1170  */
1171 long buf_CleanAndReset(void)
1172 {
1173     long i;
1174     cm_buf_t *bp;
1175     cm_req_t req;
1176
1177     lock_ObtainWrite(&buf_globalLock);
1178     for(i=0; i<buf_hashSize; i++) {
1179         for(bp = buf_hashTablepp[i]; bp; bp = bp->hashp) {
1180             bp->refCount++;
1181             lock_ReleaseWrite(&buf_globalLock);
1182
1183             /* now no locks are held; clean buffer and go on */
1184             cm_InitReq(&req);
1185             buf_CleanAsync(bp, &req);
1186             buf_CleanWait(bp);
1187
1188             /* relock and release buffer */
1189             lock_ObtainWrite(&buf_globalLock);
1190             buf_LockedRelease(bp);
1191         } /* over one bucket */
1192     }   /* for loop over all hash buckets */
1193
1194     /* release locks */
1195     lock_ReleaseWrite(&buf_globalLock);
1196
1197     /* and we're done */
1198     return 0;
1199 }       
1200
1201 /* called without global lock being held, reserves buffers for callers
1202  * that need more than one held (not locked) at once.
1203  */
1204 void buf_ReserveBuffers(long nbuffers)
1205 {
1206     lock_ObtainWrite(&buf_globalLock);
1207     while (1) {
1208         if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1209             buf_reserveWaiting = 1;
1210             osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1211             osi_SleepW((long) &buf_reservedBufs, &buf_globalLock);
1212             lock_ObtainWrite(&buf_globalLock);
1213         }
1214         else {
1215             buf_reservedBufs += nbuffers;
1216             break;
1217         }
1218     }
1219     lock_ReleaseWrite(&buf_globalLock);
1220 }
1221
1222 int buf_TryReserveBuffers(long nbuffers)
1223 {
1224     int code;
1225
1226     lock_ObtainWrite(&buf_globalLock);
1227     if (buf_reservedBufs + nbuffers > buf_maxReservedBufs) {
1228         code = 0;
1229     }
1230     else {
1231         buf_reservedBufs += nbuffers;
1232         code = 1;
1233     }
1234     lock_ReleaseWrite(&buf_globalLock);
1235     return code;
1236 }       
1237
1238 /* called without global lock held, releases reservation held by
1239  * buf_ReserveBuffers.
1240  */
1241 void buf_UnreserveBuffers(long nbuffers)
1242 {
1243     lock_ObtainWrite(&buf_globalLock);
1244     buf_reservedBufs -= nbuffers;
1245     if (buf_reserveWaiting) {
1246         buf_reserveWaiting = 0;
1247         osi_Wakeup((long) &buf_reservedBufs);
1248     }
1249     lock_ReleaseWrite(&buf_globalLock);
1250 }       
1251
1252 /* truncate the buffers past sizep, zeroing out the page, if we don't
1253  * end on a page boundary.
1254  *
1255  * Requires cm_bufCreateLock to be write locked.
1256  */
1257 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1258                    osi_hyper_t *sizep)
1259 {
1260     cm_buf_t *bufp;
1261     cm_buf_t *nbufp;                    /* next buffer, if didRelease */
1262     osi_hyper_t bufEnd;
1263     long code;
1264     long bufferPos;
1265     int didRelease;
1266     long i;
1267
1268     /* assert that cm_bufCreateLock is held in write mode */
1269     lock_AssertWrite(&scp->bufCreateLock);
1270
1271     i = BUF_FILEHASH(&scp->fid);
1272
1273     lock_ObtainWrite(&buf_globalLock);
1274     bufp = buf_fileHashTablepp[i];
1275     if (bufp == NULL) {
1276         lock_ReleaseWrite(&buf_globalLock);
1277         return 0;
1278     }
1279
1280     bufp->refCount++;
1281     lock_ReleaseWrite(&buf_globalLock);
1282     for(; bufp; bufp = nbufp) {
1283         didRelease = 0;
1284         lock_ObtainMutex(&bufp->mx);
1285
1286         bufEnd.HighPart = 0;
1287         bufEnd.LowPart = buf_bufferSize;
1288         bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1289
1290         if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1291              LargeIntegerLessThan(*sizep, bufEnd)) {
1292             buf_WaitIO(bufp);
1293         }
1294         lock_ObtainMutex(&scp->mx);
1295         
1296         /* make sure we have a callback (so we have the right value for
1297          * the length), and wait for it to be safe to do a truncate.
1298          */
1299         code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1300                           CM_SCACHESYNC_NEEDCALLBACK
1301                           | CM_SCACHESYNC_GETSTATUS
1302                           | CM_SCACHESYNC_SETSIZE
1303                           | CM_SCACHESYNC_BUFLOCKED);
1304         /* if we succeeded in our locking, and this applies to the right
1305          * file, and the truncate request overlaps the buffer either
1306          * totally or partially, then do something.
1307          */
1308         if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1309              && LargeIntegerLessThan(*sizep, bufEnd)) {
1310
1311             lock_ObtainWrite(&buf_globalLock);
1312
1313             /* destroy the buffer, turning off its dirty bit, if
1314              * we're truncating the whole buffer.  Otherwise, set
1315              * the dirty bit, and clear out the tail of the buffer
1316              * if we just overlap some.
1317              */
1318             if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1319                 /* truncating the entire page */
1320                 bufp->flags &= ~CM_BUF_DIRTY;
1321                 bufp->dataVersion = -1; /* known bad */
1322                 bufp->dirtyCounter++;
1323             }
1324             else {
1325                 /* don't set dirty, since dirty implies
1326                  * currently up-to-date.  Don't need to do this,
1327                  * since we'll update the length anyway.
1328                  *
1329                  * Zero out remainder of the page, in case we
1330                  * seek and write past EOF, and make this data
1331                  * visible again.
1332                  */
1333                 bufferPos = sizep->LowPart & (buf_bufferSize - 1);
1334                 osi_assert(bufferPos != 0);
1335                 memset(bufp->datap + bufferPos, 0,
1336                         buf_bufferSize - bufferPos);
1337             }
1338
1339             lock_ReleaseWrite(&buf_globalLock);
1340         }
1341                 
1342         lock_ReleaseMutex(&scp->mx);
1343         lock_ReleaseMutex(&bufp->mx);
1344         if (!didRelease) {
1345             lock_ObtainWrite(&buf_globalLock);
1346             nbufp = bufp->fileHashp;
1347             if (nbufp) nbufp->refCount++;
1348             buf_LockedRelease(bufp);
1349             lock_ReleaseWrite(&buf_globalLock);
1350         }
1351
1352         /* bail out early if we fail */
1353         if (code) {
1354             /* at this point, nbufp is held; bufp has already been
1355              * released.
1356              */
1357             if (nbufp) 
1358                 buf_Release(nbufp);
1359             return code;
1360         }
1361     }
1362
1363     /* success */
1364     return 0;
1365 }
1366
1367 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1368 {
1369     long code;
1370     cm_buf_t *bp;               /* buffer we're hacking on */
1371     cm_buf_t *nbp;
1372     int didRelease;
1373     long i;
1374
1375     i = BUF_FILEHASH(&scp->fid);
1376
1377     code = 0;
1378     lock_ObtainWrite(&buf_globalLock);
1379     bp = buf_fileHashTablepp[i];
1380     if (bp) bp->refCount++;
1381     lock_ReleaseWrite(&buf_globalLock);
1382     for(; bp; bp = nbp) {
1383         didRelease = 0; /* haven't released this buffer yet */
1384
1385         /* clean buffer synchronously */
1386         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1387             lock_ObtainMutex(&bp->mx);
1388
1389             /* start cleaning the buffer, and wait for it to finish */
1390             buf_LockedCleanAsync(bp, reqp);
1391             buf_WaitIO(bp);
1392             lock_ReleaseMutex(&bp->mx);
1393
1394             code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1395             if (code) goto skip;
1396
1397             lock_ObtainWrite(&buf_globalLock);
1398             /* actually, we only know that buffer is clean if ref
1399              * count is 1, since we don't have buffer itself locked.
1400              */
1401             if (!(bp->flags & CM_BUF_DIRTY)) {
1402                 if (bp->refCount == 1) {        /* bp is held above */
1403                     buf_LockedRelease(bp);
1404                     nbp = bp->fileHashp;
1405                     if (nbp) nbp->refCount++;
1406                     didRelease = 1;
1407                     buf_Recycle(bp);
1408                 }
1409             }
1410             lock_ReleaseWrite(&buf_globalLock);
1411
1412             (*cm_buf_opsp->Unstabilizep)(scp, userp);
1413         }
1414
1415       skip:
1416         if (!didRelease) {
1417             lock_ObtainWrite(&buf_globalLock);
1418             if (nbp = bp->fileHashp) nbp->refCount++;
1419             buf_LockedRelease(bp);
1420             lock_ReleaseWrite(&buf_globalLock);
1421         }
1422     }   /* for loop over a bunch of buffers */
1423
1424     /* done */
1425     return code;
1426 }       
1427
1428 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1429 {
1430     long code;
1431     cm_buf_t *bp;               /* buffer we're hacking on */
1432     cm_buf_t *nbp;              /* next one */
1433     long i;
1434
1435     i = BUF_FILEHASH(&scp->fid);
1436
1437     code = 0;
1438     lock_ObtainWrite(&buf_globalLock);
1439     bp = buf_fileHashTablepp[i];
1440     if (bp) bp->refCount++;
1441     lock_ReleaseWrite(&buf_globalLock);
1442     for(; bp; bp = nbp) {
1443         /* clean buffer synchronously */
1444         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1445             if (userp) {
1446                 cm_HoldUser(userp);
1447                 lock_ObtainMutex(&bp->mx);
1448                 if (bp->userp) 
1449                     cm_ReleaseUser(bp->userp);
1450                 bp->userp = userp;
1451                 lock_ReleaseMutex(&bp->mx);
1452             }   
1453             buf_CleanAsync(bp, reqp);
1454             buf_CleanWait(bp);
1455             lock_ObtainMutex(&bp->mx);
1456             if (bp->flags & CM_BUF_ERROR) {
1457                 if (code == 0 || code == -1) 
1458                     code = bp->error;
1459                 if (code == 0) 
1460                     code = -1;
1461             }
1462             lock_ReleaseMutex(&bp->mx);
1463         }
1464
1465         lock_ObtainWrite(&buf_globalLock);
1466         buf_LockedRelease(bp);
1467         nbp = bp->fileHashp;
1468         if (nbp) nbp->refCount++;
1469         lock_ReleaseWrite(&buf_globalLock);
1470     }   /* for loop over a bunch of buffers */
1471
1472     /* done */
1473     return code;
1474 }
1475
1476 /* dump the contents of the buf_hashTablepp. */
1477 int cm_DumpBufHashTable(FILE *outputFile, char *cookie)
1478 {
1479     int zilch;
1480     cm_buf_t *bp;
1481     char output[1024];
1482     int i;
1483   
1484     if (buf_hashTablepp == NULL)
1485         return -1;
1486
1487     lock_ObtainRead(&buf_globalLock);
1488   
1489     StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\n", cookie, buf_hashSize);
1490     WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1491   
1492     for (i = 0; i < buf_hashSize; i++)
1493     {
1494         for (bp = buf_hashTablepp[i]; bp; bp=bp->hashp) 
1495         {
1496             if (bp->refCount)
1497             {
1498                 StringCbPrintfA(output, sizeof(output), "vnode=%d, unique=%d), size=%d refCount=%d\n", 
1499                         cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume, 
1500                         bp->fid.vnode, bp->fid.unique, bp->size, bp->refCount);
1501                 WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1502             }
1503         }
1504     }
1505   
1506     StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\n", cookie);
1507     WriteFile(outputFile, output, strlen(output), &zilch, NULL);
1508
1509     lock_ReleaseRead(&buf_globalLock);
1510     return 0;
1511 }
1512
1513 void buf_ForceTrace(BOOL flush)
1514 {
1515     HANDLE handle;
1516     int len;
1517     char buf[256];
1518
1519     if (!buf_logp) 
1520         return;
1521
1522     len = GetTempPath(sizeof(buf)-10, buf);
1523     StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
1524     handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
1525                             NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1526     if (handle == INVALID_HANDLE_VALUE) {
1527         osi_panic("Cannot create log file", __FILE__, __LINE__);
1528     }
1529     osi_LogPrint(buf_logp, handle);
1530     if (flush)
1531         FlushFileBuffers(handle);
1532     CloseHandle(handle);
1533 }