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