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