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