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