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