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