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