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