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