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