Windows: buf_SetDirty add assertion
[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 #include <hcrypto\md5.h>
24
25 #include "afsd.h"
26 #include "cm_memmap.h"
27
28 #ifdef DEBUG
29 #define TRACE_BUFFER 1
30 #endif
31
32 extern void afsi_log(char *pattern, ...);
33
34 /* This module implements the buffer package used by the local transaction
35  * system (cm).  It is initialized by calling cm_Init, which calls buf_Init;
36  * it must be initalized before any of its main routines are called.
37  *
38  * Each buffer is hashed into a hash table by file ID and offset, and if its
39  * reference count is zero, it is also in a free list.
40  *
41  * There are two locks involved in buffer processing.  The global lock
42  * buf_globalLock protects all of the global variables defined in this module,
43  * the reference counts and hash pointers in the actual cm_buf_t structures,
44  * and the LRU queue pointers in the buffer structures.
45  *
46  * The mutexes in the buffer structures protect the remaining fields in the
47  * buffers, as well the data itself.
48  *
49  * The locking hierarchy here is this:
50  *
51  * - resv multiple simul. buffers reservation
52  * - lock buffer I/O flags
53  * - lock buffer's mutex
54  * - lock buf_globalLock
55  *
56  */
57
58 /* global debugging log */
59 osi_log_t *buf_logp = NULL;
60
61 /* Global lock protecting hash tables and free lists */
62 osi_rwlock_t buf_globalLock;
63
64 /* Global lock used to limit the number of RDR Release
65  * Extents requests to one. */
66 osi_mutex_t buf_rdrReleaseExtentsLock;
67
68 /* ptr to head of the free list (most recently used) and the
69  * tail (the guy to remove first).  We use osi_Q* functions
70  * to put stuff in buf_freeListp, and maintain the end
71  * pointer manually
72  */
73
74 /* a pointer to a list of all buffers, just so that we can find them
75  * easily for debugging, and for the incr syncer.  Locked under
76  * the global lock.
77  */
78
79 /* defaults setup; these variables may be manually assigned into
80  * before calling cm_Init, as a way of changing these defaults.
81  */
82
83 /* callouts for reading and writing data, etc */
84 cm_buf_ops_t *cm_buf_opsp;
85
86 #ifdef DISKCACHE95
87 /* for experimental disk caching support in Win95 client */
88 cm_buf_t *buf_diskFreeListp;
89 cm_buf_t *buf_diskFreeListEndp;
90 cm_buf_t *buf_diskAllp;
91 extern int cm_diskCacheEnabled;
92 #endif /* DISKCACHE95 */
93
94 /* set this to 1 when we are terminating to prevent access attempts */
95 static int buf_ShutdownFlag = 0;
96
97 #ifdef DEBUG_REFCOUNT
98 void buf_HoldLockedDbg(cm_buf_t *bp, char *file, long line)
99 #else
100 void buf_HoldLocked(cm_buf_t *bp)
101 #endif
102 {
103     afs_int32 refCount;
104
105     osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
106     refCount = InterlockedIncrement(&bp->refCount);
107 #ifdef DEBUG_REFCOUNT
108     osi_Log2(afsd_logp,"buf_HoldLocked bp 0x%p ref %d",bp, refCount);
109     afsi_log("%s:%d buf_HoldLocked bp 0x%p, ref %d", file, line, bp, refCount);
110 #endif
111 }
112
113 /* hold a reference to an already held buffer */
114 #ifdef DEBUG_REFCOUNT
115 void buf_HoldDbg(cm_buf_t *bp, char *file, long line)
116 #else
117 void buf_Hold(cm_buf_t *bp)
118 #endif
119 {
120     afs_int32 refCount;
121
122     lock_ObtainRead(&buf_globalLock);
123     osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
124     refCount = InterlockedIncrement(&bp->refCount);
125 #ifdef DEBUG_REFCOUNT
126     osi_Log2(afsd_logp,"buf_Hold bp 0x%p ref %d",bp, refCount);
127     afsi_log("%s:%d buf_Hold bp 0x%p, ref %d", file, line, bp, refCount);
128 #endif
129     lock_ReleaseRead(&buf_globalLock);
130 }
131
132 /* code to drop reference count while holding buf_globalLock */
133 #ifdef DEBUG_REFCOUNT
134 void buf_ReleaseLockedDbg(cm_buf_t *bp, afs_uint32 writeLocked, char *file, long line)
135 #else
136 void buf_ReleaseLocked(cm_buf_t *bp, afs_uint32 writeLocked)
137 #endif
138 {
139     afs_int32 refCount;
140
141     if (writeLocked)
142         lock_AssertWrite(&buf_globalLock);
143     else
144         lock_AssertRead(&buf_globalLock);
145
146     /* ensure that we're in the LRU queue if our ref count is 0 */
147     osi_assertx(bp->magic == CM_BUF_MAGIC,"incorrect cm_buf_t magic");
148
149     refCount = InterlockedDecrement(&bp->refCount);
150 #ifdef DEBUG_REFCOUNT
151     osi_Log3(afsd_logp,"buf_ReleaseLocked %s bp 0x%p ref %d",writeLocked?"write":"read", bp, refCount);
152     afsi_log("%s:%d buf_ReleaseLocked %s bp 0x%p, ref %d", file, line, writeLocked?"write":"read", bp, refCount);
153 #endif
154 #ifdef DEBUG
155     if (refCount < 0)
156         osi_panic("buf refcount 0",__FILE__,__LINE__);;
157 #else
158     osi_assertx(refCount >= 0, "cm_buf_t refCount == 0");
159 #endif
160     if (refCount == 0) {
161         /*
162          * If we are read locked there could be a race condition
163          * with buf_Find() so we must obtain a write lock and
164          * double check that the refCount is actually zero
165          * before we remove the buffer from the LRU queue.
166          */
167         if (!writeLocked)
168             lock_ConvertRToW(&buf_globalLock);
169
170         if (bp->refCount == 0 &&
171             !(bp->qFlags & (CM_BUF_QINLRU|CM_BUF_QREDIR))) {
172             osi_QAddH( (osi_queue_t **) &cm_data.buf_freeListp,
173                        (osi_queue_t **) &cm_data.buf_freeListEndp,
174                        &bp->q);
175             _InterlockedOr(&bp->qFlags, CM_BUF_QINLRU);
176             buf_IncrementFreeCount();
177         }
178
179         if (!writeLocked)
180             lock_ConvertWToR(&buf_globalLock);
181     }
182 }
183
184 /* release a buffer.  Buffer must be referenced, but unlocked. */
185 #ifdef DEBUG_REFCOUNT
186 void buf_ReleaseDbg(cm_buf_t *bp, char *file, long line)
187 #else
188 void buf_Release(cm_buf_t *bp)
189 #endif
190 {
191     lock_ObtainRead(&buf_globalLock);
192     buf_ReleaseLocked(bp, FALSE);
193     lock_ReleaseRead(&buf_globalLock);
194 }
195
196 long
197 buf_Sync(int quitOnShutdown)
198 {
199     cm_buf_t **bpp, *bp, *prevbp;
200     afs_uint32 wasDirty = 0;
201     cm_req_t req;
202
203     /* go through all of the dirty buffers */
204     lock_ObtainRead(&buf_globalLock);
205     for (bpp = &cm_data.buf_dirtyListp, prevbp = NULL; bp = *bpp; ) {
206         if (quitOnShutdown && buf_ShutdownFlag)
207             break;
208
209         /*
210          * If the buffer is held be the redirector we must fetch
211          * it back in order to determine whether or not it is in
212          * fact dirty.
213          */
214         if (bp->qFlags & CM_BUF_QREDIR) {
215             osi_Log1(buf_logp,"buf_Sync buffer held by redirector bp 0x%p", bp);
216
217             /* Request single buffer from the redirector */
218             buf_RDRShakeAnExtentFree(bp, &req);
219         }
220
221         lock_ReleaseRead(&buf_globalLock);
222         /*
223          * all dirty buffers are held when they are added to the
224          * dirty list.  No need for an additional hold.
225          */
226         lock_ObtainMutex(&bp->mx);
227
228         if ((bp->flags & CM_BUF_DIRTY)) {
229             /* start cleaning the buffer; don't touch log pages since
230              * the log code counts on knowing exactly who is writing
231              * a log page at any given instant.
232              *
233              * only attempt to write the buffer if the volume might
234              * be online.
235              */
236             afs_uint32 dirty;
237             cm_volume_t * volp;
238
239             volp = cm_GetVolumeByFID(&bp->fid);
240             switch (cm_GetVolumeStatus(volp, bp->fid.volume)) {
241             case vl_online:
242             case vl_unknown:
243                 cm_InitReq(&req);
244                 req.flags |= CM_REQ_NORETRY;
245                 buf_CleanLocked(NULL, bp, &req, 0, &dirty);
246                 wasDirty |= dirty;
247             }
248             cm_PutVolume(volp);
249         }
250
251         /* the buffer may or may not have been dirty
252         * and if dirty may or may not have been cleaned
253         * successfully.  check the dirty flag again.
254         */
255         if (!(bp->flags & CM_BUF_DIRTY)) {
256             /* remove the buffer from the dirty list */
257             lock_ObtainWrite(&buf_globalLock);
258 #ifdef DEBUG_REFCOUNT
259             if (bp->dirtyp == NULL && bp != cm_data.buf_dirtyListEndp) {
260                 osi_Log1(afsd_logp,"buf_Sync bp 0x%p list corruption",bp);
261                 afsi_log("buf_Sync bp 0x%p list corruption", bp);
262             }
263 #endif
264             *bpp = bp->dirtyp;
265             bp->dirtyp = NULL;
266             _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINDL);
267             if (cm_data.buf_dirtyListp == NULL)
268                 cm_data.buf_dirtyListEndp = NULL;
269             else if (cm_data.buf_dirtyListEndp == bp)
270                 cm_data.buf_dirtyListEndp = prevbp;
271             buf_ReleaseLocked(bp, TRUE);
272             lock_ConvertWToR(&buf_globalLock);
273         } else {
274             if (buf_ShutdownFlag) {
275                 cm_cell_t *cellp;
276                 cm_volume_t *volp;
277                 char volstr[VL_MAXNAMELEN+12]="";
278                 char *ext = "";
279
280                 volp = cm_GetVolumeByFID(&bp->fid);
281                 if (volp) {
282                     cellp = volp->cellp;
283                     if (bp->fid.volume == volp->vol[RWVOL].ID)
284                         ext = "";
285                     else if (bp->fid.volume == volp->vol[ROVOL].ID)
286                         ext = ".readonly";
287                     else if (bp->fid.volume == volp->vol[BACKVOL].ID)
288                         ext = ".backup";
289                     else
290                         ext = ".nomatch";
291                     snprintf(volstr, sizeof(volstr), "%s%s", volp->namep, ext);
292                 } else {
293                     cellp = cm_FindCellByID(bp->fid.cell, CM_FLAG_NOPROBE);
294                     snprintf(volstr, sizeof(volstr), "%u", bp->fid.volume);
295                 }
296
297                 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_DIRTY_BUFFER_AT_SHUTDOWN,
298                          cellp->name, volstr, bp->fid.vnode, bp->fid.unique,
299                          bp->offset.QuadPart+bp->dirty_offset, bp->dirty_length);
300             }
301
302             /* advance the pointer so we don't loop forever */
303             lock_ObtainRead(&buf_globalLock);
304             bpp = &bp->dirtyp;
305             prevbp = bp;
306         }
307         lock_ReleaseMutex(&bp->mx);
308     }   /* for loop over a bunch of buffers */
309     lock_ReleaseRead(&buf_globalLock);
310
311     return wasDirty;
312 }
313
314 /* incremental sync daemon.  Writes all dirty buffers every 5000 ms */
315 static void *
316 buf_IncrSyncer(void * parm)
317 {
318     long wasDirty = 0;
319     long i;
320
321     while (buf_ShutdownFlag == 0) {
322         if (!wasDirty) {
323             i = SleepEx(5000, 1);
324             if (i != 0)
325                 continue;
326         } else {
327             Sleep(50);
328         }
329
330         wasDirty = buf_Sync(1);
331     } /* whole daemon's while loop */
332
333     pthread_exit(NULL);
334     return NULL;
335 }
336
337 long
338 buf_ValidateBuffers(void)
339 {
340     cm_buf_t * bp, *bpf, *bpa, *bpb;
341     afs_uint64 countb = 0, countf = 0, counta = 0, countr = 0;
342
343     if (cm_data.buf_freeListp == NULL && cm_data.buf_freeListEndp != NULL ||
344          cm_data.buf_freeListp != NULL && cm_data.buf_freeListEndp == NULL) {
345         afsi_log("cm_ValidateBuffers failure: inconsistent free list pointers");
346         fprintf(stderr, "cm_ValidateBuffers failure: inconsistent free list pointers\n");
347         return -9;
348     }
349
350     for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
351         if (bp->magic != CM_BUF_MAGIC) {
352             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
353             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
354             return -1;
355         }
356         countb++;
357         bpb = bp;
358
359         if (countb > cm_data.buf_nbuffers) {
360             afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
361             fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
362             return -6;
363         }
364     }
365
366     for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
367         if (bp->magic != CM_BUF_MAGIC) {
368             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
369             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
370             return -2;
371         }
372         countf++;
373         bpf = bp;
374
375         if (countf > cm_data.buf_nbuffers) {
376             afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
377             fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
378             return -7;
379         }
380     }
381
382     for ( bp = cm_data.buf_redirListp; bp; bp = (cm_buf_t *) osi_QNext(&bp->q)) {
383         if (!(bp->qFlags & CM_BUF_QREDIR)) {
384             afsi_log("CM_BUF_QREDIR not set on cm_buf_t in buf_redirListp");
385             fprintf(stderr, "CM_BUF_QREDIR not set on cm_buf_t in buf_redirListp");
386             return -9;
387         }
388         countr++;
389         if (countr > cm_data.buf_nbuffers) {
390             afsi_log("cm_ValidateBuffers failure: countr > cm_data.buf_nbuffers");
391             fprintf(stderr, "cm_ValidateBuffers failure: countr > cm_data.buf_nbuffers\n");
392             return -10;
393         }
394     }
395
396     for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
397         if (bp->magic != CM_BUF_MAGIC) {
398             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
399             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
400             return -3;
401         }
402         counta++;
403         bpa = bp;
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 -8;
409         }
410     }
411
412     if (countb != countf) {
413         afsi_log("cm_ValidateBuffers failure: countb != countf");
414         fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
415         return -4;
416     }
417
418     if (counta != cm_data.buf_nbuffers) {
419         afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
420         fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
421         return -5;
422     }
423
424     return 0;
425 }
426
427 void buf_Shutdown(void)
428 {
429     /* disable the buf_IncrSyncer() threads */
430     buf_ShutdownFlag = 1;
431
432     /* then force all dirty buffers to the file servers */
433     buf_Sync(0);
434 }
435
436 /* initialize the buffer package; called with no locks
437  * held during the initialization phase.
438  */
439 long buf_Init(int newFile, cm_buf_ops_t *opsp, afs_uint64 nbuffers)
440 {
441     static osi_once_t once;
442     cm_buf_t *bp;
443     pthread_t phandle;
444     pthread_attr_t tattr;
445     int pstatus;
446     long i;
447     char *data;
448
449     if ( newFile ) {
450         if (nbuffers)
451             cm_data.buf_nbuffers = nbuffers;
452
453         /* Have to be able to reserve a whole chunk */
454         if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
455             return CM_ERROR_TOOFEWBUFS;
456     }
457
458     /* recall for callouts */
459     cm_buf_opsp = opsp;
460
461     if (osi_Once(&once)) {
462         /* initialize global locks */
463         lock_InitializeRWLock(&buf_globalLock, "Global buffer lock", LOCK_HIERARCHY_BUF_GLOBAL);
464         lock_InitializeMutex(&buf_rdrReleaseExtentsLock, "RDR Release Extents lock", LOCK_HIERARCHY_RDR_EXTENTS);
465
466         if ( newFile ) {
467             /* remember this for those who want to reset it */
468             cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
469
470             /* lower hash size to a prime number */
471             cm_data.buf_hashSize = cm_NextHighestPowerOf2((afs_uint32)(cm_data.buf_nbuffers/7));
472
473             /* create hash table */
474             memset((void *)cm_data.buf_scacheHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
475
476             /* another hash table */
477             memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
478
479             /* create buffer headers and put in free list */
480             bp = cm_data.bufHeaderBaseAddress;
481             data = cm_data.bufDataBaseAddress;
482             cm_data.buf_allp = NULL;
483
484             for (i=0; i<cm_data.buf_nbuffers; i++) {
485                 osi_assertx(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress,
486                             "invalid cm_buf_t address");
487                 osi_assertx(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData,
488                             "invalid cm_buf_t data address");
489
490                 /* allocate and zero some storage */
491                 memset(bp, 0, sizeof(cm_buf_t));
492                 bp->magic = CM_BUF_MAGIC;
493                 /* thread on list of all buffers */
494                 bp->allp = cm_data.buf_allp;
495                 cm_data.buf_allp = bp;
496
497                 osi_QAddH( (osi_queue_t **) &cm_data.buf_freeListp,
498                            (osi_queue_t **) &cm_data.buf_freeListEndp,
499                            &bp->q);
500                 _InterlockedOr(&bp->qFlags, CM_BUF_QINLRU);
501                 buf_IncrementFreeCount();
502                 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
503
504                 /* grab appropriate number of bytes from aligned zone */
505                 bp->datap = data;
506
507                 /* next */
508                 bp++;
509                 data += cm_data.buf_blockSize;
510             }
511
512             /* none reserved at first */
513             cm_data.buf_reservedBufs = 0;
514
515             /* just for safety's sake */
516             cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
517         } else {
518             bp = cm_data.bufHeaderBaseAddress;
519             data = cm_data.bufDataBaseAddress;
520
521             lock_ObtainWrite(&buf_globalLock);
522             for (i=0; i<cm_data.buf_nbuffers; i++) {
523                 lock_InitializeMutex(&bp->mx, "Buffer mutex", LOCK_HIERARCHY_BUFFER);
524                 bp->userp = NULL;
525                 bp->waitCount = 0;
526                 bp->waitRequests = 0;
527                 _InterlockedAnd(&bp->flags, ~CM_BUF_WAITING);
528                 bp->error = 0;
529                 if (bp->qFlags & CM_BUF_QREDIR) {
530                     /*
531                      * extent was not returned by the file system driver.
532                      * clean up the mess.
533                      */
534                     buf_RemoveFromRedirQueue(NULL, bp);
535                     bp->dataVersion = CM_BUF_VERSION_BAD;
536                     bp->redirq.nextp = bp->redirq.prevp = NULL;
537                     bp->redirLastAccess = 0;
538                     bp->redirReleaseRequested = 0;
539                     buf_ReleaseLocked(bp, TRUE);
540                 }
541                 bp++;
542             }
543
544             /*
545              * There should be nothing left in cm_data.buf_redirListp
546              * but double check just to be sure.
547              */
548             for ( bp = cm_data.buf_redirListp;
549                   bp;
550                   bp = cm_data.buf_redirListp)
551             {
552                 /*
553                  * extent was not returned by the file system driver.
554                  * clean up the mess.
555                  */
556                 buf_RemoveFromRedirQueue(NULL, bp);
557                 bp->dataVersion = CM_BUF_VERSION_BAD;
558                 bp->redirq.nextp = bp->redirq.prevp = NULL;
559                 bp->redirLastAccess = 0;
560                 bp->redirReleaseRequested = 0;
561                 buf_ReleaseLocked(bp, TRUE);
562             }
563             lock_ReleaseWrite(&buf_globalLock);
564         }
565
566 #ifdef TESTING
567         buf_ValidateBufQueues();
568 #endif /* TESTING */
569
570 #ifdef TRACE_BUFFER
571         /* init the buffer trace log */
572         buf_logp = osi_LogCreate("buffer", 1000);
573         osi_LogEnable(buf_logp);
574 #endif
575
576         osi_EndOnce(&once);
577
578         /* and create the incr-syncer */
579         pthread_attr_init(&tattr);
580         pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
581
582         pstatus = pthread_create(&phandle, &tattr, buf_IncrSyncer, 0);
583         osi_assertx(pstatus == 0, "buf: can't create incremental sync proc");
584
585         pthread_attr_destroy(&tattr);
586     }
587
588 #ifdef TESTING
589     buf_ValidateBufQueues();
590 #endif /* TESTING */
591     return 0;
592 }
593
594 /* add nbuffers to the buffer pool, if possible.
595  * Called with no locks held.
596  */
597 long buf_AddBuffers(afs_uint64 nbuffers)
598 {
599     /* The size of a virtual cache cannot be changed after it has
600      * been created.  Subsequent calls to MapViewofFile() with
601      * an existing mapping object name would not allow the
602      * object to be resized.  Return failure immediately.
603      *
604      * A similar problem now occurs with the persistent cache
605      * given that the memory mapped file now contains a complex
606      * data structure.
607      */
608     afsi_log("request to add %d buffers to the existing cache of size %d denied",
609               nbuffers, cm_data.buf_nbuffers);
610
611     return CM_ERROR_INVAL;
612 }
613
614 /* interface to set the number of buffers to an exact figure.
615  * Called with no locks held.
616  */
617 long buf_SetNBuffers(afs_uint64 nbuffers)
618 {
619     if (nbuffers < 10)
620         return CM_ERROR_INVAL;
621     if (nbuffers == cm_data.buf_nbuffers)
622         return 0;
623     else if (nbuffers > cm_data.buf_nbuffers)
624         return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
625     else
626         return CM_ERROR_INVAL;
627 }
628
629 /* wait for reading or writing to clear; called with write-locked
630  * buffer and unlocked scp and returns with locked buffer.
631  */
632 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
633 {
634     int release = 0;
635
636     if (scp)
637         osi_assertx(scp->magic == CM_SCACHE_MAGIC, "invalid cm_scache_t magic");
638     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
639
640     while (1) {
641         /* if no IO is happening, we're done */
642         if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
643             break;
644
645         /* otherwise I/O is happening, but some other thread is waiting for
646          * the I/O already.  Wait for that guy to figure out what happened,
647          * and then check again.
648          */
649         if ( bp->flags & CM_BUF_WAITING ) {
650             bp->waitCount++;
651             bp->waitRequests++;
652             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%p", bp);
653         } else {
654             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%p", bp);
655             _InterlockedOr(&bp->flags, CM_BUF_WAITING);
656             bp->waitCount = bp->waitRequests = 1;
657         }
658         osi_SleepM((LONG_PTR)bp, &bp->mx);
659
660         cm_UpdateServerPriority();
661
662         lock_ObtainMutex(&bp->mx);
663         osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%p", bp);
664         bp->waitCount--;
665         if (bp->waitCount == 0) {
666             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%p", bp);
667             _InterlockedAnd(&bp->flags, ~CM_BUF_WAITING);
668             bp->waitRequests = 0;
669         }
670
671         if ( !scp ) {
672             if (scp = cm_FindSCache(&bp->fid))
673                  release = 1;
674         }
675         if ( scp ) {
676             lock_ObtainRead(&scp->rw);
677             if (!osi_QIsEmpty(&scp->waitQueueH)) {
678                 osi_Log1(buf_logp, "buf_WaitIO waking scp 0x%p", scp);
679                 osi_Wakeup((LONG_PTR)&scp->flags);
680             }
681             lock_ReleaseRead(&scp->rw);
682         }
683     }
684
685     /* if we get here, the IO is done, but we may have to wakeup people waiting for
686      * the I/O to complete.  Do so.
687      */
688     if (bp->flags & CM_BUF_WAITING) {
689         osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
690         osi_Wakeup((LONG_PTR) bp);
691     }
692     osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%p", bp);
693
694     if (scp && release)
695         cm_ReleaseSCache(scp);
696 }
697
698 /* find a buffer, if any, for a particular file ID and offset.  Assumes
699  * that buf_globalLock is write locked when called.
700  */
701 cm_buf_t *buf_FindLocked(struct cm_fid *fidp, osi_hyper_t *offsetp)
702 {
703     afs_uint32 i;
704     cm_buf_t *bp;
705
706     lock_AssertAny(&buf_globalLock);
707
708     i = BUF_HASH(fidp, offsetp);
709     for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp) {
710         if (cm_FidCmp(fidp, &bp->fid) == 0
711              && offsetp->LowPart == bp->offset.LowPart
712              && offsetp->HighPart == bp->offset.HighPart) {
713             buf_HoldLocked(bp);
714             break;
715         }
716     }
717
718     /* return whatever we found, if anything */
719     return bp;
720 }
721
722 /* find a buffer with offset *offsetp for vnode *scp.  Called
723  * with no locks held.
724  */
725 cm_buf_t *buf_Find(struct cm_fid *fidp, osi_hyper_t *offsetp)
726 {
727     cm_buf_t *bp;
728
729     lock_ObtainRead(&buf_globalLock);
730     bp = buf_FindLocked(fidp, offsetp);
731     lock_ReleaseRead(&buf_globalLock);
732
733     return bp;
734 }
735
736 /* find a buffer, if any, for a particular file ID and offset.  Assumes
737  * that buf_globalLock is write locked when called.  Uses the all buffer
738  * list.
739  */
740 cm_buf_t *buf_FindAllLocked(struct cm_fid *fidp, osi_hyper_t *offsetp, afs_uint32 flags)
741 {
742     cm_buf_t *bp;
743
744     if (flags == 0) {
745         for(bp = cm_data.buf_allp; bp; bp=bp->allp) {
746             if (cm_FidCmp(fidp, &bp->fid) == 0
747                  && offsetp->LowPart == bp->offset.LowPart
748                  && offsetp->HighPart == bp->offset.HighPart) {
749                 buf_HoldLocked(bp);
750                 break;
751             }
752         }
753     } else {
754         for(bp = cm_data.buf_allp; bp; bp=bp->allp) {
755             if (cm_FidCmp(fidp, &bp->fid) == 0) {
756                 char * fileOffset;
757
758                 fileOffset = offsetp->QuadPart + cm_data.baseAddress;
759                 if (fileOffset == bp->datap) {
760                     buf_HoldLocked(bp);
761                     break;
762                 }
763             }
764         }
765     }
766     /* return whatever we found, if anything */
767     return bp;
768 }
769
770 /* find a buffer with offset *offsetp for vnode *scp.  Called
771  * with no locks held.  Use the all buffer list.
772  */
773 cm_buf_t *buf_FindAll(struct cm_fid *fidp, osi_hyper_t *offsetp, afs_uint32 flags)
774 {
775     cm_buf_t *bp;
776
777     lock_ObtainRead(&buf_globalLock);
778     bp = buf_FindAllLocked(fidp, offsetp, flags);
779     lock_ReleaseRead(&buf_globalLock);
780
781     return bp;
782 }
783
784 /* start cleaning I/O on this buffer.  Buffer must be write locked, and is returned
785  * write-locked.
786  *
787  * Makes sure that there's only one person writing this block
788  * at any given time, and also ensures that the log is forced sufficiently far,
789  * if this buffer contains logged data.
790  *
791  * Returns non-zero if the buffer was dirty.
792  *
793  * 'scp' may or may not be NULL.  If it is not NULL, the FID for both cm_scache_t
794  * and cm_buf_t must match.
795  */
796 afs_uint32 buf_CleanLocked(cm_scache_t *scp, cm_buf_t *bp, cm_req_t *reqp,
797                                 afs_uint32 flags, afs_uint32 *pisdirty)
798 {
799     afs_uint32 code = 0;
800     afs_uint32 isdirty = 0;
801     osi_hyper_t offset;
802     int release_scp = 0;
803
804     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
805     osi_assertx(scp == NULL || cm_FidCmp(&scp->fid, &bp->fid) == 0, "scp fid != bp fid");
806
807     /*
808      * If the matching cm_scache_t was not provided as a parameter
809      * we must either find one or allocate a new one.  It is possible
810      * that the cm_scache_t was recycled out of the cache even though
811      * a cm_buf_t with the same FID is in the cache.
812      */
813     if (scp == NULL &&
814         cm_GetSCache(&bp->fid, NULL, &scp,
815                      bp->userp ? bp->userp : cm_rootUserp,
816                      reqp) == 0)
817     {
818         release_scp = 1;
819     }
820
821     while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
822         isdirty = 1;
823         lock_ReleaseMutex(&bp->mx);
824
825         if (!scp) {
826             /*
827              * If we didn't find a cm_scache_t object for bp->fid it means
828              * that we no longer have that FID in the cache.  It does not
829              * mean that the object does not exist in the cell.  That may
830              * in fact be the case but we don't know that until we attempt
831              * a FetchStatus on the FID.
832              */
833             osi_Log1(buf_logp, "buf_CleanLocked unable to start I/O - scp not found buf 0x%p", bp);
834             code = CM_ERROR_NOSUCHFILE;
835         } else {
836             osi_Log2(buf_logp, "buf_CleanLocked starts I/O on scp 0x%p buf 0x%p", scp, bp);
837
838             offset = bp->offset;
839             LargeIntegerAdd(offset, ConvertLongToLargeInteger(bp->dirty_offset));
840             /*
841              * Only specify the dirty length of the current buffer in the call
842              * to cm_BufWrite().  It is the responsibility of cm_BufWrite()
843              * to determine if it is appropriate to fill a full chunk of data
844              * when storing to the file server.
845              */
846             code = (*cm_buf_opsp->Writep)(scp, &offset,
847                                           bp->dirty_length,
848                                           flags, bp->userp, reqp);
849             osi_Log3(buf_logp, "buf_CleanLocked I/O on scp 0x%p buf 0x%p, done=%d", scp, bp, code);
850         }
851         lock_ObtainMutex(&bp->mx);
852         /* if the Write routine returns No Such File, clear the dirty flag
853          * because we aren't going to be able to write this data to the file
854          * server.
855          */
856         if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BADFD || code == CM_ERROR_NOACCESS ||
857             code == CM_ERROR_QUOTA || code == CM_ERROR_SPACE || code == CM_ERROR_TOOBIG ||
858             code == CM_ERROR_READONLY || code == CM_ERROR_NOSUCHPATH || code == EIO){
859             _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
860             _InterlockedOr(&bp->flags, CM_BUF_ERROR);
861             bp->dirty_length = 0;
862             bp->error = code;
863             bp->dataVersion = CM_BUF_VERSION_BAD;
864             bp->dirtyCounter++;
865             break;
866         }
867
868 #ifdef DISKCACHE95
869         /* Disk cache support */
870         /* write buffer to disk cache (synchronous for now) */
871         diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
872 #endif /* DISKCACHE95 */
873
874         /* if we get here and retries are not permitted
875          * then we need to exit this loop regardless of
876          * whether or not we were able to clear the dirty bit
877          */
878         if (reqp->flags & CM_REQ_NORETRY)
879             break;
880
881         /* Ditto if the hardDeadTimeout or idleTimeout was reached */
882         if (code == CM_ERROR_TIMEDOUT || code == CM_ERROR_ALLDOWN ||
883             code == CM_ERROR_ALLBUSY || code == CM_ERROR_ALLOFFLINE ||
884             code == CM_ERROR_CLOCKSKEW) {
885             break;
886         }
887     }
888
889     if (release_scp)
890         cm_ReleaseSCache(scp);
891
892     /* if someone was waiting for the I/O that just completed or failed,
893      * wake them up.
894      */
895     if (bp->flags & CM_BUF_WAITING) {
896         /* turn off flags and wakeup users */
897         osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
898         osi_Wakeup((LONG_PTR) bp);
899     }
900
901     if (pisdirty)
902         *pisdirty = isdirty;
903
904     return code;
905 }
906
907 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
908  * recycles the buffer, and leaves it ready for reuse with a ref count of 0.
909  * The buffer must already be clean, and no I/O should be happening to it.
910  */
911 void buf_Recycle(cm_buf_t *bp)
912 {
913     afs_uint32 i;
914     cm_buf_t **lbpp;
915     cm_buf_t *tbp;
916     cm_buf_t *prevBp, *nextBp;
917
918     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
919
920     osi_assertx(!(bp->qFlags & CM_BUF_QREDIR), "can't recycle redir held buffers");
921
922     /* if we get here, we know that the buffer still has a 0 ref count,
923      * and that it is clean and has no currently pending I/O.  This is
924      * the dude to return.
925      * Remember that as long as the ref count is 0, we know that we won't
926      * have any lock conflicts, so we can grab the buffer lock out of
927      * order in the locking hierarchy.
928      */
929     osi_Log3( buf_logp, "buf_Recycle recycles 0x%p, off 0x%x:%08x",
930               bp, bp->offset.HighPart, bp->offset.LowPart);
931
932     osi_assertx(bp->refCount == 0, "cm_buf_t refcount != 0");
933     osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)),
934                 "incorrect cm_buf_t flags");
935     lock_AssertWrite(&buf_globalLock);
936
937     if (bp->qFlags & CM_BUF_QINHASH) {
938         /* Remove from hash */
939
940         i = BUF_HASH(&bp->fid, &bp->offset);
941         lbpp = &(cm_data.buf_scacheHashTablepp[i]);
942         for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = tbp->hashp) {
943             if (tbp == bp)
944                 break;
945         }
946
947         /* we better find it */
948         osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
949
950         *lbpp = bp->hashp;      /* hash out */
951         bp->hashp = NULL;
952
953         /* Remove from file hash */
954
955         i = BUF_FILEHASH(&bp->fid);
956         prevBp = bp->fileHashBackp;
957         bp->fileHashBackp = NULL;
958         nextBp = bp->fileHashp;
959         bp->fileHashp = NULL;
960         if (prevBp)
961             prevBp->fileHashp = nextBp;
962         else
963             cm_data.buf_fileHashTablepp[i] = nextBp;
964         if (nextBp)
965             nextBp->fileHashBackp = prevBp;
966
967         _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINHASH);
968     }
969
970     /* make the fid unrecognizable */
971     memset(&bp->fid, 0, sizeof(cm_fid_t));
972
973     /* clean up junk flags */
974     _InterlockedAnd(&bp->flags, ~(CM_BUF_EOF | CM_BUF_ERROR));
975     bp->dataVersion = CM_BUF_VERSION_BAD;       /* unknown so far */
976 }
977
978
979 /*
980  * buf_RDRShakeAnExtentFree
981  * called with buf_globalLock read locked
982  */
983 afs_uint32
984 buf_RDRShakeAnExtentFree(cm_buf_t *rbp, cm_req_t *reqp)
985 {
986     afs_uint32 code = 0;
987     LARGE_INTEGER heldExtents = {0,0};
988     AFSFileExtentCB extentList[1];
989     DWORD extentCount = 0;
990     BOOL locked = FALSE;
991
992     if (!(rbp->qFlags & CM_BUF_QREDIR))
993         return 0;
994
995     lock_ReleaseRead(&buf_globalLock);
996
997     if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
998         osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
999         if (reqp->flags & CM_REQ_NORETRY) {
1000             code = CM_ERROR_WOULDBLOCK;
1001             goto done;
1002         }
1003
1004         lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1005     }
1006
1007     extentList[0].Flags = 0;
1008     extentList[0].Length = cm_data.blockSize;
1009     extentList[0].FileOffset.QuadPart = rbp->offset.QuadPart;
1010     extentList[0].CacheOffset.QuadPart = rbp->datap - cm_data.baseAddress;
1011     extentCount = 1;
1012
1013     code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1014
1015     lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1016
1017   done:
1018     lock_ObtainRead(&buf_globalLock);
1019     return code;
1020 }
1021
1022 /*
1023  * buf_RDRShakeFileExtentsFree
1024  * requests all extents held by the redirector to be returned for
1025  * the specified cm_scache_t.  This function is called with no
1026  * locks held.
1027  */
1028 afs_uint32
1029 buf_RDRShakeFileExtentsFree(cm_scache_t *rscp, cm_req_t *reqp)
1030 {
1031     afs_uint32 code = 0;
1032     afs_uint64 n_redir = 0;
1033
1034     if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
1035         osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
1036         if (reqp->flags & CM_REQ_NORETRY)
1037             return CM_ERROR_WOULDBLOCK;
1038
1039         lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1040     }
1041
1042     for ( code = CM_ERROR_RETRY; code == CM_ERROR_RETRY; ) {
1043         LARGE_INTEGER heldExtents = {0,0};
1044         AFSFileExtentCB extentList[1024];
1045         DWORD extentCount = 0;
1046         cm_buf_t *srbp;
1047         time_t now;
1048
1049         /* only retry if a call to RDR_RequestExtentRelease says to */
1050         code = 0;
1051         lock_ObtainWrite(&buf_globalLock);
1052
1053         if (rscp->redirBufCount == 0)
1054         {
1055             lock_ReleaseWrite(&buf_globalLock);
1056             break;
1057         }
1058
1059         time(&now);
1060         for ( srbp = redirq_to_cm_buf_t(rscp->redirQueueT);
1061               srbp;
1062               srbp = ((code == 0 && extentCount == 0) ? redirq_to_cm_buf_t(rscp->redirQueueT) :
1063                        redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq))))
1064         {
1065             extentList[extentCount].Flags = 0;
1066             extentList[extentCount].Length = cm_data.blockSize;
1067             extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1068             extentList[extentCount].CacheOffset.QuadPart = srbp->datap - cm_data.baseAddress;
1069             srbp->redirReleaseRequested = now;
1070             extentCount++;
1071
1072             if (extentCount == 1024) {
1073                 lock_ReleaseWrite(&buf_globalLock);
1074                 heldExtents.QuadPart = cm_data.buf_redirCount;
1075                 code = RDR_RequestExtentRelease(&rscp->fid, heldExtents, extentCount, extentList);
1076                 if (code) {
1077                     if (code == CM_ERROR_RETRY) {
1078                         /*
1079                          * The redirector either is not holding the extents or cannot let them
1080                          * go because they are otherwise in use.  At the moment, do nothing.
1081                          */
1082                     } else
1083                         break;
1084                 }
1085                 extentCount = 0;
1086                 lock_ObtainWrite(&buf_globalLock);
1087             }
1088         }
1089         lock_ReleaseWrite(&buf_globalLock);
1090
1091         if (code == 0 && extentCount > 0) {
1092             heldExtents.QuadPart = cm_data.buf_redirCount;
1093             code = RDR_RequestExtentRelease(&rscp->fid, heldExtents, extentCount, extentList);
1094         }
1095
1096         if ((code == CM_ERROR_RETRY) && (reqp->flags & CM_REQ_NORETRY)) {
1097             code = CM_ERROR_WOULDBLOCK;
1098             break;
1099         }
1100     }
1101     lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1102     return code;
1103 }
1104
1105 afs_uint32
1106 buf_RDRShakeSomeExtentsFree(cm_req_t *reqp, afs_uint32 oneFid, afs_uint32 minage)
1107 {
1108     afs_uint32 code = 0;
1109
1110     if (!lock_TryMutex(&buf_rdrReleaseExtentsLock)) {
1111         if (reqp->flags & CM_REQ_NORETRY)
1112             return CM_ERROR_WOULDBLOCK;
1113
1114         osi_Log0(afsd_logp, "Waiting for prior RDR_RequestExtentRelease request to complete");
1115         lock_ObtainMutex(&buf_rdrReleaseExtentsLock);
1116     }
1117
1118     for ( code = CM_ERROR_RETRY; code == CM_ERROR_RETRY; ) {
1119         LARGE_INTEGER heldExtents;
1120         AFSFileExtentCB extentList[1024];
1121         DWORD extentCount = 0;
1122         cm_buf_t *rbp, *srbp;
1123         cm_scache_t *rscp;
1124         time_t now;
1125         BOOL locked = FALSE;
1126
1127         /* only retry if a call to RDR_RequestExtentRelease says to */
1128         code = 0;
1129         lock_ObtainWrite(&buf_globalLock);
1130         locked = TRUE;
1131
1132         for ( rbp = cm_data.buf_redirListEndp;
1133               code == 0 && rbp && (!oneFid || extentCount == 0);
1134               rbp = (cm_buf_t *) osi_QPrev(&rbp->q))
1135         {
1136             if (!oneFid)
1137                 extentCount = 0;
1138
1139             if (rbp->redirLastAccess >= rbp->redirReleaseRequested) {
1140                 rscp = cm_FindSCache(&rbp->fid);
1141                 if (!rscp)
1142                     continue;
1143
1144                 time(&now);
1145                 for ( srbp = redirq_to_cm_buf_t(rscp->redirQueueT);
1146                       srbp && extentCount < 1024;
1147                       srbp = redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq)))
1148                 {
1149                     /*
1150                      * Do not request a release if we have already done so
1151                      * or if the extent was delivered to windows less than
1152                      * 'minage' seconds ago.
1153                      */
1154                     if (srbp->redirLastAccess >= srbp->redirReleaseRequested &&
1155                          srbp->redirLastAccess < now - minage) {
1156                         extentList[extentCount].Flags = 0;
1157                         extentList[extentCount].Length = cm_data.blockSize;
1158                         extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1159                         extentList[extentCount].CacheOffset.QuadPart = srbp->datap - cm_data.baseAddress;
1160                         srbp->redirReleaseRequested = now;
1161                         extentCount++;
1162                     }
1163                 }
1164                 cm_ReleaseSCache(rscp);
1165             }
1166
1167             if ( !oneFid && extentCount > 0) {
1168                 if (locked) {
1169                     lock_ReleaseWrite(&buf_globalLock);
1170                     locked = FALSE;
1171                 }
1172                 heldExtents.QuadPart = cm_data.buf_redirCount;
1173                 code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1174             }
1175             if (!locked) {
1176                 lock_ObtainWrite(&buf_globalLock);
1177                 locked = TRUE;
1178             }
1179         }
1180         if (locked)
1181             lock_ReleaseWrite(&buf_globalLock);
1182         if (code == 0) {
1183             if (oneFid) {
1184                 heldExtents.QuadPart = cm_data.buf_redirCount;
1185                 if (rbp && extentCount)
1186                     code = RDR_RequestExtentRelease(&rbp->fid, heldExtents, extentCount, extentList);
1187                 else
1188                     code = RDR_RequestExtentRelease(NULL, heldExtents, 1024, NULL);
1189             } else {
1190                 code = 0;
1191             }
1192         }
1193
1194         if ((code == CM_ERROR_RETRY) && (reqp->flags & CM_REQ_NORETRY)) {
1195             code = CM_ERROR_WOULDBLOCK;
1196             break;
1197         }
1198     }
1199     lock_ReleaseMutex(&buf_rdrReleaseExtentsLock);
1200     return code;
1201 }
1202
1203 /* returns 0 if the buffer does not exist, and non-0 if it does */
1204 static long
1205 buf_ExistsLocked(struct cm_scache *scp, osi_hyper_t *offsetp)
1206 {
1207     cm_buf_t *bp;
1208
1209     if (bp = buf_FindLocked(&scp->fid, offsetp)) {
1210         /* Do not call buf_ReleaseLocked() because we
1211          * do not want to allow the buffer to be added
1212          * to the free list.
1213          */
1214         afs_int32 refCount = InterlockedDecrement(&bp->refCount);
1215 #ifdef DEBUG_REFCOUNT
1216         osi_Log2(afsd_logp,"buf_ExistsLocked bp 0x%p ref %d", bp, refCount);
1217         afsi_log("%s:%d buf_ExistsLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, refCount);
1218 #endif
1219         return CM_BUF_EXISTS;
1220     }
1221
1222     return 0;
1223 }
1224
1225 /* recycle a buffer, removing it from the free list, hashing in its new identity
1226  * and returning it write-locked so that no one can use it.  Called without
1227  * any locks held, and can return an error if it loses the race condition and
1228  * finds that someone else created the desired buffer.
1229  *
1230  * If success is returned, the buffer is returned write-locked.
1231  *
1232  * May be called with null scp and offsetp, if we're just trying to reclaim some
1233  * space from the buffer pool.  In that case, the buffer will be returned
1234  * without being hashed into the hash table.
1235  */
1236 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp, cm_buf_t **bufpp)
1237 {
1238     cm_buf_t *bp;       /* buffer we're dealing with */
1239     cm_buf_t *nextBp;   /* next buffer in file hash chain */
1240     afs_uint32 i;       /* temp */
1241     afs_uint64 n_bufs, n_nonzero, n_busy, n_dirty, n_own, n_redir;
1242
1243 #ifdef TESTING
1244     buf_ValidateBufQueues();
1245 #endif /* TESTING */
1246
1247     while(1) {
1248       retry:
1249         n_bufs = 0;
1250         n_nonzero = 0;
1251         n_own = 0;
1252         n_busy = 0;
1253         n_dirty = 0;
1254         n_redir = 0;
1255
1256         lock_ObtainRead(&scp->bufCreateLock);
1257         lock_ObtainWrite(&buf_globalLock);
1258         /* check to see if we lost the race */
1259         if (buf_ExistsLocked(scp, offsetp)) {
1260             lock_ReleaseWrite(&buf_globalLock);
1261             lock_ReleaseRead(&scp->bufCreateLock);
1262             return CM_BUF_EXISTS;
1263         }
1264
1265         /* does this fix the problem below?  it's a simple solution. */
1266         if (!cm_data.buf_freeListEndp)
1267         {
1268             lock_ReleaseWrite(&buf_globalLock);
1269             lock_ReleaseRead(&scp->bufCreateLock);
1270
1271             if ( RDR_Initialized )
1272                 goto rdr_release;
1273
1274             osi_Log0(afsd_logp, "buf_GetNewLocked: Free Buffer List is empty - sleeping 200ms");
1275             Sleep(200);
1276             goto retry;
1277         }
1278
1279         /* for debugging, assert free list isn't empty, although we
1280          * really should try waiting for a running tranasction to finish
1281          * instead of this; or better, we should have a transaction
1282          * throttler prevent us from entering this situation.
1283          */
1284         osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
1285
1286         /* look at all buffers in free list, some of which may temp.
1287          * have high refcounts and which then should be skipped,
1288          * starting cleaning I/O for those which are dirty.  If we find
1289          * a clean buffer, we rehash it, lock it and return it.
1290          */
1291         for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1292             int cleaned = 0;
1293
1294             n_bufs++;
1295
1296           retry_2:
1297             /* check to see if it really has zero ref count.  This
1298              * code can bump refcounts, at least, so it may not be
1299              * zero.
1300              */
1301             if (bp->refCount > 0) {
1302                 n_nonzero++;
1303                 continue;
1304             }
1305
1306             /* we don't have to lock buffer itself, since the ref
1307              * count is 0 and we know it will stay zero as long as
1308              * we hold the global lock.
1309              */
1310
1311             /* don't recycle someone in our own chunk */
1312             if (!cm_FidCmp(&bp->fid, &scp->fid) &&
1313                 bp->dataVersion >= scp->bufDataVersionLow &&
1314                 bp->dataVersion <= scp->dataVersion &&
1315                 (bp->offset.LowPart & (-cm_chunkSize)) == (offsetp->LowPart & (-cm_chunkSize))) {
1316                 n_own++;
1317                 continue;
1318             }
1319
1320             /* if this page is being filled (!) or cleaned, see if
1321              * the I/O has completed.  If not, skip it, otherwise
1322              * do the final processing for the I/O.
1323              */
1324             if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
1325                 /* probably shouldn't do this much work while
1326                  * holding the big lock?  Watch for contention
1327                  * here.
1328                  */
1329                 n_busy++;
1330                 continue;
1331             }
1332
1333             /* leave the buffer alone if held by the redirector */
1334             if (bp->qFlags & CM_BUF_QREDIR) {
1335                 n_redir++;
1336                 continue;
1337             }
1338
1339             if (bp->flags & CM_BUF_DIRTY) {
1340                 n_dirty++;
1341
1342                 /* protect against cleaning the same buffer more than once. */
1343                 if (cleaned)
1344                     continue;
1345
1346                 /* if the buffer is dirty, start cleaning it and
1347                  * move on to the next buffer.  We do this with
1348                  * just the lock required to minimize contention
1349                  * on the big lock.
1350                  */
1351                 buf_HoldLocked(bp);
1352                 lock_ReleaseWrite(&buf_globalLock);
1353                 lock_ReleaseRead(&scp->bufCreateLock);
1354
1355                 /*
1356                  * grab required lock and clean.
1357                  * previously the claim was that the cleaning
1358                  * operation was async which it is not.  It would
1359                  * be a good idea to use an async mechanism here
1360                  * but there is none at the moment other than
1361                  * the buf_IncrSyncer() thread.
1362                  */
1363                 if (cm_FidCmp(&scp->fid, &bp->fid) == 0)
1364                     buf_Clean(scp, bp, reqp, 0, NULL);
1365                 else
1366                     buf_Clean(NULL, bp, reqp, 0, NULL);
1367
1368                 /* now put it back and go around again */
1369                 buf_Release(bp);
1370
1371                 /* but first obtain the locks we gave up
1372                  * before the buf_CleanAsync() call */
1373                 lock_ObtainRead(&scp->bufCreateLock);
1374                 lock_ObtainWrite(&buf_globalLock);
1375
1376                 /*
1377                  * Since we dropped the locks we need to verify that
1378                  * another thread has not allocated the buffer for us.
1379                  */
1380                 if (buf_ExistsLocked(scp, offsetp)) {
1381                     lock_ReleaseWrite(&buf_globalLock);
1382                     lock_ReleaseRead(&scp->bufCreateLock);
1383                     return CM_BUF_EXISTS;
1384                 }
1385
1386                 /*
1387                  * We just cleaned this buffer so we need to
1388                  * restart the loop with this buffer so it
1389                  * can be retested.  Set 'cleaned' so we
1390                  * do not attempt another call to buf_Clean()
1391                  * if the prior attempt failed.
1392                  */
1393                 cleaned = 1;
1394                 goto retry_2;
1395             }
1396
1397             osi_Log3(afsd_logp, "buf_GetNewLocked: scp 0x%p examined %u buffers before recycling bufp 0x%p",
1398                      scp, n_bufs, bp);
1399             osi_Log4(afsd_logp, "... nonzero %u; own %u; busy %u; dirty %u", n_nonzero, n_own, n_busy, n_dirty);
1400
1401             /* if we get here, we know that the buffer still has a 0
1402              * ref count, and that it is clean and has no currently
1403              * pending I/O.  This is the dude to return.
1404              * Remember that as long as the ref count is 0, we know
1405              * that we won't have any lock conflicts, so we can grab
1406              * the buffer lock out of order in the locking hierarchy.
1407              */
1408             buf_Recycle(bp);
1409
1410             /* now hash in as our new buffer, and give it the
1411              * appropriate label, if requested.
1412              */
1413             if (scp) {
1414                 lock_AssertWrite(&buf_globalLock);
1415
1416                 _InterlockedOr(&bp->qFlags, CM_BUF_QINHASH);
1417                 bp->fid = scp->fid;
1418 #ifdef DEBUG
1419                 bp->scp = scp;
1420 #endif
1421                 bp->offset = *offsetp;
1422                 i = BUF_HASH(&scp->fid, offsetp);
1423                 bp->hashp = cm_data.buf_scacheHashTablepp[i];
1424                 cm_data.buf_scacheHashTablepp[i] = bp;
1425                 i = BUF_FILEHASH(&scp->fid);
1426                 nextBp = cm_data.buf_fileHashTablepp[i];
1427                 bp->fileHashp = nextBp;
1428                 bp->fileHashBackp = NULL;
1429                 if (nextBp)
1430                     nextBp->fileHashBackp = bp;
1431                 cm_data.buf_fileHashTablepp[i] = bp;
1432             }
1433
1434             /* we should remove it from the lru queue.  It better still be there,
1435              * since we've held the global (big) lock since we found it there.
1436              */
1437             osi_assertx(bp->qFlags & CM_BUF_QINLRU,
1438                          "buf_GetNewLocked: LRU screwup");
1439
1440             osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
1441                            (osi_queue_t **) &cm_data.buf_freeListEndp,
1442                            &bp->q);
1443             _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINLRU);
1444             buf_DecrementFreeCount();
1445
1446             /* prepare to return it.  Give it a refcount */
1447             InterlockedIncrement(&bp->refCount);
1448 #ifdef DEBUG_REFCOUNT
1449             osi_Log2(afsd_logp,"buf_GetNewLocked bp 0x%p ref %d", bp, 1);
1450             afsi_log("%s:%d buf_GetNewLocked bp 0x%p, ref %d", __FILE__, __LINE__, bp, 1);
1451 #endif
1452             /* grab the mutex so that people don't use it
1453              * before the caller fills it with data.  Again, no one
1454              * should have been able to get to this dude to lock it.
1455              */
1456             if (!lock_TryMutex(&bp->mx)) {
1457                 osi_Log2(afsd_logp, "buf_GetNewLocked bp 0x%p cannot be mutex locked.  refCount %d should be 0",
1458                          bp, bp->refCount);
1459                 osi_panic("buf_GetNewLocked: TryMutex failed",__FILE__,__LINE__);
1460             }
1461
1462             lock_ReleaseWrite(&buf_globalLock);
1463             lock_ReleaseRead(&scp->bufCreateLock);
1464
1465             *bufpp = bp;
1466
1467 #ifdef TESTING
1468             buf_ValidateBufQueues();
1469 #endif /* TESTING */
1470             return 0;
1471         } /* for all buffers in lru queue */
1472         lock_ReleaseWrite(&buf_globalLock);
1473         lock_ReleaseRead(&scp->bufCreateLock);
1474
1475         osi_Log2(afsd_logp, "buf_GetNewLocked: Free Buffer List has %u buffers none free; redir %u", n_bufs, n_redir);
1476         osi_Log4(afsd_logp, "... nonzero %u; own %u; busy %u; dirty %u", n_nonzero, n_own, n_busy, n_dirty);
1477
1478         if (RDR_Initialized) {
1479             afs_uint32 code;
1480           rdr_release:
1481             code = buf_RDRShakeSomeExtentsFree(reqp, TRUE, 2 /* seconds */);
1482             switch (code) {
1483             case CM_ERROR_RETRY:
1484             case 0:
1485                 goto retry;
1486             case CM_ERROR_WOULDBLOCK:
1487                 return CM_ERROR_WOULDBLOCK;
1488             }
1489         }
1490
1491         Sleep(100);             /* give some time for a buffer to be freed */
1492     }   /* while loop over everything */
1493     /* not reached */
1494 } /* the proc */
1495
1496 /*
1497  * get a page, returning it held but unlocked.  the page may or may not
1498  * contain valid data.
1499  *
1500  * The scp must be unlocked when passed in unlocked.
1501  */
1502 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_req_t *reqp, cm_buf_t **bufpp)
1503 {
1504     cm_buf_t *bp;
1505     long code;
1506     osi_hyper_t pageOffset;
1507     unsigned long tcount;
1508     int created;
1509     long lcount = 0;
1510 #ifdef DISKCACHE95
1511     cm_diskcache_t *dcp;
1512 #endif /* DISKCACHE95 */
1513
1514     created = 0;
1515     pageOffset.HighPart = offsetp->HighPart;
1516     pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
1517     while (!created) {
1518         lcount++;
1519 #ifdef TESTING
1520         buf_ValidateBufQueues();
1521 #endif /* TESTING */
1522
1523         bp = buf_Find(&scp->fid, &pageOffset);
1524         if (bp) {
1525             /* lock it and break out */
1526             lock_ObtainMutex(&bp->mx);
1527
1528 #ifdef DISKCACHE95
1529             /* touch disk chunk to update LRU info */
1530             diskcache_Touch(bp->dcp);
1531 #endif /* DISKCACHE95 */
1532             break;
1533         }
1534
1535         /* otherwise, we have to create a page */
1536         code = buf_GetNewLocked(scp, &pageOffset, reqp, &bp);
1537         switch (code) {
1538         case 0:
1539             /* the requested buffer was created */
1540             created = 1;
1541             break;
1542         case CM_BUF_EXISTS:
1543             /*
1544              * the requested buffer existed by the time the
1545              * scp->bufCreateLock and buf_globalLock could be obtained.
1546              * loop again and permit buf_Find() to obtain a reference.
1547              */
1548             break;
1549         default:
1550             /*
1551              * the requested buffer could not be created.
1552              * return the error to the caller.
1553              */
1554 #ifdef TESTING
1555             buf_ValidateBufQueues();
1556 #endif /* TESTING */
1557             return code;
1558         }
1559     } /* big while loop */
1560
1561     /* if we get here, we have a locked buffer that may have just been
1562      * created, in which case it needs to be filled with data.
1563      */
1564     if (created) {
1565         /* load the page; freshly created pages should be idle */
1566         osi_assertx(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)), "incorrect cm_buf_t flags");
1567
1568         /*
1569          * start the I/O; may drop lock.  as of this writing, the only
1570          * implementation of Readp is cm_BufRead() which simply sets
1571          * tcount to 0 and returns success.
1572          */
1573         _InterlockedOr(&bp->flags, CM_BUF_READING);
1574         code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
1575
1576 #ifdef DISKCACHE95
1577         code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
1578         bp->dcp = dcp;    /* pointer to disk cache struct. */
1579 #endif /* DISKCACHE95 */
1580
1581         if (code != 0) {
1582             /* failure or queued */
1583
1584             /* unless cm_BufRead() is altered, this path cannot be hit */
1585             if (code != ERROR_IO_PENDING) {
1586                 bp->error = code;
1587                 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
1588                 _InterlockedAnd(&bp->flags, ~CM_BUF_READING);
1589                 if (bp->flags & CM_BUF_WAITING) {
1590                     osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1591                     osi_Wakeup((LONG_PTR) bp);
1592                 }
1593                 lock_ReleaseMutex(&bp->mx);
1594                 buf_Release(bp);
1595 #ifdef TESTING
1596                 buf_ValidateBufQueues();
1597 #endif /* TESTING */
1598                 return code;
1599             }
1600         } else {
1601             /*
1602              * otherwise, I/O completed instantly and we're done, except
1603              * for padding the xfr out with 0s and checking for EOF
1604              */
1605             if (tcount < (unsigned long) cm_data.buf_blockSize) {
1606                 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
1607                 if (tcount == 0)
1608                     _InterlockedOr(&bp->flags, CM_BUF_EOF);
1609             }
1610             _InterlockedAnd(&bp->flags, ~CM_BUF_READING);
1611             if (bp->flags & CM_BUF_WAITING) {
1612                 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1613                 osi_Wakeup((LONG_PTR) bp);
1614             }
1615         }
1616     } /* if created */
1617
1618     /* wait for reads, either that which we started above, or that someone
1619      * else started.  We don't care if we return a buffer being cleaned.
1620      */
1621     if (bp->flags & CM_BUF_READING)
1622         buf_WaitIO(scp, bp);
1623
1624     /* once it has been read once, we can unlock it and return it, still
1625      * with its refcount held.
1626      */
1627     lock_ReleaseMutex(&bp->mx);
1628     *bufpp = bp;
1629
1630     /* now remove from queue; will be put in at the head (farthest from
1631      * being recycled) when we're done in buf_Release.
1632      */
1633     lock_ObtainWrite(&buf_globalLock);
1634     if (bp->qFlags & CM_BUF_QINLRU) {
1635         osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
1636                        (osi_queue_t **) &cm_data.buf_freeListEndp,
1637                        &bp->q);
1638         _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINLRU);
1639         buf_DecrementFreeCount();
1640     }
1641     lock_ReleaseWrite(&buf_globalLock);
1642
1643     osi_Log4(buf_logp, "buf_Get returning bp 0x%p for scp 0x%p, offset 0x%x:%08x",
1644               bp, scp, offsetp->HighPart, offsetp->LowPart);
1645 #ifdef TESTING
1646     buf_ValidateBufQueues();
1647 #endif /* TESTING */
1648     return 0;
1649 }
1650
1651 /* clean a buffer synchronously */
1652 afs_uint32 buf_Clean(cm_scache_t *scp, cm_buf_t *bp, cm_req_t *reqp, afs_uint32 flags, afs_uint32 *pisdirty)
1653 {
1654     long code;
1655     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1656     osi_assertx(!(flags & CM_BUF_WRITE_SCP_LOCKED), "scp->rw must not be held when calling buf_CleanAsync");
1657
1658     lock_ObtainMutex(&bp->mx);
1659     code = buf_CleanLocked(scp, bp, reqp, flags, pisdirty);
1660     lock_ReleaseMutex(&bp->mx);
1661
1662     return code;
1663 }
1664
1665 /* wait for a buffer's cleaning to finish */
1666 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp, afs_uint32 locked)
1667 {
1668     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1669
1670     if (!locked)
1671         lock_ObtainMutex(&bp->mx);
1672     if (bp->flags & CM_BUF_WRITING) {
1673         buf_WaitIO(scp, bp);
1674     }
1675     if (!locked)
1676         lock_ReleaseMutex(&bp->mx);
1677 }
1678
1679 /* set the dirty flag on a buffer, and set associated write-ahead log,
1680  * if there is one.  Allow one to be added to a buffer, but not changed.
1681  *
1682  * The buffer must be locked before calling this routine.
1683  */
1684 void buf_SetDirty(cm_buf_t *bp, cm_req_t *reqp, afs_uint32 offset, afs_uint32 length, cm_user_t *userp)
1685 {
1686     osi_assertx(bp->magic == CM_BUF_MAGIC, "invalid cm_buf_t magic");
1687     osi_assertx(bp->refCount > 0, "cm_buf_t refcount 0");
1688     osi_assertx(userp != NULL, "userp is NULL");
1689
1690     if (length == 0)
1691         return;
1692
1693     if (bp->flags & CM_BUF_DIRTY) {
1694
1695         osi_Log1(buf_logp, "buf_SetDirty 0x%p already dirty", bp);
1696
1697         if (bp->dirty_offset <= offset) {
1698             if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1699                 /* dirty_length remains the same */
1700             } else {
1701                 bp->dirty_length = offset + length - bp->dirty_offset;
1702             }
1703         } else /* bp->dirty_offset > offset */ {
1704             if (bp->dirty_offset + bp->dirty_length >= offset + length) {
1705                 bp->dirty_length = bp->dirty_offset + bp->dirty_length - offset;
1706             } else {
1707                 bp->dirty_length = length;
1708             }
1709             bp->dirty_offset = offset;
1710         }
1711     } else {
1712         osi_Log1(buf_logp, "buf_SetDirty 0x%p", bp);
1713
1714         /* set dirty bit */
1715         _InterlockedOr(&bp->flags, CM_BUF_DIRTY);
1716
1717         /* and turn off EOF flag, since it has associated data now */
1718         _InterlockedAnd(&bp->flags, ~CM_BUF_EOF);
1719
1720         bp->dirty_offset = offset;
1721         bp->dirty_length = length;
1722
1723         /*
1724          * if the request is not from the afs redirector,
1725          * add to the dirty list.  The redirector interface ensures
1726          * that a background store operation is queued for each and
1727          * every dirty extent that is released.  Therefore, the
1728          * buf_IncrSyncer thread is not required to ensure that
1729          * dirty buffers are written to the file server.
1730          *
1731          * we obtain a hold on the buffer for as long as it remains
1732          * in the list.  buffers are only removed from the list by
1733          * the buf_IncrSyncer function regardless of when else the
1734          * dirty flag might be cleared.
1735          *
1736          * This should never happen but just in case there is a bug
1737          * elsewhere, never add to the dirty list if the buffer is
1738          * already there.
1739          */
1740         if (!(reqp->flags & CM_REQ_SOURCE_REDIR)) {
1741             lock_ObtainWrite(&buf_globalLock);
1742             if (!(bp->qFlags & CM_BUF_QINDL)) {
1743                 buf_HoldLocked(bp);
1744                 if (!cm_data.buf_dirtyListp) {
1745                     cm_data.buf_dirtyListp = cm_data.buf_dirtyListEndp = bp;
1746                 } else {
1747                     cm_data.buf_dirtyListEndp->dirtyp = bp;
1748                     cm_data.buf_dirtyListEndp = bp;
1749                 }
1750                 bp->dirtyp = NULL;
1751                 _InterlockedOr(&bp->qFlags, CM_BUF_QINDL);
1752             }
1753             lock_ReleaseWrite(&buf_globalLock);
1754         }
1755     }
1756
1757     /* and record the last writer */
1758     if (bp->userp != userp) {
1759         cm_HoldUser(userp);
1760         if (bp->userp)
1761             cm_ReleaseUser(bp->userp);
1762         bp->userp = userp;
1763     }
1764 }
1765
1766 /* clean all buffers, reset log pointers and invalidate all buffers.
1767  * Called with no locks held, and returns with same.
1768  *
1769  * This function is guaranteed to clean and remove the log ptr of all the
1770  * buffers that were dirty or had non-zero log ptrs before the call was
1771  * made.  That's sufficient to clean up any garbage left around by recovery,
1772  * which is all we're counting on this for; there may be newly created buffers
1773  * added while we're running, but that should be OK.
1774  *
1775  * In an environment where there are no transactions (artificially imposed, for
1776  * example, when switching the database to raw mode), this function is used to
1777  * make sure that all updates have been written to the disk.  In that case, we don't
1778  * really require that we forget the log association between pages and logs, but
1779  * it also doesn't hurt.  Since raw mode I/O goes through this buffer package, we don't
1780  * have to worry about invalidating data in the buffers.
1781  *
1782  * This function is used at the end of recovery as paranoia to get the recovered
1783  * database out to disk.  It removes all references to the recovery log and cleans
1784  * all buffers.
1785  */
1786 long buf_CleanAndReset(void)
1787 {
1788     afs_uint32 i;
1789     cm_buf_t *bp;
1790     cm_req_t req;
1791
1792     lock_ObtainRead(&buf_globalLock);
1793     for(i=0; i<cm_data.buf_hashSize; i++) {
1794         for(bp = cm_data.buf_scacheHashTablepp[i]; bp; bp = bp->hashp) {
1795             if (bp->qFlags & CM_BUF_QREDIR) {
1796                 osi_Log1(buf_logp,"buf_CleanAndReset buffer held by redirector bp 0x%p", bp);
1797
1798                 /* Request single extent from the redirector */
1799                 buf_RDRShakeAnExtentFree(bp, &req);
1800             }
1801
1802             if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1803                 buf_HoldLocked(bp);
1804                 lock_ReleaseRead(&buf_globalLock);
1805
1806                 /* now no locks are held; clean buffer and go on */
1807                 cm_InitReq(&req);
1808                 req.flags |= CM_REQ_NORETRY;
1809
1810                 buf_Clean(NULL, bp, &req, 0, NULL);
1811                 buf_CleanWait(NULL, bp, FALSE);
1812
1813                 /* relock and release buffer */
1814                 lock_ObtainRead(&buf_globalLock);
1815                 buf_ReleaseLocked(bp, FALSE);
1816             } /* dirty */
1817         } /* over one bucket */
1818     }   /* for loop over all hash buckets */
1819
1820     /* release locks */
1821     lock_ReleaseRead(&buf_globalLock);
1822
1823 #ifdef TESTING
1824     buf_ValidateBufQueues();
1825 #endif /* TESTING */
1826
1827     /* and we're done */
1828     return 0;
1829 }
1830
1831 /* called without global lock being held, reserves buffers for callers
1832  * that need more than one held (not locked) at once.
1833  */
1834 void buf_ReserveBuffers(afs_uint64 nbuffers)
1835 {
1836     lock_ObtainWrite(&buf_globalLock);
1837     while (1) {
1838         if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1839             cm_data.buf_reserveWaiting = 1;
1840             osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1841             osi_SleepW((LONG_PTR) &cm_data.buf_reservedBufs, &buf_globalLock);
1842             lock_ObtainWrite(&buf_globalLock);
1843         }
1844         else {
1845             cm_data.buf_reservedBufs += nbuffers;
1846             break;
1847         }
1848     }
1849     lock_ReleaseWrite(&buf_globalLock);
1850 }
1851
1852 int buf_TryReserveBuffers(afs_uint64 nbuffers)
1853 {
1854     int code;
1855
1856     lock_ObtainWrite(&buf_globalLock);
1857     if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1858         code = 0;
1859     }
1860     else {
1861         cm_data.buf_reservedBufs += nbuffers;
1862         code = 1;
1863     }
1864     lock_ReleaseWrite(&buf_globalLock);
1865     return code;
1866 }
1867
1868 /* called without global lock held, releases reservation held by
1869  * buf_ReserveBuffers.
1870  */
1871 void buf_UnreserveBuffers(afs_uint64 nbuffers)
1872 {
1873     lock_ObtainWrite(&buf_globalLock);
1874     cm_data.buf_reservedBufs -= nbuffers;
1875     if (cm_data.buf_reserveWaiting) {
1876         cm_data.buf_reserveWaiting = 0;
1877         osi_Wakeup((LONG_PTR) &cm_data.buf_reservedBufs);
1878     }
1879     lock_ReleaseWrite(&buf_globalLock);
1880 }
1881
1882 /* truncate the buffers past sizep, zeroing out the page, if we don't
1883  * end on a page boundary.
1884  *
1885  * Requires cm_bufCreateLock to be write locked.
1886  */
1887 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1888                    osi_hyper_t *sizep)
1889 {
1890     cm_buf_t *bufp;
1891     cm_buf_t *nbufp;                    /* next buffer, if didRelease */
1892     osi_hyper_t bufEnd;
1893     long code;
1894     long bufferPos;
1895     afs_uint32 i;
1896     afs_uint32 invalidate = 0;
1897
1898     /* assert that cm_bufCreateLock is held in write mode */
1899     lock_AssertWrite(&scp->bufCreateLock);
1900
1901     i = BUF_FILEHASH(&scp->fid);
1902
1903     lock_ObtainRead(&buf_globalLock);
1904     bufp = cm_data.buf_fileHashTablepp[i];
1905     if (bufp == NULL) {
1906         lock_ReleaseRead(&buf_globalLock);
1907         return 0;
1908     }
1909
1910     buf_HoldLocked(bufp);
1911     lock_ReleaseRead(&buf_globalLock);
1912
1913     while (bufp) {
1914         lock_ObtainMutex(&bufp->mx);
1915
1916         bufEnd.HighPart = 0;
1917         bufEnd.LowPart = cm_data.buf_blockSize;
1918         bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1919
1920         if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1921              LargeIntegerLessThan(*sizep, bufEnd)) {
1922             buf_WaitIO(scp, bufp);
1923         }
1924         lock_ObtainWrite(&scp->rw);
1925
1926         /* make sure we have a callback (so we have the right value for
1927          * the length), and wait for it to be safe to do a truncate.
1928          */
1929         code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1930                           CM_SCACHESYNC_NEEDCALLBACK
1931                           | CM_SCACHESYNC_GETSTATUS
1932                           | CM_SCACHESYNC_SETSIZE
1933                           | CM_SCACHESYNC_BUFLOCKED);
1934
1935
1936         /* if we succeeded in our locking, and this applies to the right
1937          * file, and the truncate request overlaps the buffer either
1938          * totally or partially, then do something.
1939          */
1940         if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1941              && LargeIntegerLessThan(*sizep, bufEnd)) {
1942
1943
1944             /* destroy the buffer, turning off its dirty bit, if
1945              * we're truncating the whole buffer.  Otherwise, set
1946              * the dirty bit, and clear out the tail of the buffer
1947              * if we just overlap some.
1948              */
1949             if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1950                 /* truncating the entire page */
1951                 if (reqp->flags & CM_REQ_SOURCE_REDIR) {
1952                     /*
1953                      * Implicitly clear the redirector flag
1954                      * and release the matching hold.
1955                      */
1956                     if (bufp->qFlags & CM_BUF_QREDIR) {
1957                         osi_Log4(buf_logp,"buf_Truncate taking from file system bufp 0x%p vno 0x%x foffset 0x%x:%x",
1958                                  bufp, bufp->fid.vnode, bufp->offset.HighPart, bufp->offset.LowPart);
1959                         lock_ObtainWrite(&buf_globalLock);
1960                         if (bufp->qFlags & CM_BUF_QREDIR) {
1961                             buf_RemoveFromRedirQueue(scp, bufp);
1962                             buf_ReleaseLocked(bufp, TRUE);
1963                         }
1964                         lock_ReleaseWrite(&buf_globalLock);
1965                     }
1966                 } else {
1967                     invalidate = 1;
1968                 }
1969                 _InterlockedAnd(&bufp->flags, ~CM_BUF_DIRTY);
1970                 bufp->error = 0;
1971                 bufp->dirty_length = 0;
1972                 bufp->dataVersion = CM_BUF_VERSION_BAD; /* known bad */
1973                 bufp->dirtyCounter++;
1974             }
1975             else {
1976                 /* don't set dirty, since dirty implies
1977                  * currently up-to-date.  Don't need to do this,
1978                  * since we'll update the length anyway.
1979                  *
1980                  * Zero out remainder of the page, in case we
1981                  * seek and write past EOF, and make this data
1982                  * visible again.
1983                  */
1984                 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1985                 osi_assertx(bufferPos != 0, "non-zero bufferPos");
1986                 memset(bufp->datap + bufferPos, 0,
1987                         cm_data.buf_blockSize - bufferPos);
1988             }
1989         }
1990
1991         cm_SyncOpDone( scp, bufp,
1992                        CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
1993                        | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_BUFLOCKED);
1994
1995         lock_ReleaseWrite(&scp->rw);
1996         lock_ReleaseMutex(&bufp->mx);
1997
1998         if (!code) {
1999             nbufp = bufp->fileHashp;
2000             if (nbufp)
2001                 buf_Hold(nbufp);
2002         } else {
2003             /* This forces the loop to end and the error code
2004              * to be returned. */
2005             nbufp = NULL;
2006         }
2007         buf_Release(bufp);
2008         bufp = nbufp;
2009     }
2010
2011 #ifdef TESTING
2012     buf_ValidateBufQueues();
2013 #endif /* TESTING */
2014
2015     if (invalidate && RDR_Initialized)
2016         RDR_InvalidateObject(scp->fid.cell, scp->fid.volume, scp->fid.vnode,
2017                              scp->fid.unique, scp->fid.hash,
2018                              scp->fileType, AFS_INVALIDATE_SMB);
2019
2020     /* done */
2021     return code;
2022 }
2023
2024 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
2025 {
2026     long code;
2027     cm_buf_t *bp;               /* buffer we're hacking on */
2028     cm_buf_t *nbp;
2029     int didRelease;
2030     afs_uint32 i;
2031     afs_uint32 stable = 0;
2032
2033     i = BUF_FILEHASH(&scp->fid);
2034
2035     code = 0;
2036     lock_ObtainRead(&buf_globalLock);
2037     bp = cm_data.buf_fileHashTablepp[i];
2038     if (bp)
2039         buf_HoldLocked(bp);
2040     lock_ReleaseRead(&buf_globalLock);
2041
2042     for (; bp; bp = nbp) {
2043         didRelease = 0; /* haven't released this buffer yet */
2044
2045         /* clean buffer synchronously */
2046         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2047
2048             if (code == 0 && !stable && (bp->flags & CM_BUF_DIRTY)) {
2049                 /*
2050                  * we must stabilize the object to ensure that buffer
2051                  * changes cannot occur while the flush is performed.
2052                  * However, we do not want to Stabilize if we do not
2053                  * need to because Stabilize obtains a callback.
2054                  */
2055                 code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
2056                 stable = (code == 0);
2057             }
2058
2059             if (code == CM_ERROR_BADFD) {
2060                 /* if the scp's FID is bad its because we received VNOVNODE
2061                  * when attempting to FetchStatus before the write.  This
2062                  * page therefore contains data that can no longer be stored.
2063                  */
2064                 lock_ObtainMutex(&bp->mx);
2065                 _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
2066                 _InterlockedOr(&bp->flags, CM_BUF_ERROR);
2067                 bp->error = CM_ERROR_BADFD;
2068                 bp->dirty_length = 0;
2069                 bp->dataVersion = CM_BUF_VERSION_BAD;   /* known bad */
2070                 bp->dirtyCounter++;
2071                 lock_ReleaseMutex(&bp->mx);
2072             } else if (!(scp->flags & CM_SCACHEFLAG_RO)) {
2073                 if (code) {
2074                     goto skip;
2075                 }
2076
2077                 lock_ObtainMutex(&bp->mx);
2078
2079                 /* start cleaning the buffer, and wait for it to finish */
2080                 buf_CleanLocked(scp, bp, reqp, 0, NULL);
2081                 buf_WaitIO(scp, bp);
2082
2083                 lock_ReleaseMutex(&bp->mx);
2084             }
2085
2086             /* actually, we only know that buffer is clean if ref
2087              * count is 1, since we don't have buffer itself locked.
2088              */
2089             if (!(bp->flags & CM_BUF_DIRTY) && !(bp->qFlags & CM_BUF_QREDIR)) {
2090                 lock_ObtainWrite(&buf_globalLock);
2091                 if (!(bp->flags & CM_BUF_DIRTY) && !(bp->qFlags & CM_BUF_QREDIR)) {
2092                     if (bp->refCount == 1) {    /* bp is held above */
2093                         nbp = bp->fileHashp;
2094                         if (nbp)
2095                             buf_HoldLocked(nbp);
2096                         buf_ReleaseLocked(bp, TRUE);
2097                         didRelease = 1;
2098                         buf_Recycle(bp);
2099                     }
2100                 }
2101                 lock_ReleaseWrite(&buf_globalLock);
2102             }
2103         }
2104
2105       skip:
2106         if (!didRelease) {
2107             lock_ObtainRead(&buf_globalLock);
2108             nbp = bp->fileHashp;
2109             if (nbp)
2110                 buf_HoldLocked(nbp);
2111             buf_ReleaseLocked(bp, FALSE);
2112             lock_ReleaseRead(&buf_globalLock);
2113         }
2114     }   /* for loop over a bunch of buffers */
2115
2116     if (stable)
2117         (*cm_buf_opsp->Unstabilizep)(scp, userp);
2118
2119 #ifdef TESTING
2120     buf_ValidateBufQueues();
2121 #endif /* TESTING */
2122
2123     /* done */
2124     return code;
2125 }
2126
2127 /* Must be called with scp->rw held */
2128 long buf_InvalidateBuffers(cm_scache_t * scp)
2129 {
2130     cm_buf_t * bp;
2131     afs_uint32 i;
2132     int found = 0;
2133
2134     lock_AssertAny(&scp->rw);
2135
2136     i = BUF_FILEHASH(&scp->fid);
2137
2138     lock_ObtainRead(&buf_globalLock);
2139
2140     for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp = bp->fileHashp) {
2141         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2142             bp->dataVersion = CM_BUF_VERSION_BAD;
2143             found = 1;
2144         }
2145     }
2146     lock_ReleaseRead(&buf_globalLock);
2147
2148     if (found)
2149         return 0;
2150     else
2151         return ENOENT;
2152 }
2153
2154 /* Must be called with scp->rw held */
2155 long buf_ForceDataVersion(cm_scache_t * scp, afs_uint64 fromVersion, afs_uint64 toVersion)
2156 {
2157     cm_buf_t * bp;
2158     afs_uint32 i;
2159     int found = 0;
2160
2161     lock_AssertAny(&scp->rw);
2162
2163     i = BUF_FILEHASH(&scp->fid);
2164
2165     lock_ObtainRead(&buf_globalLock);
2166
2167     for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp = bp->fileHashp) {
2168         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2169             if (bp->dataVersion == fromVersion) {
2170                 bp->dataVersion = toVersion;
2171                 found = 1;
2172             }
2173         }
2174     }
2175     lock_ReleaseRead(&buf_globalLock);
2176
2177     if (found)
2178         return 0;
2179     else
2180         return ENOENT;
2181 }
2182
2183 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
2184 {
2185     long code = 0;
2186     long wasDirty = 0;
2187     cm_buf_t *bp;               /* buffer we're hacking on */
2188     cm_buf_t *nbp;              /* next one */
2189     afs_uint32 i;
2190
2191     if (RDR_Initialized && scp->redirBufCount > 0) {
2192         /* Retrieve all extents for this file from the redirector */
2193         buf_RDRShakeFileExtentsFree(scp, reqp);
2194     }
2195
2196     i = BUF_FILEHASH(&scp->fid);
2197
2198     lock_ObtainRead(&buf_globalLock);
2199     bp = cm_data.buf_fileHashTablepp[i];
2200     if (bp)
2201         buf_HoldLocked(bp);
2202     lock_ReleaseRead(&buf_globalLock);
2203     for (; bp; bp = nbp) {
2204         /* clean buffer synchronously */
2205         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
2206             /*
2207              * If the buffer is held by the redirector we must fetch
2208              * it back in order to determine whether or not it is in
2209              * fact dirty.
2210              */
2211             lock_ObtainRead(&buf_globalLock);
2212             if (bp->qFlags & CM_BUF_QREDIR) {
2213                 osi_Log1(buf_logp,"buf_CleanVnode buffer held by redirector bp 0x%p", bp);
2214
2215                 /* Retrieve single extent from the redirector */
2216                 buf_RDRShakeAnExtentFree(bp, reqp);
2217             }
2218             lock_ReleaseRead(&buf_globalLock);
2219
2220             lock_ObtainMutex(&bp->mx);
2221             if ((bp->flags & CM_BUF_DIRTY)) {
2222                 if (userp && userp != bp->userp) {
2223                     cm_HoldUser(userp);
2224                     if (bp->userp)
2225                         cm_ReleaseUser(bp->userp);
2226                     bp->userp = userp;
2227                 }
2228
2229                 switch (code) {
2230                 case CM_ERROR_NOSUCHFILE:
2231                 case CM_ERROR_BADFD:
2232                 case CM_ERROR_NOACCESS:
2233                 case CM_ERROR_QUOTA:
2234                 case CM_ERROR_SPACE:
2235                 case CM_ERROR_TOOBIG:
2236                 case CM_ERROR_READONLY:
2237                 case CM_ERROR_NOSUCHPATH:
2238                 case EIO:
2239                     /*
2240                      * Apply the previous fatal error to this buffer.
2241                      * Do not waste the time attempting to store to
2242                      * the file server when we know it will fail.
2243                      */
2244                     _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
2245                     _InterlockedOr(&bp->flags, CM_BUF_ERROR);
2246                     bp->dirty_length = 0;
2247                     bp->error = code;
2248                     bp->dataVersion = CM_BUF_VERSION_BAD;
2249                     bp->dirtyCounter++;
2250                     break;
2251                 case CM_ERROR_TIMEDOUT:
2252                 case CM_ERROR_ALLDOWN:
2253                 case CM_ERROR_ALLBUSY:
2254                 case CM_ERROR_ALLOFFLINE:
2255                 case CM_ERROR_CLOCKSKEW:
2256                     /* do not mark the buffer in error state but do
2257                      * not attempt to complete the rest either.
2258                      */
2259                     break;
2260                 default:
2261                     code = buf_CleanLocked(scp, bp, reqp, 0, &wasDirty);
2262                     if (bp->flags & CM_BUF_ERROR) {
2263                         code = bp->error;
2264                         if (code == 0)
2265                             code = -1;
2266                     }
2267                 }
2268                 buf_CleanWait(scp, bp, TRUE);
2269             }
2270             lock_ReleaseMutex(&bp->mx);
2271         }
2272
2273         lock_ObtainRead(&buf_globalLock);
2274         nbp = bp->fileHashp;
2275         if (nbp)
2276             buf_HoldLocked(nbp);
2277         buf_ReleaseLocked(bp, FALSE);
2278         lock_ReleaseRead(&buf_globalLock);
2279     }   /* for loop over a bunch of buffers */
2280
2281 #ifdef TESTING
2282     buf_ValidateBufQueues();
2283 #endif /* TESTING */
2284
2285     /* done */
2286     return code;
2287 }
2288
2289 #ifdef TESTING
2290 void
2291 buf_ValidateBufQueues(void)
2292 {
2293     cm_buf_t * bp, *bpb, *bpf, *bpa;
2294     afs_uint32 countf=0, countb=0, counta=0;
2295
2296     lock_ObtainRead(&buf_globalLock);
2297     for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
2298         if (bp->magic != CM_BUF_MAGIC)
2299             osi_panic("buf magic error",__FILE__,__LINE__);
2300         countb++;
2301         bpb = bp;
2302     }
2303
2304     for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
2305         if (bp->magic != CM_BUF_MAGIC)
2306             osi_panic("buf magic error",__FILE__,__LINE__);
2307         countf++;
2308         bpf = bp;
2309     }
2310
2311     for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
2312         if (bp->magic != CM_BUF_MAGIC)
2313             osi_panic("buf magic error",__FILE__,__LINE__);
2314         counta++;
2315         bpa = bp;
2316     }
2317     lock_ReleaseRead(&buf_globalLock);
2318
2319     if (countb != countf)
2320         osi_panic("buf magic error",__FILE__,__LINE__);
2321
2322     if (counta != cm_data.buf_nbuffers)
2323         osi_panic("buf magic error",__FILE__,__LINE__);
2324 }
2325 #endif /* TESTING */
2326
2327 /* dump the contents of the buf_scacheHashTablepp. */
2328 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
2329 {
2330     int zilch;
2331     cm_buf_t *bp;
2332     char output[1024];
2333     afs_uint32 i;
2334
2335     if (cm_data.buf_scacheHashTablepp == NULL)
2336         return -1;
2337
2338     if (lock)
2339         lock_ObtainRead(&buf_globalLock);
2340
2341     StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\r\n",
2342                     cookie, cm_data.buf_hashSize);
2343     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2344
2345     for (i = 0; i < cm_data.buf_hashSize; i++)
2346     {
2347         for (bp = cm_data.buf_scacheHashTablepp[i]; bp; bp=bp->hashp)
2348         {
2349             StringCbPrintfA(output, sizeof(output),
2350                             "%s bp=0x%08X, hash=%d, fid (cell=%d, volume=%d, "
2351                             "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2352                             "flags=0x%x, qFlags=0x%x cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2353                              cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume,
2354                              bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2355                              bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2356                              bp->cmFlags, bp->error, bp->refCount);
2357             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2358         }
2359     }
2360
2361     StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\r\n", cookie);
2362     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2363
2364     StringCbPrintfA(output, sizeof(output), "%s - dumping buf_freeListEndp\r\n", cookie);
2365     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2366     for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
2367         StringCbPrintfA(output, sizeof(output),
2368                          "%s bp=0x%08X, fid (cell=%d, volume=%d, "
2369                          "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2370                          "flags=0x%x, qFlags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2371                          cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
2372                          bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2373                          bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2374                          bp->cmFlags, bp->error, bp->refCount);
2375         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2376     }
2377     StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_FreeListEndp.\r\n", cookie);
2378     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2379
2380     StringCbPrintfA(output, sizeof(output), "%s - dumping buf_dirtyListp\r\n", cookie);
2381     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2382     for(bp = cm_data.buf_dirtyListp; bp; bp=bp->dirtyp) {
2383         StringCbPrintfA(output, sizeof(output),
2384                          "%s bp=0x%08X, fid (cell=%d, volume=%d, "
2385                          "vnode=%d, unique=%d), offset=%x:%08x, dv=%I64d, "
2386                          "flags=0x%x, qFlags=0x%x, cmFlags=0x%x, error=0x%x, refCount=%d\r\n",
2387                          cookie, (void *)bp, bp->fid.cell, bp->fid.volume,
2388                          bp->fid.vnode, bp->fid.unique, bp->offset.HighPart,
2389                          bp->offset.LowPart, bp->dataVersion, bp->flags, bp->qFlags,
2390                          bp->cmFlags, bp->error, bp->refCount);
2391         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2392     }
2393     StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_dirtyListp.\r\n", cookie);
2394     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2395
2396     if (lock)
2397         lock_ReleaseRead(&buf_globalLock);
2398     return 0;
2399 }
2400
2401 void buf_ForceTrace(BOOL flush)
2402 {
2403     HANDLE handle;
2404     int len;
2405     char buf[256];
2406
2407     if (!buf_logp)
2408         return;
2409
2410     len = GetTempPath(sizeof(buf)-10, buf);
2411     StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
2412     handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
2413                             NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2414     if (handle == INVALID_HANDLE_VALUE) {
2415         osi_panic("Cannot create log file", __FILE__, __LINE__);
2416     }
2417     osi_LogPrint(buf_logp, handle);
2418     if (flush)
2419         FlushFileBuffers(handle);
2420     CloseHandle(handle);
2421 }
2422
2423 long buf_DirtyBuffersExist(cm_fid_t *fidp)
2424 {
2425     cm_buf_t *bp;
2426     afs_uint32 bcount = 0;
2427     afs_uint32 i;
2428     long found = 0;
2429
2430     i = BUF_FILEHASH(fidp);
2431
2432     lock_ObtainRead(&buf_globalLock);
2433     for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2434         if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
2435             found = 1;
2436             break;
2437         }
2438     }
2439     lock_ReleaseRead(&buf_globalLock);
2440     return found;
2441 }
2442
2443 long buf_RDRBuffersExist(cm_fid_t *fidp)
2444 {
2445     cm_buf_t *bp;
2446     afs_uint32 bcount = 0;
2447     afs_uint32 i;
2448     long found = 0;
2449
2450     if (!RDR_Initialized)
2451         return 0;
2452
2453     i = BUF_FILEHASH(fidp);
2454
2455     lock_ObtainRead(&buf_globalLock);
2456     for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2457         if (!cm_FidCmp(fidp, &bp->fid) && (bp->qFlags & CM_BUF_QREDIR)) {
2458             found = 1;
2459             break;
2460         }
2461     }
2462     lock_ReleaseRead(&buf_globalLock);
2463     return 0;
2464 }
2465
2466 long buf_ClearRDRFlag(cm_scache_t *scp, char *reason)
2467 {
2468     cm_fid_t *fidp = &scp->fid;
2469     cm_buf_t *bp;
2470     afs_uint32 bcount = 0;
2471     afs_uint32 i;
2472
2473     i = BUF_FILEHASH(fidp);
2474
2475     lock_ObtainWrite(&scp->rw);
2476     lock_ObtainRead(&buf_globalLock);
2477     for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=bp->fileHashp, bcount++) {
2478         if (!cm_FidCmp(fidp, &bp->fid) && (bp->qFlags & CM_BUF_QREDIR)) {
2479             lock_ConvertRToW(&buf_globalLock);
2480             if (bp->qFlags & CM_BUF_QREDIR) {
2481                 osi_Log4(buf_logp,"buf_ClearRDRFlag taking from file system bp 0x%p vno 0x%x foffset 0x%x:%x",
2482                           bp, bp->fid.vnode, bp->offset.HighPart, bp->offset.LowPart);
2483                 buf_RemoveFromRedirQueue(scp, bp);
2484                 buf_ReleaseLocked(bp, TRUE);
2485             }
2486             lock_ConvertWToR(&buf_globalLock);
2487         }
2488     }
2489
2490     /* Confirm that there are none left */
2491     lock_ConvertRToW(&buf_globalLock);
2492     for ( bp = redirq_to_cm_buf_t(scp->redirQueueT);
2493           bp;
2494           bp = redirq_to_cm_buf_t(scp->redirQueueT))
2495     {
2496         if (bp->qFlags & CM_BUF_QREDIR) {
2497             osi_Log4(buf_logp,"buf_ClearRDRFlag taking from file system bufp 0x%p vno 0x%x foffset 0x%x:%x",
2498                       bp, bp->fid.vnode, bp->offset.HighPart, bp->offset.LowPart);
2499             buf_RemoveFromRedirQueue(scp, bp);
2500             buf_ReleaseLocked(bp, TRUE);
2501         }
2502
2503     }
2504     lock_ReleaseWrite(&buf_globalLock);
2505     lock_ReleaseWrite(&scp->rw);
2506     return 0;
2507 }
2508
2509 #if 0
2510 long buf_CleanDirtyBuffers(cm_scache_t *scp)
2511 {
2512     cm_buf_t *bp;
2513     afs_uint32 bcount = 0;
2514     cm_fid_t * fidp = &scp->fid;
2515
2516     for (bp = cm_data.buf_allp; bp; bp=bp->allp, bcount++) {
2517         if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
2518             buf_Hold(bp);
2519             lock_ObtainMutex(&bp->mx);
2520             _InterlockedAnd(&bp->cmFlags, ~CM_BUF_CMSTORING);
2521             _InterlockedAnd(&bp->flags, ~CM_BUF_DIRTY);
2522             bp->dirty_length = 0;
2523             _InterlockedOr(&bp->flags, CM_BUF_ERROR);
2524             bp->error = VNOVNODE;
2525             bp->dataVersion = CM_BUF_VERSION_BAD; /* bad */
2526             bp->dirtyCounter++;
2527             if (bp->flags & CM_BUF_WAITING) {
2528                 osi_Log2(buf_logp, "BUF CleanDirtyBuffers Waking [scp 0x%x] bp 0x%x", scp, bp);
2529                 osi_Wakeup((long) &bp);
2530             }
2531             lock_ReleaseMutex(&bp->mx);
2532             buf_Release(bp);
2533         }
2534     }
2535     return 0;
2536 }
2537 #endif
2538
2539 /*
2540  * The following routines will not be used on a
2541  * regular basis but are very useful in a variety
2542  * of scenarios when debugging data corruption.
2543  */
2544 const char *
2545 buf_HexCheckSum(cm_buf_t * bp)
2546 {
2547     int i, k;
2548     static char buf[33];
2549     static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
2550
2551     for (i=0;i<16;i++) {
2552         k = bp->md5cksum[i];
2553
2554         buf[i*2] = tr[k / 16];
2555         buf[i*2+1] = tr[k % 16];
2556     }
2557     buf[32] = '\0';
2558
2559     return buf;
2560 }
2561
2562 void
2563 buf_ComputeCheckSum(cm_buf_t * bp)
2564 {
2565     MD5_CTX md5;
2566
2567     MD5_Init(&md5);
2568     MD5_Update(&md5, bp->datap, cm_data.blockSize);
2569     MD5_Final(bp->md5cksum, &md5);
2570
2571     osi_Log4(buf_logp, "CheckSum bp 0x%p md5 %s, dirty: offset %u length %u",
2572              bp, osi_LogSaveString(buf_logp, buf_HexCheckSum(bp)),
2573              bp->dirty_offset, bp->dirty_length);
2574 }
2575
2576 int
2577 buf_ValidateCheckSum(cm_buf_t * bp)
2578 {
2579     MD5_CTX md5;
2580     unsigned char tmp[16];
2581
2582     MD5_Init(&md5);
2583     MD5_Update(&md5, bp->datap, cm_data.blockSize);
2584     MD5_Final(tmp, &md5);
2585
2586     if (memcmp(tmp, bp->md5cksum, 16) == 0)
2587         return 1;
2588     return 0;
2589 }
2590
2591 void
2592 buf_InsertToRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2593 {
2594     lock_AssertWrite(&buf_globalLock);
2595
2596     if (scp) {
2597         lock_ObtainMutex(&scp->redirMx);
2598     }
2599
2600     if (bufp->qFlags & CM_BUF_QINLRU) {
2601         _InterlockedAnd(&bufp->qFlags, ~CM_BUF_QINLRU);
2602         osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_freeListp,
2603                        (osi_queue_t **) &cm_data.buf_freeListEndp,
2604                        &bufp->q);
2605         buf_DecrementFreeCount();
2606     }
2607     _InterlockedOr(&bufp->qFlags, CM_BUF_QREDIR);
2608     osi_QAddH( (osi_queue_t **) &cm_data.buf_redirListp,
2609                (osi_queue_t **) &cm_data.buf_redirListEndp,
2610                &bufp->q);
2611     buf_IncrementRedirCount();
2612     bufp->redirLastAccess = time(NULL);
2613     if (scp) {
2614         osi_QAddH( (osi_queue_t **) &scp->redirQueueH,
2615                    (osi_queue_t **) &scp->redirQueueT,
2616                    &bufp->redirq);
2617         scp->redirLastAccess = bufp->redirLastAccess;
2618         InterlockedIncrement(&scp->redirBufCount);
2619
2620         lock_ReleaseMutex(&scp->redirMx);
2621     }
2622 }
2623
2624 void
2625 buf_RemoveFromRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2626 {
2627     lock_AssertWrite(&buf_globalLock);
2628
2629     if (!(bufp->qFlags & CM_BUF_QREDIR))
2630         return;
2631
2632     if (scp) {
2633         lock_ObtainMutex(&scp->redirMx);
2634     }
2635
2636     _InterlockedAnd(&bufp->qFlags, ~CM_BUF_QREDIR);
2637     osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_redirListp,
2638                    (osi_queue_t **) &cm_data.buf_redirListEndp,
2639                    &bufp->q);
2640     buf_DecrementRedirCount();
2641
2642     if (scp) {
2643         osi_QRemoveHT( (osi_queue_t **) &scp->redirQueueH,
2644                        (osi_queue_t **) &scp->redirQueueT,
2645                        &bufp->redirq);
2646
2647         InterlockedDecrement(&scp->redirBufCount);
2648         lock_ReleaseMutex(&scp->redirMx);
2649     }
2650 }
2651
2652 void
2653 buf_MoveToHeadOfRedirQueue(cm_scache_t *scp, cm_buf_t *bufp)
2654 {
2655     lock_AssertWrite(&buf_globalLock);
2656     if (!(bufp->qFlags & CM_BUF_QREDIR))
2657         return;
2658
2659     if (scp) {
2660         lock_ObtainMutex(&scp->redirMx);
2661     }
2662
2663     osi_QRemoveHT( (osi_queue_t **) &cm_data.buf_redirListp,
2664                    (osi_queue_t **) &cm_data.buf_redirListEndp,
2665                    &bufp->q);
2666     osi_QAddH( (osi_queue_t **) &cm_data.buf_redirListp,
2667                (osi_queue_t **) &cm_data.buf_redirListEndp,
2668                &bufp->q);
2669     bufp->redirLastAccess = time(NULL);
2670     if (scp) {
2671         osi_QRemoveHT( (osi_queue_t **) &scp->redirQueueH,
2672                        (osi_queue_t **) &scp->redirQueueT,
2673                        &bufp->redirq);
2674         osi_QAddH( (osi_queue_t **) &scp->redirQueueH,
2675                    (osi_queue_t **) &scp->redirQueueT,
2676                    &bufp->redirq);
2677         scp->redirLastAccess = bufp->redirLastAccess;
2678
2679         lock_ReleaseMutex(&scp->redirMx);
2680     }
2681 }