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