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