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