windows-buf-clean-error-handling-20080731
[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 #ifdef DEBUG_REFCOUNT
91 void buf_HoldLockedDbg(cm_buf_t *bp, char *file, long line)
92 #else
93 void buf_HoldLocked(cm_buf_t *bp)
94 #endif
95 {
96     afs_int32 refCount;
97
98     osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
99     refCount = InterlockedIncrement(&bp->refCount);
100 #ifdef DEBUG_REFCOUNT
101     osi_Log2(afsd_logp,"buf_HoldLocked bp 0x%p ref %d",bp, refCount);
102     afsi_log("%s:%d buf_HoldLocked bp 0x%p, ref %d", file, line, bp, refCount);
103 #endif
104 }
105
106 /* hold a reference to an already held buffer */
107 #ifdef DEBUG_REFCOUNT
108 void buf_HoldDbg(cm_buf_t *bp, char *file, long line)
109 #else
110 void buf_Hold(cm_buf_t *bp)
111 #endif
112 {
113     afs_int32 refCount;
114
115     lock_ObtainRead(&buf_globalLock);
116     osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
117     refCount = InterlockedIncrement(&bp->refCount);
118 #ifdef DEBUG_REFCOUNT
119     osi_Log2(afsd_logp,"buf_Hold bp 0x%p ref %d",bp, refCount);
120     afsi_log("%s:%d buf_Hold bp 0x%p, ref %d", file, line, bp, refCount);
121 #endif
122     lock_ReleaseRead(&buf_globalLock);
123 }
124
125 /* code to drop reference count while holding buf_globalLock */
126 #ifdef DEBUG_REFCOUNT
127 void buf_ReleaseLockedDbg(cm_buf_t *bp, afs_uint32 writeLocked, char *file, long line)
128 #else
129 void buf_ReleaseLocked(cm_buf_t *bp, afs_uint32 writeLocked)
130 #endif
131 {
132     afs_int32 refCount;
133
134     if (writeLocked)
135         lock_AssertWrite(&buf_globalLock);
136     else
137         lock_AssertRead(&buf_globalLock);
138
139     /* ensure that we're in the LRU queue if our ref count is 0 */
140     osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
141
142     refCount = InterlockedDecrement(&bp->refCount);
143 #ifdef DEBUG_REFCOUNT
144     osi_Log3(afsd_logp,"buf_ReleaseLocked %s bp 0x%p ref %d",writeLocked?"write":"read", bp, refCount);
145     afsi_log("%s:%d buf_ReleaseLocked %s bp 0x%p, ref %d", file, line, writeLocked?"write":"read", bp, refCount);
146 #endif
147 #ifdef DEBUG
148     if (refCount < 0)
149         osi_panic("buf refcount 0",__FILE__,__LINE__);;
150 #else
151     osi_assertx(refCount >= 0, "cm_buf_t refCount == 0");
152 #endif
153     if (refCount == 0) {
154         /* 
155          * If we are read locked there could be a race condition
156          * with buf_Find() so we must obtain a write lock and
157          * double check that the refCount is actually zero
158          * before we remove the buffer from the LRU queue.
159          */
160         if (!writeLocked)
161             lock_ConvertRToW(&buf_globalLock);
162
163         if (bp->refCount == 0 &&
164             !(bp->flags & CM_BUF_INLRU)) {
165             osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
166
167             /* watch for transition from empty to one element */
168             if (!cm_data.buf_freeListEndp)
169                 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
170             bp->flags |= CM_BUF_INLRU;
171         }
172
173         if (!writeLocked)
174             lock_ConvertWToR(&buf_globalLock);
175     }
176 }       
177
178 /* release a buffer.  Buffer must be referenced, but unlocked. */
179 #ifdef DEBUG_REFCOUNT
180 void buf_ReleaseDbg(cm_buf_t *bp, char *file, long line)
181 #else
182 void buf_Release(cm_buf_t *bp)
183 #endif
184 {
185     afs_int32 refCount;
186
187     /* ensure that we're in the LRU queue if our ref count is 0 */
188     osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
189
190     refCount = InterlockedDecrement(&bp->refCount);
191 #ifdef DEBUG_REFCOUNT
192     osi_Log2(afsd_logp,"buf_Release bp 0x%p ref %d", bp, refCount);
193     afsi_log("%s:%d buf_ReleaseLocked bp 0x%p, ref %d", file, line, bp, refCount);
194 #endif
195 #ifdef DEBUG
196     if (refCount < 0)
197         osi_panic("buf refcount 0",__FILE__,__LINE__);;
198 #else
199     osi_assertx(refCount >= 0, "cm_buf_t refCount == 0");
200 #endif
201     if (refCount == 0) {
202         lock_ObtainWrite(&buf_globalLock);
203         if (bp->refCount == 0 && 
204             !(bp->flags & CM_BUF_INLRU)) {
205             osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
206
207             /* watch for transition from empty to one element */
208             if (!cm_data.buf_freeListEndp)
209                 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
210             bp->flags |= CM_BUF_INLRU;
211         }
212         lock_ReleaseWrite(&buf_globalLock);
213     }
214 }
215
216 /* incremental sync daemon.  Writes all dirty buffers every 5000 ms */
217 void buf_IncrSyncer(long parm)
218 {
219     cm_buf_t **bpp, *bp, *prevbp;
220     long i;                             /* counter */
221     long wasDirty = 0;
222     cm_req_t req;
223
224     while (buf_ShutdownFlag == 0) {
225         if (!wasDirty) {
226             i = SleepEx(5000, 1);
227             if (i != 0) continue;
228         }
229
230         wasDirty = 0;
231
232         /* go through all of the dirty buffers */
233         lock_ObtainRead(&buf_globalLock);
234         for (bpp = &cm_data.buf_dirtyListp, prevbp = NULL; bp = *bpp; ) {
235             lock_ReleaseRead(&buf_globalLock);
236             /* all dirty buffers are held when they are added to the
237              * dirty list.  No need for an additional hold.
238              */
239             lock_ObtainMutex(&bp->mx);
240
241             if (bp->flags & CM_BUF_DIRTY) {
242                 /* start cleaning the buffer; don't touch log pages since
243                  * the log code counts on knowing exactly who is writing
244                  * a log page at any given instant.
245                  */
246                 cm_InitReq(&req);
247                 req.flags |= CM_REQ_NORETRY;
248                 wasDirty |= buf_CleanAsyncLocked(bp, &req);
249             }
250
251             /* the buffer may or may not have been dirty
252              * and if dirty may or may not have been cleaned
253              * successfully.  check the dirty flag again.  
254              */
255             if (!(bp->flags & CM_BUF_DIRTY)) {
256                 /* remove the buffer from the dirty list */
257                 lock_ObtainWrite(&buf_globalLock);
258 #ifdef DEBUG_REFCOUNT
259                 if (bp->dirtyp == NULL && bp != cm_data.buf_dirtyListEndp) {
260                     osi_Log1(afsd_logp,"buf_IncrSyncer bp 0x%p list corruption",bp);
261                     afsi_log("buf_IncrSyncer bp 0x%p list corruption", bp);
262                 }
263 #endif
264                 *bpp = bp->dirtyp;
265                 bp->dirtyp = NULL;
266                 bp->flags &= ~CM_BUF_INDL;
267                 if (cm_data.buf_dirtyListp == NULL)
268                     cm_data.buf_dirtyListEndp = NULL;
269                 else if (cm_data.buf_dirtyListEndp == bp)
270                     cm_data.buf_dirtyListEndp = prevbp;
271                 buf_ReleaseLocked(bp, TRUE);
272                 lock_ConvertWToR(&buf_globalLock);
273             } else {
274                 /* advance the pointer so we don't loop forever */
275                 lock_ObtainRead(&buf_globalLock);
276                 bpp = &bp->dirtyp;
277                 prevbp = bp;
278             }
279             lock_ReleaseMutex(&bp->mx);
280         }       /* for loop over a bunch of buffers */
281         lock_ReleaseRead(&buf_globalLock);
282     }           /* whole daemon's while loop */
283 }
284
285 long
286 buf_ValidateBuffers(void)
287 {
288     cm_buf_t * bp, *bpf, *bpa, *bpb;
289     afs_uint64 countb = 0, countf = 0, counta = 0;
290
291     if (cm_data.buf_freeListp == NULL && cm_data.buf_freeListEndp != NULL ||
292          cm_data.buf_freeListp != NULL && cm_data.buf_freeListEndp == NULL) {
293         afsi_log("cm_ValidateBuffers failure: inconsistent free list pointers");
294         fprintf(stderr, "cm_ValidateBuffers failure: inconsistent free list pointers\n");
295         return -9;                  
296     }
297
298     for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) { 
299         if (bp->magic != CM_BUF_MAGIC) {
300             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
301             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
302             return -1;                  
303         }
304         countb++;                                                                
305         bpb = bp;     
306
307         if (countb > cm_data.buf_nbuffers) {
308             afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
309             fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
310             return -6;                   
311         }
312     }
313
314     for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) { 
315         if (bp->magic != CM_BUF_MAGIC) {
316             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
317             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
318             return -2;                  
319         }
320         countf++;                                                             
321         bpf = bp;    
322
323         if (countf > cm_data.buf_nbuffers) {
324             afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
325             fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
326             return -7;
327         }
328     }                                                                         
329                                                                               
330     for (bp = cm_data.buf_allp; bp; bp=bp->allp) {                            
331         if (bp->magic != CM_BUF_MAGIC) {
332             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
333             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
334             return -3;                  
335         }
336         counta++;                                                             
337         bpa = bp;                                                             
338
339         if (counta > cm_data.buf_nbuffers) {
340             afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
341             fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
342             return -8;                   
343         }
344     }                                                                         
345                                                                               
346     if (countb != countf) {
347         afsi_log("cm_ValidateBuffers failure: countb != countf");
348         fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
349         return -4;         
350     }
351                                                                               
352     if (counta != cm_data.buf_nbuffers) {
353         afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
354         fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
355         return -5;                       
356     }
357                                                                               
358     return 0;                                                                 
359 }
360
361 void buf_Shutdown(void)  
362 {                        
363     buf_ShutdownFlag = 1;
364 }                        
365
366 /* initialize the buffer package; called with no locks
367  * held during the initialization phase.
368  */
369 long buf_Init(int newFile, cm_buf_ops_t *opsp, afs_uint64 nbuffers)
370 {
371     static osi_once_t once;
372     cm_buf_t *bp;
373     thread_t phandle;
374     long i;
375     unsigned long pid;
376     char *data;
377
378     if ( newFile ) {
379         if (nbuffers) 
380             cm_data.buf_nbuffers = nbuffers;
381
382         /* Have to be able to reserve a whole chunk */
383         if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
384             return CM_ERROR_TOOFEWBUFS;
385     }
386
387     /* recall for callouts */
388     cm_buf_opsp = opsp;
389
390     if (osi_Once(&once)) {
391         /* initialize global locks */
392         lock_InitializeRWLock(&buf_globalLock, "Global buffer lock");
393
394         if ( newFile ) {
395             /* remember this for those who want to reset it */
396             cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
397  
398             /* lower hash size to a prime number */
399             cm_data.buf_hashSize = osi_PrimeLessThan((afs_uint32)(cm_data.buf_nbuffers/7 + 1));
400  
401             /* create hash table */
402             memset((void *)cm_data.buf_scacheHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
403             
404             /* another hash table */
405             memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
406
407             /* create buffer headers and put in free list */
408             bp = cm_data.bufHeaderBaseAddress;
409             data = cm_data.bufDataBaseAddress;
410             cm_data.buf_allp = NULL;
411             
412             for (i=0; i<cm_data.buf_nbuffers; i++) {
413                 osi_assertx(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress, 
414                             "invalid cm_buf_t address");
415                 osi_assertx(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData,
416                             "invalid cm_buf_t data address");
417                 
418                 /* allocate and zero some storage */
419                 memset(bp, 0, sizeof(cm_buf_t));
420                 bp->magic = CM_BUF_MAGIC;
421                 /* thread on list of all buffers */
422                 bp->allp = cm_data.buf_allp;
423                 cm_data.buf_allp = bp;
424                 
425                 osi_QAdd((osi_queue_t **)&cm_data.buf_freeListp, &bp->q);
426                 bp->flags |= CM_BUF_INLRU;
427                 lock_InitializeMutex(&bp->mx, "Buffer mutex");
428                 
429                 /* grab appropriate number of bytes from aligned zone */
430                 bp->datap = data;
431                 
432                 /* setup last buffer pointer */
433                 if (i == 0)
434                     cm_data.buf_freeListEndp = bp;
435                     
436                 /* next */
437                 bp++;
438                 data += cm_data.buf_blockSize;
439             }       
440  
441             /* none reserved at first */
442             cm_data.buf_reservedBufs = 0;
443  
444             /* just for safety's sake */
445             cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
446         } else {
447             bp = cm_data.bufHeaderBaseAddress;
448             data = cm_data.bufDataBaseAddress;
449             
450             for (i=0; i<cm_data.buf_nbuffers; i++) {
451                 lock_InitializeMutex(&bp->mx, "Buffer mutex");
452                 bp->userp = NULL;
453                 bp->waitCount = 0;
454                 bp->waitRequests = 0;
455                 bp->flags &= ~CM_BUF_WAITING;
456                 bp++;
457             }       
458         }
459  
460 #ifdef TESTING
461         buf_ValidateBufQueues();
462 #endif /* TESTING */
463
464 #ifdef TRACE_BUFFER
465         /* init the buffer trace log */
466         buf_logp = osi_LogCreate("buffer", 1000);
467         osi_LogEnable(buf_logp);
468 #endif
469
470         osi_EndOnce(&once);
471
472         /* and create the incr-syncer */
473         phandle = thrd_Create(0, 0,
474                                (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
475                                "buf_IncrSyncer");
476
477         osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
478         CloseHandle(phandle);
479     }
480
481 #ifdef TESTING
482     buf_ValidateBufQueues();
483 #endif /* TESTING */
484     return 0;
485 }
486
487 /* add nbuffers to the buffer pool, if possible.
488  * Called with no locks held.
489  */
490 long buf_AddBuffers(afs_uint64 nbuffers)
491 {
492     /* The size of a virtual cache cannot be changed after it has
493      * been created.  Subsequent calls to MapViewofFile() with
494      * an existing mapping object name would not allow the 
495      * object to be resized.  Return failure immediately.
496      *
497      * A similar problem now occurs with the persistent cache
498      * given that the memory mapped file now contains a complex
499      * data structure.
500      */
501     afsi_log("request to add %d buffers to the existing cache of size %d denied",
502               nbuffers, cm_data.buf_nbuffers);
503
504     return CM_ERROR_INVAL;
505 }       
506
507 /* interface to set the number of buffers to an exact figure.
508  * Called with no locks held.
509  */
510 long buf_SetNBuffers(afs_uint64 nbuffers)
511 {
512     if (nbuffers < 10) 
513         return CM_ERROR_INVAL;
514     if (nbuffers == cm_data.buf_nbuffers) 
515         return 0;
516     else if (nbuffers > cm_data.buf_nbuffers)
517         return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
518     else 
519         return CM_ERROR_INVAL;
520 }
521
522 /* wait for reading or writing to clear; called with write-locked
523  * buffer and unlocked scp and returns with locked buffer.
524  */
525 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
526 {
527     int release = 0;
528
529     if (scp)
530         osi_assertx(scp->magic == CM_SCACHE_MAGIC, "invalid cm_scache_t magic");
531     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
532
533     while (1) {
534         /* if no IO is happening, we're done */
535         if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
536             break;
537                 
538         /* otherwise I/O is happening, but some other thread is waiting for
539          * the I/O already.  Wait for that guy to figure out what happened,
540          * and then check again.
541          */
542         if ( bp->flags & CM_BUF_WAITING ) {
543             bp->waitCount++;
544             bp->waitRequests++;
545             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%p", bp);
546         } else {
547             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%p", bp);
548             bp->flags |= CM_BUF_WAITING;
549             bp->waitCount = bp->waitRequests = 1;
550         }
551         osi_SleepM((LONG_PTR)bp, &bp->mx);
552
553         smb_UpdateServerPriority();
554
555         lock_ObtainMutex(&bp->mx);
556         osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%p", bp);
557         bp->waitCount--;
558         if (bp->waitCount == 0) {
559             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%p", bp);
560             bp->flags &= ~CM_BUF_WAITING;
561             bp->waitRequests = 0;
562         }
563
564         if ( !scp ) {
565             if (scp = cm_FindSCache(&bp->fid))
566                  release = 1;
567         }
568         if ( scp ) {
569             lock_ObtainRead(&scp->rw);
570             if (scp->flags & CM_SCACHEFLAG_WAITING) {
571                 osi_Log1(buf_logp, "buf_WaitIO waking scp 0x%p", scp);
572                 osi_Wakeup((LONG_PTR)&scp->flags);
573             }
574             lock_ReleaseRead(&scp->rw);
575         }
576     }
577         
578     /* if we get here, the IO is done, but we may have to wakeup people waiting for
579      * the I/O to complete.  Do so.
580      */
581     if (bp->flags & CM_BUF_WAITING) {
582         osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
583         osi_Wakeup((LONG_PTR) bp);
584     }
585     osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%p", bp);
586
587     if (scp && release)
588         cm_ReleaseSCache(scp);
589 }
590
591 /* find a buffer, if any, for a particular file ID and offset.  Assumes
592  * that buf_globalLock is write locked when called.
593  */
594 cm_buf_t *buf_FindLocked(struct cm_scache *scp, osi_hyper_t *offsetp)
595 {
596     afs_uint32 i;
597     cm_buf_t *bp;
598
599     i = BUF_HASH(&scp->fid, offsetp);
600     for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp) {
601         if (cm_FidCmp(&scp->fid, &bp->fid) == 0
602              && offsetp->LowPart == bp->offset.LowPart
603              && offsetp->HighPart == bp->offset.HighPart) {
604             buf_HoldLocked(bp);
605             break;
606         }
607     }
608         
609     /* return whatever we found, if anything */
610     return bp;
611 }
612
613 /* find a buffer with offset *offsetp for vnode *scp.  Called
614  * with no locks held.
615  */
616 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
617 {
618     cm_buf_t *bp;
619
620     lock_ObtainRead(&buf_globalLock);
621     bp = buf_FindLocked(scp, offsetp);
622     lock_ReleaseRead(&buf_globalLock);
623
624     return bp;
625 }       
626
627 /* start cleaning I/O on this buffer.  Buffer must be write locked, and is returned
628  * write-locked.
629  *
630  * Makes sure that there's only one person writing this block
631  * at any given time, and also ensures that the log is forced sufficiently far,
632  * if this buffer contains logged data.
633  *
634  * Returns non-zero if the buffer was dirty.
635  */
636 long buf_CleanAsyncLocked(cm_buf_t *bp, cm_req_t *reqp)
637 {
638     long code = 0;
639     long isdirty = 0;
640     cm_scache_t * scp = NULL;
641     osi_hyper_t offset;
642
643     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
644
645     while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
646         isdirty = 1;
647         lock_ReleaseMutex(&bp->mx);
648
649         scp = cm_FindSCache(&bp->fid);
650         if (scp) {
651             osi_Log2(buf_logp, "buf_CleanAsyncLocked starts I/O on scp 0x%p buf 0x%p", scp, bp);
652
653             offset = bp->offset;
654             LargeIntegerAdd(offset, ConvertLongToLargeInteger(bp->dirty_offset));
655             code = (*cm_buf_opsp->Writep)(scp, &offset, 
656 #if 1
657                                            /* we might as well try to write all of the contiguous 
658                                             * dirty buffers in one RPC 
659                                             */
660                                            cm_chunkSize,
661 #else
662                                           bp->dirty_length, 
663 #endif
664                                           0, bp->userp, reqp);
665             osi_Log3(buf_logp, "buf_CleanAsyncLocked I/O on scp 0x%p buf 0x%p, done=%d", scp, bp, code);
666
667             cm_ReleaseSCache(scp);
668             scp = NULL;
669         } else {
670             osi_Log1(buf_logp, "buf_CleanAsyncLocked unable to start I/O - scp not found buf 0x%p", bp);
671             code = CM_ERROR_NOSUCHFILE;
672         }    
673         
674         lock_ObtainMutex(&bp->mx);
675         /* if the Write routine returns No Such File, clear the dirty flag
676          * because we aren't going to be able to write this data to the file
677          * server.
678          */
679         if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BADFD || code == CM_ERROR_NOACCESS || 
680             code == CM_ERROR_QUOTA || code == CM_ERROR_SPACE || code == CM_ERROR_TOOBIG || 
681             code == CM_ERROR_READONLY || code == CM_ERROR_NOSUCHPATH){
682             bp->flags &= ~CM_BUF_DIRTY;
683             bp->flags |= CM_BUF_ERROR;
684             bp->dirty_offset = 0;
685             bp->dirty_length = 0;
686             bp->error = code;
687             bp->dataVersion = CM_BUF_VERSION_BAD;
688             bp->dirtyCounter++;
689             break;
690         }
691
692 #ifdef DISKCACHE95
693         /* Disk cache support */
694         /* write buffer to disk cache (synchronous for now) */
695         diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
696 #endif /* DISKCACHE95 */
697
698         /* if we get here and retries are not permitted 
699          * then we need to exit this loop regardless of 
700          * whether or not we were able to clear the dirty bit
701          */
702         if (reqp->flags & CM_REQ_NORETRY)
703             break;
704     };
705
706     if (!(bp->flags & CM_BUF_DIRTY)) {
707         /* remove buffer from dirty buffer queue */
708
709     }
710
711     /* do logging after call to GetLastError, or else */
712         
713     /* if someone was waiting for the I/O that just completed or failed,
714      * wake them up.
715      */
716     if (bp->flags & CM_BUF_WAITING) {
717         /* turn off flags and wakeup users */
718         osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
719         osi_Wakeup((LONG_PTR) bp);
720     }
721     return isdirty;
722 }
723
724 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
725  * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
726  * The buffer must already be clean, and no I/O should be happening to it.
727  */
728 void buf_Recycle(cm_buf_t *bp)
729 {
730     afs_uint32 i;
731     cm_buf_t **lbpp;
732     cm_buf_t *tbp;
733     cm_buf_t *prevBp, *nextBp;
734
735     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
736
737     /* if we get here, we know that the buffer still has a 0 ref count,
738      * and that it is clean and has no currently pending I/O.  This is
739      * the dude to return.
740      * Remember that as long as the ref count is 0, we know that we won't
741      * have any lock conflicts, so we can grab the buffer lock out of
742      * order in the locking hierarchy.
743      */
744     osi_Log3( buf_logp, "buf_Recycle recycles 0x%p, off 0x%x:%08x",
745               bp, bp->offset.HighPart, bp->offset.LowPart);
746
747     osi_assertx(bp->refCount == 0, "cm_buf_t refcount != 0");
748     osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)),
749                 "incorrect cm_buf_t flags");
750     lock_AssertWrite(&buf_globalLock);
751
752     if (bp->flags & CM_BUF_INHASH) {
753         /* Remove from hash */
754
755         i = BUF_HASH(&bp->fid, &bp->offset);
756         lbpp = &(cm_data.buf_scacheHashTablepp[i]);
757         for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
758             if (tbp == bp) 
759                 break;
760         }
761
762         /* we better find it */
763         osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
764
765         *lbpp = bp->hashp;      /* hash out */
766         bp->hashp = NULL;
767
768         /* Remove from file hash */
769
770         i = BUF_FILEHASH(&bp->fid);
771         prevBp = bp->fileHashBackp;
772         bp->fileHashBackp = NULL;
773         nextBp = bp->fileHashp;
774         bp->fileHashp = NULL;
775         if (prevBp)
776             prevBp->fileHashp = nextBp;
777         else
778             cm_data.buf_fileHashTablepp[i] = nextBp;
779         if (nextBp)
780             nextBp->fileHashBackp = prevBp;
781
782         bp->flags &= ~CM_BUF_INHASH;
783     }
784
785     /* make the fid unrecognizable */
786     memset(&bp->fid, 0, sizeof(cm_fid_t));
787 }       
788
789 /* recycle a buffer, removing it from the free list, hashing in its new identity
790  * and returning it write-locked so that no one can use it.  Called without
791  * any locks held, and can return an error if it loses the race condition and 
792  * finds that someone else created the desired buffer.
793  *
794  * If success is returned, the buffer is returned write-locked.
795  *
796  * May be called with null scp and offsetp, if we're just trying to reclaim some
797  * space from the buffer pool.  In that case, the buffer will be returned
798  * without being hashed into the hash table.
799  */
800 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
801 {
802     cm_buf_t *bp;       /* buffer we're dealing with */
803     cm_buf_t *nextBp;   /* next buffer in file hash chain */
804     afs_uint32 i;       /* temp */
805     cm_req_t req;
806
807     cm_InitReq(&req);   /* just in case */
808
809 #ifdef TESTING
810     buf_ValidateBufQueues();
811 #endif /* TESTING */
812
813     while(1) {
814       retry:
815         lock_ObtainRead(&scp->bufCreateLock);
816         lock_ObtainWrite(&buf_globalLock);
817         /* check to see if we lost the race */
818         if (scp) {
819             if (bp = buf_FindLocked(scp, offsetp)) {
820                 /* Do not call buf_ReleaseLocked() because we 
821                  * do not want to allow the buffer to be added
822                  * to the free list.
823                  */
824                 afs_int32 refCount = InterlockedDecrement(&bp->refCount);
825 #ifdef DEBUG_REFCOUNT
826                 osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, refCount);
827                 afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, refCount);
828 #endif
829                 lock_ReleaseWrite(&buf_globalLock);
830                 lock_ReleaseRead(&scp->bufCreateLock);
831                 return CM_BUF_EXISTS;
832             }
833         }
834
835         /* does this fix the problem below?  it's a simple solution. */
836         if (!cm_data.buf_freeListEndp)
837         {
838             lock_ReleaseWrite(&buf_globalLock);
839             lock_ReleaseRead(&scp->bufCreateLock);
840             osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List is empty - sleeping 200ms");
841             Sleep(200);
842             goto retry;
843         }
844
845         /* for debugging, assert free list isn't empty, although we
846          * really should try waiting for a running tranasction to finish
847          * instead of this; or better, we should have a transaction
848          * throttler prevent us from entering this situation.
849          */
850         osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
851
852         /* look at all buffers in free list, some of which may temp.
853          * have high refcounts and which then should be skipped,
854          * starting cleaning I/O for those which are dirty.  If we find
855          * a clean buffer, we rehash it, lock it and return it.
856          */
857         for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
858             /* check to see if it really has zero ref count.  This
859              * code can bump refcounts, at least, so it may not be
860              * zero.
861              */
862             if (bp->refCount > 0) 
863                 continue;
864                         
865             /* we don't have to lock buffer itself, since the ref
866              * count is 0 and we know it will stay zero as long as
867              * we hold the global lock.
868              */
869
870             /* Don't recycle a buffer held by the redirector. */
871             if (bp->flags & CM_BUF_REDIR)
872                 continue;
873
874             /* don't recycle someone in our own chunk */
875             if (!cm_FidCmp(&bp->fid, &scp->fid)
876                  && (bp->offset.LowPart & (-cm_chunkSize))
877                  == (offsetp->LowPart & (-cm_chunkSize)))
878                 continue;
879
880             /* if this page is being filled (!) or cleaned, see if
881              * the I/O has completed.  If not, skip it, otherwise
882              * do the final processing for the I/O.
883              */
884             if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
885                 /* probably shouldn't do this much work while
886                  * holding the big lock?  Watch for contention
887                  * here.
888                  */
889                 continue;
890             }
891                         
892             if (bp->flags & CM_BUF_DIRTY) {
893                 /* if the buffer is dirty, start cleaning it and
894                  * move on to the next buffer.  We do this with
895                  * just the lock required to minimize contention
896                  * on the big lock.
897                  */
898                 buf_HoldLocked(bp);
899                 lock_ReleaseWrite(&buf_globalLock);
900                 lock_ReleaseRead(&scp->bufCreateLock);
901
902                 /* grab required lock and clean; this only
903                  * starts the I/O.  By the time we're back,
904                  * it'll still be marked dirty, but it will also
905                  * have the WRITING flag set, so we won't get
906                  * back here.
907                  */
908                 buf_CleanAsync(bp, &req);
909
910                 /* now put it back and go around again */
911                 buf_Release(bp);
912                 goto retry;
913             }
914
915             /* if we get here, we know that the buffer still has a 0
916              * ref count, and that it is clean and has no currently
917              * pending I/O.  This is the dude to return.
918              * Remember that as long as the ref count is 0, we know
919              * that we won't have any lock conflicts, so we can grab
920              * the buffer lock out of order in the locking hierarchy.
921              */
922             buf_Recycle(bp);
923
924             /* clean up junk flags */
925             bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
926             bp->dataVersion = CM_BUF_VERSION_BAD;       /* unknown so far */
927
928             /* now hash in as our new buffer, and give it the
929              * appropriate label, if requested.
930              */
931             if (scp) {
932                 bp->flags |= CM_BUF_INHASH;
933                 bp->fid = scp->fid;
934 #ifdef DEBUG
935                 bp->scp = scp;
936 #endif
937                 bp->offset = *offsetp;
938                 i = BUF_HASH(&scp->fid, offsetp);
939                 bp->hashp = cm_data.buf_scacheHashTablepp[i];
940                 cm_data.buf_scacheHashTablepp[i] = bp;
941                 i = BUF_FILEHASH(&scp->fid);
942                 nextBp = cm_data.buf_fileHashTablepp[i];
943                 bp->fileHashp = nextBp;
944                 bp->fileHashBackp = NULL;
945                 if (nextBp)
946                     nextBp->fileHashBackp = bp;
947                 cm_data.buf_fileHashTablepp[i] = bp;
948             }
949
950             /* we should move it from the lru queue.  It better still be there,
951              * since we've held the global (big) lock since we found it there.
952              */
953             osi_assertx(bp->flags & CM_BUF_INLRU,
954                          "buf_GetNewLocked: LRU screwup");
955
956             if (cm_data.buf_freeListEndp == bp) {
957                 /* we're the last guy in this queue, so maintain it */
958                 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
959             }
960             osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
961             bp->flags &= ~CM_BUF_INLRU;
962
963             /* grab the mutex so that people don't use it
964              * before the caller fills it with data.  Again, no one     
965              * should have been able to get to this dude to lock it.
966              */
967             if (!lock_TryMutex(&bp->mx)) {
968                 osi_Log2(afsd_logp, "buf_GetNewLocked bp 0x%p cannot be mutex locked.  refCount %d should be 0",
969                          bp, bp->refCount);
970                 osi_panic("buf_GetNewLocked: TryMutex failed",__FILE__,__LINE__);
971             }
972
973             /* prepare to return it.  Give it a refcount */
974             bp->refCount = 1;
975 #ifdef DEBUG_REFCOUNT
976             osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, 1);
977             afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, 1);
978 #endif
979             lock_ReleaseWrite(&buf_globalLock);
980             lock_ReleaseRead(&scp->bufCreateLock);
981             *bufpp = bp;
982
983 #ifdef TESTING
984             buf_ValidateBufQueues();
985 #endif /* TESTING */
986             return 0;
987         } /* for all buffers in lru queue */
988         lock_ReleaseWrite(&buf_globalLock);
989         lock_ReleaseRead(&scp->bufCreateLock);
990         osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List has no buffers with a zero refcount - sleeping 100ms");
991         Sleep(100);             /* give some time for a buffer to be freed */
992     }   /* while loop over everything */
993     /* not reached */
994 } /* the proc */
995
996 /* get a page, returning it held but unlocked.  Doesn't fill in the page
997  * with I/O, since we're going to write the whole thing new.
998  */
999 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
1000 {
1001     cm_buf_t *bp;
1002     long code;
1003     osi_hyper_t pageOffset;
1004     int created;
1005
1006     created = 0;
1007     pageOffset.HighPart = offsetp->HighPart;
1008     pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1009     while (1) {
1010         bp = buf_Find(scp, &pageOffset);
1011         if (bp) {
1012             /* lock it and break out */
1013             lock_ObtainMutex(&bp->mx);
1014             break;
1015         }
1016
1017         /* otherwise, we have to create a page */
1018         code = buf_GetNewLocked(scp, &pageOffset, &bp);
1019
1020         /* check if the buffer was created in a race condition branch.
1021          * If so, go around so we can hold a reference to it. 
1022          */
1023         if (code == CM_BUF_EXISTS) 
1024             continue;
1025
1026         /* something else went wrong */
1027         if (code != 0) 
1028             return code;
1029
1030         /* otherwise, we have a locked buffer that we just created */
1031         created = 1;
1032         break;
1033     } /* big while loop */
1034
1035     /* wait for reads */
1036     if (bp->flags & CM_BUF_READING)
1037         buf_WaitIO(scp, bp);
1038
1039     /* once it has been read once, we can unlock it and return it, still
1040      * with its refcount held.
1041      */
1042     lock_ReleaseMutex(&bp->mx);
1043     *bufpp = bp;
1044     osi_Log4(buf_logp, "buf_GetNew returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1045               bp, scp, offsetp->HighPart, offsetp->LowPart);
1046     return 0;
1047 }
1048
1049 /* get a page, returning it held but unlocked.  Make sure it is complete */
1050 /* The scp must be unlocked when passed to this function */
1051 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
1052 {
1053     cm_buf_t *bp;
1054     long code;
1055     osi_hyper_t pageOffset;
1056     unsigned long tcount;
1057     int created;
1058     long lcount = 0;
1059 #ifdef DISKCACHE95
1060     cm_diskcache_t *dcp;
1061 #endif /* DISKCACHE95 */
1062
1063     created = 0;
1064     pageOffset.HighPart = offsetp->HighPart;
1065     pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1066     while (1) {
1067         lcount++;
1068 #ifdef TESTING
1069         buf_ValidateBufQueues();
1070 #endif /* TESTING */
1071
1072         bp = buf_Find(scp, &pageOffset);
1073         if (bp) {
1074             /* lock it and break out */
1075             lock_ObtainMutex(&bp->mx);
1076
1077 #ifdef DISKCACHE95
1078             /* touch disk chunk to update LRU info */
1079             diskcache_Touch(bp->dcp);
1080 #endif /* DISKCACHE95 */
1081             break;
1082         }
1083
1084         /* otherwise, we have to create a page */
1085         code = buf_GetNewLocked(scp, &pageOffset, &bp);
1086         /* bp->mx is now held */
1087
1088         /* check if the buffer was created in a race condition branch.
1089          * If so, go around so we can hold a reference to it. 
1090          */
1091         if (code == CM_BUF_EXISTS) 
1092             continue;
1093
1094         /* something else went wrong */
1095         if (code != 0) { 
1096 #ifdef TESTING
1097             buf_ValidateBufQueues();
1098 #endif /* TESTING */
1099             return code;
1100         }
1101                 
1102         /* otherwise, we have a locked buffer that we just created */
1103         created = 1;
1104         break;
1105     } /* big while loop */
1106
1107     /* if we get here, we have a locked buffer that may have just been
1108      * created, in which case it needs to be filled with data.
1109      */
1110     if (created) {
1111         /* load the page; freshly created pages should be idle */
1112         osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)), "incorrect cm_buf_t flags");
1113
1114         /* start the I/O; may drop lock */
1115         bp->flags |= CM_BUF_READING;
1116         code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
1117
1118 #ifdef DISKCACHE95
1119         code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
1120         bp->dcp = dcp;    /* pointer to disk cache struct. */
1121 #endif /* DISKCACHE95 */
1122
1123         if (code != 0) {
1124             /* failure or queued */
1125             if (code != ERROR_IO_PENDING) {
1126                 bp->error = code;
1127                 bp->flags |= CM_BUF_ERROR;
1128                 bp->flags &= ~CM_BUF_READING;
1129                 if (bp->flags & CM_BUF_WAITING) {
1130                     osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1131                     osi_Wakeup((LONG_PTR) bp);
1132                 }
1133                 lock_ReleaseMutex(&bp->mx);
1134                 buf_Release(bp);
1135 #ifdef TESTING
1136                 buf_ValidateBufQueues();
1137 #endif /* TESTING */
1138                 return code;
1139             }
1140         } else {
1141             /* otherwise, I/O completed instantly and we're done, except
1142              * for padding the xfr out with 0s and checking for EOF
1143              */
1144             if (tcount < (unsigned long) cm_data.buf_blockSize) {
1145                 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
1146                 if (tcount == 0)
1147                     bp->flags |= CM_BUF_EOF;
1148             }
1149             bp->flags &= ~CM_BUF_READING;
1150             if (bp->flags & CM_BUF_WAITING) {
1151                 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1152                 osi_Wakeup((LONG_PTR) bp);
1153             }
1154         }
1155
1156     } /* if created */
1157
1158     /* wait for reads, either that which we started above, or that someone
1159      * else started.  We don't care if we return a buffer being cleaned.
1160      */
1161     if (bp->flags & CM_BUF_READING)
1162         buf_WaitIO(scp, bp);
1163
1164     /* once it has been read once, we can unlock it and return it, still
1165      * with its refcount held.
1166      */
1167     lock_ReleaseMutex(&bp->mx);
1168     *bufpp = bp;
1169
1170     /* now remove from queue; will be put in at the head (farthest from
1171      * being recycled) when we're done in buf_Release.
1172      */
1173     lock_ObtainWrite(&buf_globalLock);
1174     if (bp->flags & CM_BUF_INLRU) {
1175         if (cm_data.buf_freeListEndp == bp)
1176             cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1177         osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
1178         bp->flags &= ~CM_BUF_INLRU;
1179     }
1180     lock_ReleaseWrite(&buf_globalLock);
1181
1182     osi_Log4(buf_logp, "buf_Get returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1183               bp, scp, offsetp->HighPart, offsetp->LowPart);
1184 #ifdef TESTING
1185     buf_ValidateBufQueues();
1186 #endif /* TESTING */
1187     return 0;
1188 }
1189
1190 /* count # of elements in the free list;
1191  * we don't bother doing the proper locking for accessing dataVersion or flags
1192  * since it is a pain, and this is really just an advisory call.  If you need
1193  * to do better at some point, rewrite this function.
1194  */
1195 long buf_CountFreeList(void)
1196 {
1197     long count;
1198     cm_buf_t *bufp;
1199
1200     count = 0;
1201     lock_ObtainRead(&buf_globalLock);
1202     for(bufp = cm_data.buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1203         /* if the buffer doesn't have an identity, or if the buffer
1204          * has been invalidate (by having its DV stomped upon), then
1205          * count it as free, since it isn't really being utilized.
1206          */
1207         if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion == CM_BUF_VERSION_BAD)
1208             count++;
1209     }       
1210     lock_ReleaseRead(&buf_globalLock);
1211     return count;
1212 }
1213
1214 /* clean a buffer synchronously */
1215 long buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1216 {
1217     long code;
1218     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1219
1220     lock_ObtainMutex(&bp->mx);
1221     code = buf_CleanAsyncLocked(bp, reqp);
1222     lock_ReleaseMutex(&bp->mx);
1223
1224     return code;
1225 }       
1226
1227 /* wait for a buffer's cleaning to finish */
1228 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp, afs_uint32 locked)
1229 {
1230     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1231
1232     if (!locked)
1233         lock_ObtainMutex(&bp->mx);
1234     if (bp->flags & CM_BUF_WRITING) {
1235         buf_WaitIO(scp, bp);
1236     }
1237     if (!locked)
1238         lock_ReleaseMutex(&bp->mx);
1239 }       
1240
1241 /* set the dirty flag on a buffer, and set associated write-ahead log,
1242  * if there is one.  Allow one to be added to a buffer, but not changed.
1243  *
1244  * The buffer must be locked before calling this routine.
1245  */
1246 void buf_SetDirty(cm_buf_t *bp, afs_uint32 offset, afs_uint32 length, cm_user_t *userp)
1247 {
1248     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1249     osi_assertx(bp->refCount > 0, "cm_buf_t refcount 0");
1250
1251     if (bp->flags & CM_BUF_DIRTY) {
1252
1253         osi_Log1(buf_logp, "buf_SetDirty 0x%p already dirty", bp);
1254
1255         if (bp->dirty_offset <= offset) {
1256             if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1257                 /* dirty_length remains the same */
1258             } else {
1259                 bp->dirty_length = offset + length - bp->dirty_offset;
1260             }
1261         } else /* bp->dirty_offset > offset */ {
1262             if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1263                 bp->dirty_length = bp->dirty_offset + bp->dirty_length - offset;
1264             } else {
1265                 bp->dirty_length = length;
1266             }
1267             bp->dirty_offset = offset;
1268         }
1269     } else {
1270         osi_Log1(buf_logp, "buf_SetDirty 0x%p", bp);
1271
1272         /* set dirty bit */
1273         bp->flags |= CM_BUF_DIRTY;
1274
1275         /* and turn off EOF flag, since it has associated data now */
1276         bp->flags &= ~CM_BUF_EOF;
1277
1278         bp->dirty_offset = offset;
1279         bp->dirty_length = length;
1280
1281         /* and add to the dirty list.  
1282          * we obtain a hold on the buffer for as long as it remains 
1283          * in the list.  buffers are only removed from the list by 
1284          * the buf_IncrSyncer function regardless of when else the
1285          * dirty flag might be cleared.
1286          *
1287          * This should never happen but just in case there is a bug
1288          * elsewhere, never add to the dirty list if the buffer is 
1289          * already there.
1290          */
1291         lock_ObtainWrite(&buf_globalLock);
1292         if (!(bp->flags & CM_BUF_INDL)) {
1293             buf_HoldLocked(bp);
1294             if (!cm_data.buf_dirtyListp) {
1295                 cm_data.buf_dirtyListp = cm_data.buf_dirtyListEndp = bp;
1296             } else {
1297                 cm_data.buf_dirtyListEndp->dirtyp = bp;
1298                 cm_data.buf_dirtyListEndp = bp;
1299             }
1300             bp->dirtyp = NULL;
1301             bp->flags |= CM_BUF_INDL;
1302         }
1303         lock_ReleaseWrite(&buf_globalLock);
1304     }
1305
1306     /* and record the last writer */
1307     if (bp->userp != userp) {
1308         cm_HoldUser(userp);
1309         if (bp->userp) 
1310             cm_ReleaseUser(bp->userp);
1311         bp->userp = userp;
1312     }
1313 }
1314
1315 /* clean all buffers, reset log pointers and invalidate all buffers.
1316  * Called with no locks held, and returns with same.
1317  *
1318  * This function is guaranteed to clean and remove the log ptr of all the
1319  * buffers that were dirty or had non-zero log ptrs before the call was
1320  * made.  That's sufficient to clean up any garbage left around by recovery,
1321  * which is all we're counting on this for; there may be newly created buffers
1322  * added while we're running, but that should be OK.
1323  *
1324  * In an environment where there are no transactions (artificially imposed, for
1325  * example, when switching the database to raw mode), this function is used to
1326  * make sure that all updates have been written to the disk.  In that case, we don't
1327  * really require that we forget the log association between pages and logs, but
1328  * it also doesn't hurt.  Since raw mode I/O goes through this buffer package, we don't
1329  * have to worry about invalidating data in the buffers.
1330  *
1331  * This function is used at the end of recovery as paranoia to get the recovered
1332  * database out to disk.  It removes all references to the recovery log and cleans
1333  * all buffers.
1334  */
1335 long buf_CleanAndReset(void)
1336 {
1337     afs_uint32 i;
1338     cm_buf_t *bp;
1339     cm_req_t req;
1340
1341     lock_ObtainRead(&buf_globalLock);
1342     for(i=0; i<cm_data.buf_hashSize; i++) {
1343         for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp = bp->hashp) {
1344             if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1345                 buf_HoldLocked(bp);
1346                 lock_ReleaseRead(&buf_globalLock);
1347
1348                 /* now no locks are held; clean buffer and go on */
1349                 cm_InitReq(&req);
1350                 req.flags |= CM_REQ_NORETRY;
1351
1352                 buf_CleanAsync(bp, &req);
1353                 buf_CleanWait(NULL, bp, FALSE);
1354
1355                 /* relock and release buffer */
1356                 lock_ObtainRead(&buf_globalLock);
1357                 buf_ReleaseLocked(bp, FALSE);
1358             } /* dirty */
1359         } /* over one bucket */
1360     }   /* for loop over all hash buckets */
1361
1362     /* release locks */
1363     lock_ReleaseRead(&buf_globalLock);
1364
1365 #ifdef TESTING
1366     buf_ValidateBufQueues();
1367 #endif /* TESTING */
1368     
1369     /* and we're done */
1370     return 0;
1371 }       
1372
1373 /* called without global lock being held, reserves buffers for callers
1374  * that need more than one held (not locked) at once.
1375  */
1376 void buf_ReserveBuffers(afs_uint64 nbuffers)
1377 {
1378     lock_ObtainWrite(&buf_globalLock);
1379     while (1) {
1380         if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1381             cm_data.buf_reserveWaiting = 1;
1382             osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1383             osi_SleepW((LONG_PTR) &cm_data.buf_reservedBufs, &buf_globalLock);
1384             lock_ObtainWrite(&buf_globalLock);
1385         }
1386         else {
1387             cm_data.buf_reservedBufs += nbuffers;
1388             break;
1389         }
1390     }
1391     lock_ReleaseWrite(&buf_globalLock);
1392 }
1393
1394 int buf_TryReserveBuffers(afs_uint64 nbuffers)
1395 {
1396     int code;
1397
1398     lock_ObtainWrite(&buf_globalLock);
1399     if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1400         code = 0;
1401     }
1402     else {
1403         cm_data.buf_reservedBufs += nbuffers;
1404         code = 1;
1405     }
1406     lock_ReleaseWrite(&buf_globalLock);
1407     return code;
1408 }       
1409
1410 /* called without global lock held, releases reservation held by
1411  * buf_ReserveBuffers.
1412  */
1413 void buf_UnreserveBuffers(afs_uint64 nbuffers)
1414 {
1415     lock_ObtainWrite(&buf_globalLock);
1416     cm_data.buf_reservedBufs -= nbuffers;
1417     if (cm_data.buf_reserveWaiting) {
1418         cm_data.buf_reserveWaiting = 0;
1419         osi_Wakeup((LONG_PTR) &cm_data.buf_reservedBufs);
1420     }
1421     lock_ReleaseWrite(&buf_globalLock);
1422 }       
1423
1424 /* truncate the buffers past sizep, zeroing out the page, if we don't
1425  * end on a page boundary.
1426  *
1427  * Requires cm_bufCreateLock to be write locked.
1428  */
1429 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1430                    osi_hyper_t *sizep)
1431 {
1432     cm_buf_t *bufp;
1433     cm_buf_t *nbufp;                    /* next buffer, if didRelease */
1434     osi_hyper_t bufEnd;
1435     long code;
1436     long bufferPos;
1437     afs_uint32 i;
1438
1439     /* assert that cm_bufCreateLock is held in write mode */
1440     lock_AssertWrite(&scp->bufCreateLock);
1441
1442     i = BUF_FILEHASH(&scp->fid);
1443
1444     lock_ObtainRead(&buf_globalLock);
1445     bufp = cm_data.buf_fileHashTablepp[i];
1446     if (bufp == NULL) {
1447         lock_ReleaseRead(&buf_globalLock);
1448         return 0;
1449     }
1450
1451     buf_HoldLocked(bufp);
1452     lock_ReleaseRead(&buf_globalLock);
1453     while (bufp) {
1454         lock_ObtainMutex(&bufp->mx);
1455
1456         bufEnd.HighPart = 0;
1457         bufEnd.LowPart = cm_data.buf_blockSize;
1458         bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1459
1460         if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1461              LargeIntegerLessThan(*sizep, bufEnd)) {
1462             buf_WaitIO(scp, bufp);
1463         }
1464         lock_ObtainWrite(&scp->rw);
1465         
1466         /* make sure we have a callback (so we have the right value for
1467          * the length), and wait for it to be safe to do a truncate.
1468          */
1469         code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1470                           CM_SCACHESYNC_NEEDCALLBACK
1471                           | CM_SCACHESYNC_GETSTATUS
1472                           | CM_SCACHESYNC_SETSIZE
1473                           | CM_SCACHESYNC_BUFLOCKED);
1474
1475         
1476         /* if we succeeded in our locking, and this applies to the right
1477          * file, and the truncate request overlaps the buffer either
1478          * totally or partially, then do something.
1479          */
1480         if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1481              && LargeIntegerLessThan(*sizep, bufEnd)) {
1482
1483
1484             /* destroy the buffer, turning off its dirty bit, if
1485              * we're truncating the whole buffer.  Otherwise, set
1486              * the dirty bit, and clear out the tail of the buffer
1487              * if we just overlap some.
1488              */
1489             if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1490                 /* truncating the entire page */
1491                 bufp->flags &= ~CM_BUF_DIRTY;
1492                 bufp->dirty_offset = 0;
1493                 bufp->dirty_length = 0;
1494                 bufp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
1495                 bufp->dirtyCounter++;
1496             }
1497             else {
1498                 /* don't set dirty, since dirty implies
1499                  * currently up-to-date.  Don't need to do this,
1500                  * since we'll update the length anyway.
1501                  *
1502                  * Zero out remainder of the page, in case we
1503                  * seek and write past EOF, and make this data
1504                  * visible again.
1505                  */
1506                 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1507                 osi_assertx(bufferPos != 0, "non-zero bufferPos");
1508                 memset(bufp->datap + bufferPos, 0,
1509                         cm_data.buf_blockSize - bufferPos);
1510             }
1511         }
1512                 
1513         cm_SyncOpDone( scp, bufp, 
1514                        CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
1515                        | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_BUFLOCKED);
1516
1517         lock_ReleaseWrite(&scp->rw);
1518         lock_ReleaseMutex(&bufp->mx);
1519     
1520         if (!code) {
1521             nbufp = bufp->fileHashp;
1522             if (nbufp) 
1523                 buf_Hold(nbufp);
1524         } else {
1525             /* This forces the loop to end and the error code
1526              * to be returned. */
1527             nbufp = NULL;
1528         }
1529         buf_Release(bufp);
1530         bufp = nbufp;
1531     }
1532
1533 #ifdef TESTING
1534     buf_ValidateBufQueues();
1535 #endif /* TESTING */
1536
1537     /* done */
1538     return code;
1539 }
1540
1541 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1542 {
1543     long code;
1544     cm_buf_t *bp;               /* buffer we're hacking on */
1545     cm_buf_t *nbp;
1546     int didRelease;
1547     afs_uint32 i;
1548
1549     i = BUF_FILEHASH(&scp->fid);
1550
1551     code = 0;
1552     lock_ObtainRead(&buf_globalLock);
1553     bp = cm_data.buf_fileHashTablepp[i];
1554     if (bp) 
1555         buf_HoldLocked(bp);
1556     lock_ReleaseRead(&buf_globalLock);
1557     
1558     for (; bp; bp = nbp) {
1559         didRelease = 0; /* haven't released this buffer yet */
1560
1561         /* clean buffer synchronously */
1562         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1563             lock_ObtainMutex(&bp->mx);
1564
1565             /* start cleaning the buffer, and wait for it to finish */
1566             buf_CleanAsyncLocked(bp, reqp);
1567             buf_WaitIO(scp, bp);
1568             lock_ReleaseMutex(&bp->mx);
1569
1570             /* 
1571              * if the error for the previous buffer was BADFD
1572              * then all buffers for the FID are bad.  Do not
1573              * attempt to stabalize.
1574              */
1575             if (code != CM_ERROR_BADFD) {
1576                 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1577                 if (code && code != CM_ERROR_BADFD) 
1578                     goto skip;
1579             }
1580             if (code == CM_ERROR_BADFD) {
1581                 /* if the scp's FID is bad its because we received VNOVNODE 
1582                  * when attempting to FetchStatus before the write.  This
1583                  * page therefore contains data that can no longer be stored.
1584                  */
1585                 lock_ObtainMutex(&bp->mx);
1586                 bp->flags &= ~CM_BUF_DIRTY;
1587                 bp->flags |= CM_BUF_ERROR;
1588                 bp->error = CM_ERROR_BADFD;
1589                 bp->dirty_offset = 0;
1590                 bp->dirty_length = 0;
1591                 bp->dataVersion = CM_BUF_VERSION_BAD;   /* known bad */
1592                 bp->dirtyCounter++;
1593                 lock_ReleaseMutex(&bp->mx);
1594             }
1595
1596             /* actually, we only know that buffer is clean if ref
1597              * count is 1, since we don't have buffer itself locked.
1598              */
1599             if (!(bp->flags & CM_BUF_DIRTY)) {
1600                 lock_ObtainWrite(&buf_globalLock);
1601                 if (bp->refCount == 1) {        /* bp is held above */
1602                     nbp = bp->fileHashp;
1603                     if (nbp) 
1604                         buf_HoldLocked(nbp);
1605                     buf_ReleaseLocked(bp, TRUE);
1606                     didRelease = 1;
1607                     buf_Recycle(bp);
1608                 }
1609                 lock_ReleaseWrite(&buf_globalLock);
1610             }
1611
1612             if (code == 0)
1613                 (*cm_buf_opsp->Unstabilizep)(scp, userp);
1614         }
1615
1616       skip:
1617         if (!didRelease) {
1618             lock_ObtainRead(&buf_globalLock);
1619             nbp = bp->fileHashp;
1620             if (nbp)
1621                 buf_HoldLocked(nbp);
1622             buf_ReleaseLocked(bp, FALSE);
1623             lock_ReleaseRead(&buf_globalLock);
1624         }
1625     }   /* for loop over a bunch of buffers */
1626
1627 #ifdef TESTING
1628     buf_ValidateBufQueues();
1629 #endif /* TESTING */
1630
1631     /* done */
1632     return code;
1633 }       
1634
1635 /* Must be called with scp->rw held */
1636 long buf_ForceDataVersion(cm_scache_t * scp, afs_uint64 fromVersion, afs_uint64 toVersion)
1637 {
1638     cm_buf_t * bp;
1639     afs_uint32 i;
1640     int found = 0;
1641
1642     lock_AssertAny(&scp->rw);
1643
1644     i = BUF_FILEHASH(&scp->fid);
1645
1646     lock_ObtainRead(&buf_globalLock);
1647
1648     for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp = bp->fileHashp) {
1649         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1650             if (bp->dataVersion == fromVersion) {
1651                 bp->dataVersion = toVersion;
1652                 found = 1;
1653             }
1654         }
1655     }
1656     lock_ReleaseRead(&buf_globalLock);
1657
1658     if (found)
1659         return 0;
1660     else
1661         return ENOENT;
1662 }
1663
1664 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1665 {
1666     long code = 0;
1667     long wasDirty = 0;
1668     cm_buf_t *bp;               /* buffer we're hacking on */
1669     cm_buf_t *nbp;              /* next one */
1670     afs_uint32 i;
1671
1672     i = BUF_FILEHASH(&scp->fid);
1673
1674     lock_ObtainRead(&buf_globalLock);
1675     bp = cm_data.buf_fileHashTablepp[i];
1676     if (bp) 
1677         buf_HoldLocked(bp);
1678     lock_ReleaseRead(&buf_globalLock);
1679     for (; bp; bp = nbp) {
1680         /* clean buffer synchronously */
1681         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1682             lock_ObtainMutex(&bp->mx);
1683             if (bp->flags & CM_BUF_DIRTY) {
1684                 if (userp) {
1685                     cm_HoldUser(userp);
1686                     if (bp->userp) 
1687                         cm_ReleaseUser(bp->userp);
1688                     bp->userp = userp;
1689                 }   
1690
1691                 switch (code) {
1692                 case CM_ERROR_NOSUCHFILE:
1693                 case CM_ERROR_BADFD:
1694                 case CM_ERROR_NOACCESS:
1695                 case CM_ERROR_QUOTA:
1696                 case CM_ERROR_SPACE:
1697                 case CM_ERROR_TOOBIG:
1698                 case CM_ERROR_READONLY:
1699                 case CM_ERROR_NOSUCHPATH:
1700                     /* 
1701                      * Apply the previous fatal error to this buffer.
1702                      * Do not waste the time attempting to store to
1703                      * the file server when we know it will fail.
1704                      */
1705                     bp->flags &= ~CM_BUF_DIRTY;
1706                     bp->flags |= CM_BUF_ERROR;
1707                     bp->dirty_offset = 0;
1708                     bp->dirty_length = 0;
1709                     bp->error = code;
1710                     bp->dataVersion = CM_BUF_VERSION_BAD;
1711                     bp->dirtyCounter++;
1712                     break;
1713                 default:
1714                     wasDirty = buf_CleanAsyncLocked(bp, reqp);
1715                     if (bp->flags & CM_BUF_ERROR) {
1716                         code = bp->error;
1717                         if (code == 0)
1718                             code = -1;
1719                     }
1720                 }
1721                 buf_CleanWait(scp, bp, TRUE);
1722             }
1723             lock_ReleaseMutex(&bp->mx);
1724         }
1725
1726         lock_ObtainRead(&buf_globalLock);
1727         nbp = bp->fileHashp;
1728         if (nbp) 
1729             buf_HoldLocked(nbp);
1730         buf_ReleaseLocked(bp, FALSE);
1731         lock_ReleaseRead(&buf_globalLock);
1732     }   /* for loop over a bunch of buffers */
1733
1734 #ifdef TESTING
1735     buf_ValidateBufQueues();
1736 #endif /* TESTING */
1737
1738     /* done */
1739     return code;
1740 }
1741
1742 #ifdef TESTING
1743 void
1744 buf_ValidateBufQueues(void)
1745 {
1746     cm_buf_t * bp, *bpb, *bpf, *bpa;
1747     afs_uint32 countf=0, countb=0, counta=0;
1748
1749     lock_ObtainRead(&buf_globalLock);
1750     for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1751         if (bp->magic != CM_BUF_MAGIC)
1752             osi_panic("buf magic error",__FILE__,__LINE__);
1753         countb++;
1754         bpb = bp;
1755     }
1756
1757     for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
1758         if (bp->magic != CM_BUF_MAGIC)
1759             osi_panic("buf magic error",__FILE__,__LINE__);
1760         countf++;
1761         bpf = bp;
1762     }
1763
1764     for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
1765         if (bp->magic != CM_BUF_MAGIC)
1766             osi_panic("buf magic error",__FILE__,__LINE__);
1767         counta++;
1768         bpa = bp;
1769     }
1770     lock_ReleaseRead(&buf_globalLock);
1771
1772     if (countb != countf)
1773         osi_panic("buf magic error",__FILE__,__LINE__);
1774
1775     if (counta != cm_data.buf_nbuffers)
1776         osi_panic("buf magic error",__FILE__,__LINE__);
1777 }
1778 #endif /* TESTING */
1779
1780 /* dump the contents of the buf_scacheHashTablepp. */
1781 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
1782 {
1783     int zilch;
1784     cm_buf_t *bp;
1785     char output[1024];
1786     afs_uint32 i;
1787   
1788     if (cm_data.buf_scacheHashTablepp == NULL)
1789         return -1;
1790
1791     if (lock)
1792         lock_ObtainRead(&buf_globalLock);
1793   
1794     StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\r\n", 
1795                     cookie, cm_data.buf_hashSize);
1796     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1797   
1798     for (i = 0; i < cm_data.buf_hashSize; i++)
1799     {
1800         for (bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp) 
1801         {
1802             StringCbPrintfA(output, sizeof(output), 
1803                             "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d, "
1804                             "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1805                             "flags=0x%x, cmFlags=0x%x, refCount=%d\r\n",
1806                              cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume, 
1807                              bp->fid.vnode, bp->fid.unique, bp->offset.HighPart, 
1808                              bp->offset.LowPart, bp->dataVersion, bp->flags, 
1809                              bp->cmFlags, bp->refCount);
1810             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1811         }
1812     }
1813   
1814     StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\r\n", cookie);
1815     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1816
1817     StringCbPrintfA(output, sizeof(output), "%s - dumping buf_freeListEndp\r\n", cookie);
1818     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1819     for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1820         StringCbPrintfA(output, sizeof(output), 
1821                          "%s bp=0x%08X, fid (cell=%d, volume=%d, "
1822                          "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1823                          "flags=0x%x, cmFlags=0x%x, refCount=%d\r\n",
1824                          cookie, (void *)bp, bp->fid.cell, bp->fid.volume, 
1825                          bp->fid.vnode, bp->fid.unique, bp->offset.HighPart, 
1826                          bp->offset.LowPart, bp->dataVersion, bp->flags, 
1827                          bp->cmFlags, bp->refCount);
1828         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1829     }
1830     StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_FreeListEndp.\r\n", cookie);
1831     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1832
1833     StringCbPrintfA(output, sizeof(output), "%s - dumping buf_dirtyListp\r\n", cookie);
1834     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1835     for(bp = cm_data.buf_dirtyListp; bp; bp=bp->dirtyp) {
1836         StringCbPrintfA(output, sizeof(output), 
1837                          "%s bp=0x%08X, fid (cell=%d, volume=%d, "
1838                          "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
1839                          "flags=0x%x, cmFlags=0x%x, refCount=%d\r\n",
1840                          cookie, (void *)bp, bp->fid.cell, bp->fid.volume, 
1841                          bp->fid.vnode, bp->fid.unique, bp->offset.HighPart, 
1842                          bp->offset.LowPart, bp->dataVersion, bp->flags, 
1843                          bp->cmFlags, bp->refCount);
1844         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1845     }
1846     StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_dirtyListp.\r\n", cookie);
1847     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1848
1849     if (lock)
1850         lock_ReleaseRead(&buf_globalLock);
1851     return 0;
1852 }
1853
1854 void buf_ForceTrace(BOOL flush)
1855 {
1856     HANDLE handle;
1857     int len;
1858     char buf[256];
1859
1860     if (!buf_logp) 
1861         return;
1862
1863     len = GetTempPath(sizeof(buf)-10, buf);
1864     StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
1865     handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
1866                             NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1867     if (handle == INVALID_HANDLE_VALUE) {
1868         osi_panic("Cannot create log file", __FILE__, __LINE__);
1869     }
1870     osi_LogPrint(buf_logp, handle);
1871     if (flush)
1872         FlushFileBuffers(handle);
1873     CloseHandle(handle);
1874 }
1875
1876 long buf_DirtyBuffersExist(cm_fid_t *fidp)
1877 {
1878     cm_buf_t *bp;
1879     afs_uint32 bcount = 0;
1880     afs_uint32 i;
1881
1882     i = BUF_FILEHASH(fidp);
1883
1884     for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->allp, bcount++) {
1885         if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY))
1886             return 1;
1887     }
1888     return 0;
1889 }
1890
1891 #if 0
1892 long buf_CleanDirtyBuffers(cm_scache_t *scp)
1893 {
1894     cm_buf_t *bp;
1895     afs_uint32 bcount = 0;
1896     cm_fid_t * fidp = &scp->fid;
1897
1898     for (bp = cm_data.buf_allp; bp; bp=bp->allp, bcount++) {
1899         if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
1900             buf_Hold(bp);
1901             lock_ObtainMutex(&bp->mx);
1902             bp->cmFlags &= ~CM_BUF_CMSTORING;
1903             bp->flags &= ~CM_BUF_DIRTY;
1904             bp->dirty_offset = 0;
1905             bp->dirty_length = 0;
1906             bp->flags |= CM_BUF_ERROR;
1907             bp->error = VNOVNODE;
1908             bp->dataVersion = CM_BUF_VERSION_BAD; /* bad */
1909             bp->dirtyCounter++;
1910             if (bp->flags & CM_BUF_WAITING) {
1911                 osi_Log2(buf_logp, "BUF CleanDirtyBuffers Waking [scp 0x%x] bp 0x%x", scp, bp);
1912                 osi_Wakeup((long) &bp);
1913             }
1914             lock_ReleaseMutex(&bp->mx);
1915             buf_Release(bp);
1916         }
1917     }
1918     return 0;
1919 }
1920 #endif