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