windows-buf-flush-20061109
[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 <afs/param.h>
13 #include <afs/stds.h>
14
15 #include <windows.h>
16 #include <osi.h>
17 #include <stdio.h>
18 #include <assert.h>
19 #include <strsafe.h>
20 #include <math.h>
21
22 #include "afsd.h"
23 #include "cm_memmap.h"
24
25 #ifdef DEBUG
26 #define TRACE_BUFFER 1
27 #endif
28
29 extern void afsi_log(char *pattern, ...);
30
31 /* This module implements the buffer package used by the local transaction
32  * system (cm).  It is initialized by calling cm_Init, which calls buf_Init;
33  * it must be initalized before any of its main routines are called.
34  *
35  * Each buffer is hashed into a hash table by file ID and offset, and if its
36  * reference count is zero, it is also in a free list.
37  *
38  * There are two locks involved in buffer processing.  The global lock
39  * buf_globalLock protects all of the global variables defined in this module,
40  * the reference counts and hash pointers in the actual cm_buf_t structures,
41  * and the LRU queue pointers in the buffer structures.
42  *
43  * The mutexes in the buffer structures protect the remaining fields in the
44  * buffers, as well the data itself.
45  * 
46  * The locking hierarchy here is this:
47  * 
48  * - resv multiple simul. buffers reservation
49  * - lock buffer I/O flags
50  * - lock buffer's mutex
51  * - lock buf_globalLock
52  *
53  */
54
55 /* global debugging log */
56 osi_log_t *buf_logp = NULL;
57
58 /* Global lock protecting hash tables and free lists */
59 osi_rwlock_t buf_globalLock;
60
61 /* ptr to head of the free list (most recently used) and the
62  * tail (the guy to remove first).  We use osi_Q* functions
63  * to put stuff in buf_freeListp, and maintain the end
64  * pointer manually
65  */
66
67 /* a pointer to a list of all buffers, just so that we can find them
68  * easily for debugging, and for the incr syncer.  Locked under
69  * the global lock.
70  */
71
72 /* defaults setup; these variables may be manually assigned into
73  * before calling cm_Init, as a way of changing these defaults.
74  */
75
76 /* callouts for reading and writing data, etc */
77 cm_buf_ops_t *cm_buf_opsp;
78
79 #ifdef DISKCACHE95
80 /* for experimental disk caching support in Win95 client */
81 cm_buf_t *buf_diskFreeListp;
82 cm_buf_t *buf_diskFreeListEndp;
83 cm_buf_t *buf_diskAllp;
84 extern int cm_diskCacheEnabled;
85 #endif /* DISKCACHE95 */
86
87 /* set this to 1 when we are terminating to prevent access attempts */
88 static int buf_ShutdownFlag = 0;
89
90 void buf_HoldLocked(cm_buf_t *bp)
91 {
92     osi_assert(bp->magic == CM_BUF_MAGIC);
93     bp->refCount++;
94 }
95
96 /* hold a reference to an already held buffer */
97 void buf_Hold(cm_buf_t *bp)
98 {
99     lock_ObtainWrite(&buf_globalLock);
100     buf_HoldLocked(bp);
101     lock_ReleaseWrite(&buf_globalLock);
102 }
103
104 /* code to drop reference count while holding buf_globalLock */
105 void buf_ReleaseLocked(cm_buf_t *bp)
106 {
107     /* ensure that we're in the LRU queue if our ref count is 0 */
108     osi_assert(bp->magic == CM_BUF_MAGIC);
109 #ifdef DEBUG
110     if (bp->refCount == 0)
111         osi_panic("buf refcount 0",__FILE__,__LINE__);;
112 #else
113     osi_assert(bp->refCount > 0);
114 #endif
115     if (--bp->refCount == 0) {
116         if (!(bp->flags & CM_BUF_INLRU)) {
117             osi_QAdd((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
118
119             /* watch for transition from empty to one element */
120             if (!cm_data.buf_freeListEndp)
121                 cm_data.buf_freeListEndp = cm_data.buf_freeListp;
122             bp->flags |= CM_BUF_INLRU;
123         }
124     }
125 }       
126
127 /* release a buffer.  Buffer must be referenced, but unlocked. */
128 void buf_Release(cm_buf_t *bp)
129 {
130     lock_ObtainWrite(&buf_globalLock);
131     buf_ReleaseLocked(bp);
132     lock_ReleaseWrite(&buf_globalLock);
133 }
134
135 /* incremental sync daemon.  Writes 1/10th of all the buffers every 5000 ms */
136 void buf_IncrSyncer(long parm)
137 {
138     cm_buf_t *bp;                       /* buffer we're hacking on; held */
139     long i;                             /* counter */
140     long wasDirty;
141     cm_req_t req;
142
143     lock_ObtainWrite(&buf_globalLock);
144     bp = cm_data.buf_allp;
145     buf_HoldLocked(bp);
146     lock_ReleaseWrite(&buf_globalLock);
147     wasDirty = 0;
148
149     while (buf_ShutdownFlag == 0) {
150         if (!wasDirty) {
151             i = SleepEx(5000, 1);
152             if (i != 0) continue;
153         }
154
155         if (buf_ShutdownFlag == 1)
156             return;
157
158         wasDirty = 0;
159
160         /* now go through our percentage of the buffers */
161         for (i=0; i<cm_data.buf_nbuffers; i++) {
162             /* don't want its identity changing while we're
163              * messing with it, so must do all of this with
164              * bp held.
165              */
166
167             /* start cleaning the buffer; don't touch log pages since
168              * the log code counts on knowing exactly who is writing
169              * a log page at any given instant.
170              */
171             cm_InitReq(&req);
172             req.flags |= CM_REQ_NORETRY;
173             wasDirty |= buf_CleanAsync(bp, &req);
174
175             /* now advance to the next buffer; the allp chain never changes,
176              * and so can be followed even when holding no locks.
177              */
178             lock_ObtainWrite(&buf_globalLock);
179             buf_ReleaseLocked(bp);
180             bp = bp->allp;
181             if (!bp) 
182                 bp = cm_data.buf_allp;
183             buf_HoldLocked(bp);
184             lock_ReleaseWrite(&buf_globalLock);
185         }       /* for loop over a bunch of buffers */
186     }           /* whole daemon's while loop */
187 }
188
189 long
190 buf_ValidateBuffers(void)
191 {
192     cm_buf_t * bp, *bpf, *bpa, *bpb;
193     afs_uint64 countb = 0, countf = 0, counta = 0;
194
195     if (cm_data.buf_freeListp == NULL && cm_data.buf_freeListEndp != NULL ||
196          cm_data.buf_freeListp != NULL && cm_data.buf_freeListEndp == NULL) {
197         afsi_log("cm_ValidateBuffers failure: inconsistent free list pointers");
198         fprintf(stderr, "cm_ValidateBuffers failure: inconsistent free list pointers\n");
199         return -9;                  
200     }
201
202     for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) { 
203         if (bp->magic != CM_BUF_MAGIC) {
204             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
205             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
206             return -1;                  
207         }
208         countb++;                                                                
209         bpb = bp;     
210
211         if (countb > cm_data.buf_nbuffers) {
212             afsi_log("cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers");
213             fprintf(stderr, "cm_ValidateBuffers failure: countb > cm_data.buf_nbuffers\n");
214             return -6;                   
215         }
216     }
217
218     for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) { 
219         if (bp->magic != CM_BUF_MAGIC) {
220             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
221             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
222             return -2;                  
223         }
224         countf++;                                                             
225         bpf = bp;    
226
227         if (countf > cm_data.buf_nbuffers) {
228             afsi_log("cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers");
229             fprintf(stderr, "cm_ValidateBuffers failure: countf > cm_data.buf_nbuffers\n");
230             return -7;
231         }
232     }                                                                         
233                                                                               
234     for (bp = cm_data.buf_allp; bp; bp=bp->allp) {                            
235         if (bp->magic != CM_BUF_MAGIC) {
236             afsi_log("cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC");
237             fprintf(stderr, "cm_ValidateBuffers failure: bp->magic != CM_BUF_MAGIC\n");
238             return -3;                  
239         }
240         counta++;                                                             
241         bpa = bp;                                                             
242
243         if (counta > cm_data.buf_nbuffers) {
244             afsi_log("cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers");
245             fprintf(stderr, "cm_ValidateBuffers failure: counta > cm_data.buf_nbuffers\n");
246             return -8;                   
247         }
248     }                                                                         
249                                                                               
250     if (countb != countf) {
251         afsi_log("cm_ValidateBuffers failure: countb != countf");
252         fprintf(stderr, "cm_ValidateBuffers failure: countb != countf\n");
253         return -4;         
254     }
255                                                                               
256     if (counta != cm_data.buf_nbuffers) {
257         afsi_log("cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers");
258         fprintf(stderr, "cm_ValidateBuffers failure: counta != cm_data.buf_nbuffers\n");
259         return -5;                       
260     }
261                                                                               
262     return 0;                                                                 
263 }
264
265 void buf_Shutdown(void)  
266 {                        
267     buf_ShutdownFlag = 1;
268 }                        
269
270 /* initialize the buffer package; called with no locks
271  * held during the initialization phase.
272  */
273 long buf_Init(int newFile, cm_buf_ops_t *opsp, afs_uint64 nbuffers)
274 {
275     static osi_once_t once;
276     cm_buf_t *bp;
277     thread_t phandle;
278     long i;
279     unsigned long pid;
280     char *data;
281
282     if ( newFile ) {
283         if (nbuffers) 
284             cm_data.buf_nbuffers = nbuffers;
285
286         /* Have to be able to reserve a whole chunk */
287         if (((cm_data.buf_nbuffers - 3) * cm_data.buf_blockSize) < cm_chunkSize)
288             return CM_ERROR_TOOFEWBUFS;
289     }
290
291     /* recall for callouts */
292     cm_buf_opsp = opsp;
293
294     if (osi_Once(&once)) {
295         /* initialize global locks */
296         lock_InitializeRWLock(&buf_globalLock, "Global buffer lock");
297
298         if ( newFile ) {
299             /* remember this for those who want to reset it */
300             cm_data.buf_nOrigBuffers = cm_data.buf_nbuffers;
301  
302             /* lower hash size to a prime number */
303             cm_data.buf_hashSize = osi_PrimeLessThan(CM_BUF_HASHSIZE);
304  
305             /* create hash table */
306             memset((void *)cm_data.buf_hashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
307             
308             /* another hash table */
309             memset((void *)cm_data.buf_fileHashTablepp, 0, cm_data.buf_hashSize * sizeof(cm_buf_t *));
310
311             /* create buffer headers and put in free list */
312             bp = cm_data.bufHeaderBaseAddress;
313             data = cm_data.bufDataBaseAddress;
314             cm_data.buf_allp = NULL;
315             
316             for (i=0; i<cm_data.buf_nbuffers; i++) {
317                 osi_assert(bp >= cm_data.bufHeaderBaseAddress && bp < (cm_buf_t *)cm_data.bufDataBaseAddress);
318                 osi_assert(data >= cm_data.bufDataBaseAddress && data < cm_data.bufEndOfData);
319                 
320                 /* allocate and zero some storage */
321                 memset(bp, 0, sizeof(cm_buf_t));
322                 bp->magic = CM_BUF_MAGIC;
323                 /* thread on list of all buffers */
324                 bp->allp = cm_data.buf_allp;
325                 cm_data.buf_allp = bp;
326                 
327                 osi_QAdd((osi_queue_t **)&cm_data.buf_freeListp, &bp->q);
328                 bp->flags |= CM_BUF_INLRU;
329                 lock_InitializeMutex(&bp->mx, "Buffer mutex");
330                 
331                 /* grab appropriate number of bytes from aligned zone */
332                 bp->datap = data;
333                 
334                 /* setup last buffer pointer */
335                 if (i == 0)
336                     cm_data.buf_freeListEndp = bp;
337                     
338                 /* next */
339                 bp++;
340                 data += cm_data.buf_blockSize;
341             }       
342  
343             /* none reserved at first */
344             cm_data.buf_reservedBufs = 0;
345  
346             /* just for safety's sake */
347             cm_data.buf_maxReservedBufs = cm_data.buf_nbuffers - 3;
348         } else {
349             bp = cm_data.bufHeaderBaseAddress;
350             data = cm_data.bufDataBaseAddress;
351             
352             for (i=0; i<cm_data.buf_nbuffers; i++) {
353                 lock_InitializeMutex(&bp->mx, "Buffer mutex");
354                 bp->userp = NULL;
355                 bp->waitCount = 0;
356                 bp->waitRequests = 0;
357                 bp->flags &= ~CM_BUF_WAITING;
358                 bp++;
359             }       
360         }
361  
362 #ifdef TESTING
363         buf_ValidateBufQueues();
364 #endif /* TESTING */
365
366 #ifdef TRACE_BUFFER
367         /* init the buffer trace log */
368         buf_logp = osi_LogCreate("buffer", 1000);
369         osi_LogEnable(buf_logp);
370 #endif
371
372         osi_EndOnce(&once);
373
374         /* and create the incr-syncer */
375         phandle = thrd_Create(0, 0,
376                                (ThreadFunc) buf_IncrSyncer, 0, 0, &pid,
377                                "buf_IncrSyncer");
378
379         osi_assertx(phandle != NULL, "buf: can't create incremental sync proc");
380         CloseHandle(phandle);
381     }
382
383 #ifdef TESTING
384     buf_ValidateBufQueues();
385 #endif /* TESTING */
386     return 0;
387 }
388
389 /* add nbuffers to the buffer pool, if possible.
390  * Called with no locks held.
391  */
392 long buf_AddBuffers(afs_uint64 nbuffers)
393 {
394     /* The size of a virtual cache cannot be changed after it has
395      * been created.  Subsequent calls to MapViewofFile() with
396      * an existing mapping object name would not allow the 
397      * object to be resized.  Return failure immediately.
398      *
399      * A similar problem now occurs with the persistent cache
400      * given that the memory mapped file now contains a complex
401      * data structure.
402      */
403     afsi_log("request to add %d buffers to the existing cache of size %d denied",
404               nbuffers, cm_data.buf_nbuffers);
405
406     return CM_ERROR_INVAL;
407 }       
408
409 /* interface to set the number of buffers to an exact figure.
410  * Called with no locks held.
411  */
412 long buf_SetNBuffers(afs_uint64 nbuffers)
413 {
414     if (nbuffers < 10) 
415         return CM_ERROR_INVAL;
416     if (nbuffers == cm_data.buf_nbuffers) 
417         return 0;
418     else if (nbuffers > cm_data.buf_nbuffers)
419         return buf_AddBuffers(nbuffers - cm_data.buf_nbuffers);
420     else 
421         return CM_ERROR_INVAL;
422 }
423
424 /* wait for reading or writing to clear; called with write-locked
425  * buffer and unlocked scp and returns with locked buffer.
426  */
427 void buf_WaitIO(cm_scache_t * scp, cm_buf_t *bp)
428 {
429     int release = 0;
430
431     if (scp)
432         osi_assert(scp->magic == CM_SCACHE_MAGIC);
433     osi_assert(bp->magic == CM_BUF_MAGIC);
434
435     while (1) {
436         /* if no IO is happening, we're done */
437         if (!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)))
438             break;
439                 
440         /* otherwise I/O is happening, but some other thread is waiting for
441          * the I/O already.  Wait for that guy to figure out what happened,
442          * and then check again.
443          */
444         if ( bp->flags & CM_BUF_WAITING ) {
445             bp->waitCount++;
446             bp->waitRequests++;
447             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING already set for 0x%p", bp);
448         } else {
449             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING set for 0x%p", bp);
450             bp->flags |= CM_BUF_WAITING;
451             bp->waitCount = bp->waitRequests = 1;
452         }
453         osi_SleepM((LONG_PTR)bp, &bp->mx);
454
455         smb_UpdateServerPriority();
456
457         lock_ObtainMutex(&bp->mx);
458         osi_Log1(buf_logp, "buf_WaitIO conflict wait done for 0x%p", bp);
459         bp->waitCount--;
460         if (bp->waitCount == 0) {
461             osi_Log1(buf_logp, "buf_WaitIO CM_BUF_WAITING reset for 0x%p", bp);
462             bp->flags &= ~CM_BUF_WAITING;
463             bp->waitRequests = 0;
464         }
465
466         if ( !scp ) {
467             if (scp = cm_FindSCache(&bp->fid))
468                  release = 1;
469         }
470         if ( scp ) {
471             lock_ObtainMutex(&scp->mx);
472             if (scp->flags & CM_SCACHEFLAG_WAITING) {
473                 osi_Log1(buf_logp, "buf_WaitIO waking scp 0x%p", scp);
474                 osi_Wakeup((LONG_PTR)&scp->flags);
475             }
476             lock_ReleaseMutex(&scp->mx);
477         }
478     }
479         
480     /* if we get here, the IO is done, but we may have to wakeup people waiting for
481      * the I/O to complete.  Do so.
482      */
483     if (bp->flags & CM_BUF_WAITING) {
484         osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
485         osi_Wakeup((LONG_PTR) bp);
486     }
487     osi_Log1(buf_logp, "WaitIO finished wait for bp 0x%p", bp);
488
489     if (scp && release)
490         cm_ReleaseSCache(scp);
491 }
492
493 /* find a buffer, if any, for a particular file ID and offset.  Assumes
494  * that buf_globalLock is write locked when called.
495  */
496 cm_buf_t *buf_FindLocked(struct cm_scache *scp, osi_hyper_t *offsetp)
497 {
498     long i;
499     cm_buf_t *bp;
500
501     i = BUF_HASH(&scp->fid, offsetp);
502     for(bp = cm_data.buf_hashTablepp[i]; bp; bp=bp->hashp) {
503         if (cm_FidCmp(&scp->fid, &bp->fid) == 0
504              && offsetp->LowPart == bp->offset.LowPart
505              && offsetp->HighPart == bp->offset.HighPart) {
506             buf_HoldLocked(bp);
507             break;
508         }
509     }
510         
511     /* return whatever we found, if anything */
512     return bp;
513 }
514
515 /* find a buffer with offset *offsetp for vnode *scp.  Called
516  * with no locks held.
517  */
518 cm_buf_t *buf_Find(struct cm_scache *scp, osi_hyper_t *offsetp)
519 {
520     cm_buf_t *bp;
521
522     lock_ObtainWrite(&buf_globalLock);
523     bp = buf_FindLocked(scp, offsetp);
524     lock_ReleaseWrite(&buf_globalLock);
525
526     return bp;
527 }       
528
529 /* start cleaning I/O on this buffer.  Buffer must be write locked, and is returned
530  * write-locked.
531  *
532  * Makes sure that there's only one person writing this block
533  * at any given time, and also ensures that the log is forced sufficiently far,
534  * if this buffer contains logged data.
535  *
536  * Returns non-zero if the buffer was dirty.
537  */
538 long buf_CleanAsyncLocked(cm_buf_t *bp, cm_req_t *reqp)
539 {
540     long code = 0;
541     long isdirty = 0;
542     cm_scache_t * scp = NULL;
543
544     osi_assert(bp->magic == CM_BUF_MAGIC);
545
546     while ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
547         isdirty = 1;
548         lock_ReleaseMutex(&bp->mx);
549
550         scp = cm_FindSCache(&bp->fid);
551         if (scp) {
552             osi_Log2(buf_logp, "buf_CleanAsyncLocked starts I/O on scp 0x%p buf 0x%p", scp, bp);
553             code = (*cm_buf_opsp->Writep)(scp, &bp->offset,
554                                            cm_data.buf_blockSize, 0, bp->userp,
555                                            reqp);
556             osi_Log3(buf_logp, "buf_CleanAsyncLocked I/O on scp 0x%p buf 0x%p, done=%d", scp, bp, code);
557
558             cm_ReleaseSCache(scp);
559             scp = NULL;
560         } else {
561             osi_Log1(buf_logp, "buf_CleanAsyncLocked unable to start I/O - scp not found buf 0x%p", bp);
562             code = CM_ERROR_NOSUCHFILE;
563         }    
564         
565         lock_ObtainMutex(&bp->mx);
566         /* if the Write routine returns No Such File, clear the dirty flag
567          * because we aren't going to be able to write this data to the file
568          * server.
569          */
570         if (code == CM_ERROR_NOSUCHFILE){
571             bp->flags &= ~CM_BUF_DIRTY;
572             bp->flags |= CM_BUF_ERROR;
573             bp->error = CM_ERROR_NOSUCHFILE;
574             bp->dataVersion = -1; /* bad */
575             bp->dirtyCounter++;
576         }
577
578 #ifdef DISKCACHE95
579         /* Disk cache support */
580         /* write buffer to disk cache (synchronous for now) */
581         diskcache_Update(bp->dcp, bp->datap, cm_data.buf_blockSize, bp->dataVersion);
582 #endif /* DISKCACHE95 */
583
584         /* if we get here and retries are not permitted 
585          * then we need to exit this loop regardless of 
586          * whether or not we were able to clear the dirty bit
587          */
588         if (reqp->flags & CM_REQ_NORETRY)
589             break;
590     };
591
592     /* do logging after call to GetLastError, or else */
593         
594     /* if someone was waiting for the I/O that just completed or failed,
595      * wake them up.
596      */
597     if (bp->flags & CM_BUF_WAITING) {
598         /* turn off flags and wakeup users */
599         osi_Log1(buf_logp, "buf_WaitIO Waking bp 0x%p", bp);
600         osi_Wakeup((LONG_PTR) bp);
601     }
602     return isdirty;
603 }
604
605 /* Called with a zero-ref count buffer and with the buf_globalLock write locked.
606  * recycles the buffer, and leaves it ready for reuse with a ref count of 1.
607  * The buffer must already be clean, and no I/O should be happening to it.
608  */
609 void buf_Recycle(cm_buf_t *bp)
610 {
611     int i;
612     cm_buf_t **lbpp;
613     cm_buf_t *tbp;
614     cm_buf_t *prevBp, *nextBp;
615
616     osi_assert(bp->magic == CM_BUF_MAGIC);
617
618     /* if we get here, we know that the buffer still has a 0 ref count,
619      * and that it is clean and has no currently pending I/O.  This is
620      * the dude to return.
621      * Remember that as long as the ref count is 0, we know that we won't
622      * have any lock conflicts, so we can grab the buffer lock out of
623      * order in the locking hierarchy.
624      */
625     osi_Log2( buf_logp, "buf_Recycle recycles 0x%p, off 0x%x",
626               bp, bp->offset.LowPart);
627
628     osi_assert(bp->refCount == 0);
629     osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)));
630     lock_AssertWrite(&buf_globalLock);
631
632     if (bp->flags & CM_BUF_INHASH) {
633         /* Remove from hash */
634
635         i = BUF_HASH(&bp->fid, &bp->offset);
636         lbpp = &(cm_data.buf_hashTablepp[i]);
637         for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = *lbpp) {
638             if (tbp == bp) break;
639         }
640
641         /* we better find it */
642         osi_assertx(tbp != NULL, "buf_Recycle: hash table screwup");
643
644         *lbpp = bp->hashp;      /* hash out */
645
646         /* Remove from file hash */
647
648         i = BUF_FILEHASH(&bp->fid);
649         prevBp = bp->fileHashBackp;
650         nextBp = bp->fileHashp;
651         if (prevBp)
652             prevBp->fileHashp = nextBp;
653         else
654             cm_data.buf_fileHashTablepp[i] = nextBp;
655         if (nextBp)
656             nextBp->fileHashBackp = prevBp;
657
658         bp->flags &= ~CM_BUF_INHASH;
659     }
660
661     /* bump the soft reference counter now, to invalidate softRefs; no
662      * wakeup is required since people don't sleep waiting for this
663      * counter to change.
664      */
665     bp->idCounter++;
666
667     /* make the fid unrecognizable */
668     memset(&bp->fid, 0, sizeof(cm_fid_t));
669 }       
670
671 /* recycle a buffer, removing it from the free list, hashing in its new identity
672  * and returning it write-locked so that no one can use it.  Called without
673  * any locks held, and can return an error if it loses the race condition and 
674  * finds that someone else created the desired buffer.
675  *
676  * If success is returned, the buffer is returned write-locked.
677  *
678  * May be called with null scp and offsetp, if we're just trying to reclaim some
679  * space from the buffer pool.  In that case, the buffer will be returned
680  * without being hashed into the hash table.
681  */
682 long buf_GetNewLocked(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
683 {
684     cm_buf_t *bp;               /* buffer we're dealing with */
685     cm_buf_t *nextBp;   /* next buffer in file hash chain */
686     long i;                     /* temp */
687     cm_req_t req;
688
689     cm_InitReq(&req);   /* just in case */
690
691 #ifdef TESTING
692     buf_ValidateBufQueues();
693 #endif /* TESTING */
694
695     while(1) {
696       retry:
697         lock_ObtainWrite(&buf_globalLock);
698         /* check to see if we lost the race */
699         if (scp) {
700             if (bp = buf_FindLocked(scp, offsetp)) {
701                 /* Do not call buf_ReleaseLocked() because we 
702                  * do not want to allow the buffer to be added
703                  * to the free list.
704                  */
705                 bp->refCount--;
706                 lock_ReleaseWrite(&buf_globalLock);
707                 return CM_BUF_EXISTS;
708             }
709         }
710
711         /* does this fix the problem below?  it's a simple solution. */
712         if (!cm_data.buf_freeListEndp)
713             {
714             lock_ReleaseWrite(&buf_globalLock);
715             Sleep(200);
716             goto retry;
717             }
718
719         /* for debugging, assert free list isn't empty, although we
720          * really should try waiting for a running tranasction to finish
721          * instead of this; or better, we should have a transaction
722          * throttler prevent us from entering this situation.
723          */
724         osi_assertx(cm_data.buf_freeListEndp != NULL, "buf_GetNewLocked: no free buffers");
725
726         /* look at all buffers in free list, some of which may temp.
727          * have high refcounts and which then should be skipped,
728          * starting cleaning I/O for those which are dirty.  If we find
729          * a clean buffer, we rehash it, lock it and return it.
730          */
731         for(bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
732             /* check to see if it really has zero ref count.  This
733              * code can bump refcounts, at least, so it may not be
734              * zero.
735              */
736             if (bp->refCount > 0) 
737                 continue;
738                         
739             /* we don't have to lock buffer itself, since the ref
740              * count is 0 and we know it will stay zero as long as
741              * we hold the global lock.
742              */
743
744             /* don't recycle someone in our own chunk */
745             if (!cm_FidCmp(&bp->fid, &scp->fid)
746                  && (bp->offset.LowPart & (-cm_chunkSize))
747                  == (offsetp->LowPart & (-cm_chunkSize)))
748                 continue;
749
750             /* if this page is being filled (!) or cleaned, see if
751              * the I/O has completed.  If not, skip it, otherwise
752              * do the final processing for the I/O.
753              */
754             if (bp->flags & (CM_BUF_READING | CM_BUF_WRITING)) {
755                 /* probably shouldn't do this much work while
756                  * holding the big lock?  Watch for contention
757                  * here.
758                  */
759                 continue;
760             }
761                         
762             if (bp->flags & CM_BUF_DIRTY) {
763                 /* if the buffer is dirty, start cleaning it and
764                  * move on to the next buffer.  We do this with
765                  * just the lock required to minimize contention
766                  * on the big lock.
767                  */
768                 buf_HoldLocked(bp);
769                 lock_ReleaseWrite(&buf_globalLock);
770
771                 /* grab required lock and clean; this only
772                  * starts the I/O.  By the time we're back,
773                  * it'll still be marked dirty, but it will also
774                  * have the WRITING flag set, so we won't get
775                  * back here.
776                  */
777                 buf_CleanAsync(bp, &req);
778
779                 /* now put it back and go around again */
780                 buf_Release(bp);
781                 goto retry;
782             }
783
784             /* if we get here, we know that the buffer still has a 0
785              * ref count, and that it is clean and has no currently
786              * pending I/O.  This is the dude to return.
787              * Remember that as long as the ref count is 0, we know
788              * that we won't have any lock conflicts, so we can grab
789              * the buffer lock out of order in the locking hierarchy.
790              */
791             buf_Recycle(bp);
792
793             /* clean up junk flags */
794             bp->flags &= ~(CM_BUF_EOF | CM_BUF_ERROR);
795             bp->dataVersion = -1;       /* unknown so far */
796
797             /* now hash in as our new buffer, and give it the
798              * appropriate label, if requested.
799              */
800             if (scp) {
801                 bp->flags |= CM_BUF_INHASH;
802                 bp->fid = scp->fid;
803 #ifdef DEBUG
804                 bp->scp = scp;
805 #endif
806                 bp->offset = *offsetp;
807                 i = BUF_HASH(&scp->fid, offsetp);
808                 bp->hashp = cm_data.buf_hashTablepp[i];
809                 cm_data.buf_hashTablepp[i] = bp;
810                 i = BUF_FILEHASH(&scp->fid);
811                 nextBp = cm_data.buf_fileHashTablepp[i];
812                 bp->fileHashp = nextBp;
813                 bp->fileHashBackp = NULL;
814                 if (nextBp)
815                     nextBp->fileHashBackp = bp;
816                 cm_data.buf_fileHashTablepp[i] = bp;
817             }
818
819             /* prepare to return it.  Start by giving it a good
820              * refcount */
821             bp->refCount = 1;
822                         
823             /* and since it has a non-zero ref count, we should move
824              * it from the lru queue.  It better be still there,
825              * since we've held the global (big) lock since we found
826              * it there.
827              */
828             osi_assertx(bp->flags & CM_BUF_INLRU,
829                          "buf_GetNewLocked: LRU screwup");
830             if (cm_data.buf_freeListEndp == bp) {
831                 /* we're the last guy in this queue, so maintain it */
832                 cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
833             }
834             osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
835             bp->flags &= ~CM_BUF_INLRU;
836
837             /* finally, grab the mutex so that people don't use it
838              * before the caller fills it with data.  Again, no one     
839              * should have been able to get to this dude to lock it.
840              */
841             osi_assertx(lock_TryMutex(&bp->mx),
842                          "buf_GetNewLocked: TryMutex failed");
843
844             lock_ReleaseWrite(&buf_globalLock);
845             *bufpp = bp;
846
847 #ifdef TESTING
848             buf_ValidateBufQueues();
849 #endif /* TESTING */
850             return 0;
851         } /* for all buffers in lru queue */
852         lock_ReleaseWrite(&buf_globalLock);
853     }   /* while loop over everything */
854     /* not reached */
855 } /* the proc */
856
857 /* get a page, returning it held but unlocked.  Doesn't fill in the page
858  * with I/O, since we're going to write the whole thing new.
859  */
860 long buf_GetNew(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
861 {
862     cm_buf_t *bp;
863     long code;
864     osi_hyper_t pageOffset;
865     int created;
866
867     created = 0;
868     pageOffset.HighPart = offsetp->HighPart;
869     pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
870     while (1) {
871         bp = buf_Find(scp, &pageOffset);
872         if (bp) {
873             /* lock it and break out */
874             lock_ObtainMutex(&bp->mx);
875             break;
876         }
877
878         /* otherwise, we have to create a page */
879         code = buf_GetNewLocked(scp, &pageOffset, &bp);
880
881         /* check if the buffer was created in a race condition branch.
882          * If so, go around so we can hold a reference to it. 
883          */
884         if (code == CM_BUF_EXISTS) 
885             continue;
886
887         /* something else went wrong */
888         if (code != 0) 
889             return code;
890
891         /* otherwise, we have a locked buffer that we just created */
892         created = 1;
893         break;
894     } /* big while loop */
895
896     /* wait for reads */
897     if (bp->flags & CM_BUF_READING)
898         buf_WaitIO(scp, bp);
899
900     /* once it has been read once, we can unlock it and return it, still
901      * with its refcount held.
902      */
903     lock_ReleaseMutex(&bp->mx);
904     *bufpp = bp;
905     osi_Log3(buf_logp, "buf_GetNew returning bp 0x%p for scp 0x%p, offset 0x%x",
906               bp, scp, offsetp->LowPart);
907     return 0;
908 }
909
910 /* get a page, returning it held but unlocked.  Make sure it is complete */
911 /* The scp must be unlocked when passed to this function */
912 long buf_Get(struct cm_scache *scp, osi_hyper_t *offsetp, cm_buf_t **bufpp)
913 {
914     cm_buf_t *bp;
915     long code;
916     osi_hyper_t pageOffset;
917     unsigned long tcount;
918     int created;
919     long lcount = 0;
920 #ifdef DISKCACHE95
921     cm_diskcache_t *dcp;
922 #endif /* DISKCACHE95 */
923
924     created = 0;
925     pageOffset.HighPart = offsetp->HighPart;
926     pageOffset.LowPart = offsetp->LowPart & ~(cm_data.buf_blockSize-1);
927     while (1) {
928         lcount++;
929 #ifdef TESTING
930         buf_ValidateBufQueues();
931 #endif /* TESTING */
932
933         bp = buf_Find(scp, &pageOffset);
934         if (bp) {
935             /* lock it and break out */
936             lock_ObtainMutex(&bp->mx);
937
938 #ifdef DISKCACHE95
939             /* touch disk chunk to update LRU info */
940             diskcache_Touch(bp->dcp);
941 #endif /* DISKCACHE95 */
942             break;
943         }
944
945         /* otherwise, we have to create a page */
946         code = buf_GetNewLocked(scp, &pageOffset, &bp);
947         /* bp->mx is now held */
948
949         /* check if the buffer was created in a race condition branch.
950          * If so, go around so we can hold a reference to it. 
951          */
952         if (code == CM_BUF_EXISTS) 
953             continue;
954
955         /* something else went wrong */
956         if (code != 0) { 
957 #ifdef TESTING
958             buf_ValidateBufQueues();
959 #endif /* TESTING */
960             return code;
961         }
962                 
963         /* otherwise, we have a locked buffer that we just created */
964         created = 1;
965         break;
966     } /* big while loop */
967
968     /* if we get here, we have a locked buffer that may have just been
969      * created, in which case it needs to be filled with data.
970      */
971     if (created) {
972         /* load the page; freshly created pages should be idle */
973         osi_assert(!(bp->flags & (CM_BUF_READING | CM_BUF_WRITING)));
974
975         /* setup offset, event */
976         bp->over.Offset = bp->offset.LowPart;
977         bp->over.OffsetHigh = bp->offset.HighPart;
978
979         /* start the I/O; may drop lock */
980         bp->flags |= CM_BUF_READING;
981         code = (*cm_buf_opsp->Readp)(bp, cm_data.buf_blockSize, &tcount, NULL);
982
983 #ifdef DISKCACHE95
984         code = diskcache_Get(&bp->fid, &bp->offset, bp->datap, cm_data.buf_blockSize, &bp->dataVersion, &tcount, &dcp);
985         bp->dcp = dcp;    /* pointer to disk cache struct. */
986 #endif /* DISKCACHE95 */
987
988         if (code != 0) {
989             /* failure or queued */
990             if (code != ERROR_IO_PENDING) {
991                 bp->error = code;
992                 bp->flags |= CM_BUF_ERROR;
993                 bp->flags &= ~CM_BUF_READING;
994                 if (bp->flags & CM_BUF_WAITING) {
995                     osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
996                     osi_Wakeup((LONG_PTR) bp);
997                 }
998                 lock_ReleaseMutex(&bp->mx);
999                 buf_Release(bp);
1000 #ifdef TESTING
1001                 buf_ValidateBufQueues();
1002 #endif /* TESTING */
1003                 return code;
1004             }
1005         } else {
1006             /* otherwise, I/O completed instantly and we're done, except
1007              * for padding the xfr out with 0s and checking for EOF
1008              */
1009             if (tcount < (unsigned long) cm_data.buf_blockSize) {
1010                 memset(bp->datap+tcount, 0, cm_data.buf_blockSize - tcount);
1011                 if (tcount == 0)
1012                     bp->flags |= CM_BUF_EOF;
1013             }
1014             bp->flags &= ~CM_BUF_READING;
1015             if (bp->flags & CM_BUF_WAITING) {
1016                 osi_Log1(buf_logp, "buf_Get Waking bp 0x%p", bp);
1017                 osi_Wakeup((LONG_PTR) bp);
1018             }
1019         }
1020
1021     } /* if created */
1022
1023     /* wait for reads, either that which we started above, or that someone
1024      * else started.  We don't care if we return a buffer being cleaned.
1025      */
1026     if (bp->flags & CM_BUF_READING)
1027         buf_WaitIO(scp, bp);
1028
1029     /* once it has been read once, we can unlock it and return it, still
1030      * with its refcount held.
1031      */
1032     lock_ReleaseMutex(&bp->mx);
1033     *bufpp = bp;
1034
1035     /* now remove from queue; will be put in at the head (farthest from
1036      * being recycled) when we're done in buf_Release.
1037      */
1038     lock_ObtainWrite(&buf_globalLock);
1039     if (bp->flags & CM_BUF_INLRU) {
1040         if (cm_data.buf_freeListEndp == bp)
1041             cm_data.buf_freeListEndp = (cm_buf_t *) osi_QPrev(&bp->q);
1042         osi_QRemove((osi_queue_t **) &cm_data.buf_freeListp, &bp->q);
1043         bp->flags &= ~CM_BUF_INLRU;
1044     }
1045     lock_ReleaseWrite(&buf_globalLock);
1046
1047     osi_Log3(buf_logp, "buf_Get returning bp 0x%p for scp 0x%p, offset 0x%x",
1048               bp, scp, offsetp->LowPart);
1049 #ifdef TESTING
1050     buf_ValidateBufQueues();
1051 #endif /* TESTING */
1052     return 0;
1053 }
1054
1055 /* count # of elements in the free list;
1056  * we don't bother doing the proper locking for accessing dataVersion or flags
1057  * since it is a pain, and this is really just an advisory call.  If you need
1058  * to do better at some point, rewrite this function.
1059  */
1060 long buf_CountFreeList(void)
1061 {
1062     long count;
1063     cm_buf_t *bufp;
1064
1065     count = 0;
1066     lock_ObtainRead(&buf_globalLock);
1067     for(bufp = cm_data.buf_freeListp; bufp; bufp = (cm_buf_t *) osi_QNext(&bufp->q)) {
1068         /* if the buffer doesn't have an identity, or if the buffer
1069          * has been invalidate (by having its DV stomped upon), then
1070          * count it as free, since it isn't really being utilized.
1071          */
1072         if (!(bufp->flags & CM_BUF_INHASH) || bufp->dataVersion <= 0)
1073             count++;
1074     }       
1075     lock_ReleaseRead(&buf_globalLock);
1076     return count;
1077 }
1078
1079 /* clean a buffer synchronously */
1080 long buf_CleanAsync(cm_buf_t *bp, cm_req_t *reqp)
1081 {
1082     long code;
1083     osi_assert(bp->magic == CM_BUF_MAGIC);
1084
1085     lock_ObtainMutex(&bp->mx);
1086     code = buf_CleanAsyncLocked(bp, reqp);
1087     lock_ReleaseMutex(&bp->mx);
1088
1089     return code;
1090 }       
1091
1092 /* wait for a buffer's cleaning to finish */
1093 void buf_CleanWait(cm_scache_t * scp, cm_buf_t *bp)
1094 {
1095     osi_assert(bp->magic == CM_BUF_MAGIC);
1096
1097     lock_ObtainMutex(&bp->mx);
1098     if (bp->flags & CM_BUF_WRITING) {
1099         buf_WaitIO(scp, bp);
1100     }
1101     lock_ReleaseMutex(&bp->mx);
1102 }       
1103
1104 /* set the dirty flag on a buffer, and set associated write-ahead log,
1105  * if there is one.  Allow one to be added to a buffer, but not changed.
1106  *
1107  * The buffer must be locked before calling this routine.
1108  */
1109 void buf_SetDirty(cm_buf_t *bp)
1110 {
1111     osi_assert(bp->magic == CM_BUF_MAGIC);
1112     osi_assert(bp->refCount > 0);
1113         
1114     osi_Log1(buf_logp, "buf_SetDirty 0x%p", bp);
1115
1116     /* set dirty bit */
1117     bp->flags |= CM_BUF_DIRTY;
1118
1119     /* and turn off EOF flag, since it has associated data now */
1120     bp->flags &= ~CM_BUF_EOF;
1121 }
1122
1123 /* clean all buffers, reset log pointers and invalidate all buffers.
1124  * Called with no locks held, and returns with same.
1125  *
1126  * This function is guaranteed to clean and remove the log ptr of all the
1127  * buffers that were dirty or had non-zero log ptrs before the call was
1128  * made.  That's sufficient to clean up any garbage left around by recovery,
1129  * which is all we're counting on this for; there may be newly created buffers
1130  * added while we're running, but that should be OK.
1131  *
1132  * In an environment where there are no transactions (artificially imposed, for
1133  * example, when switching the database to raw mode), this function is used to
1134  * make sure that all updates have been written to the disk.  In that case, we don't
1135  * really require that we forget the log association between pages and logs, but
1136  * it also doesn't hurt.  Since raw mode I/O goes through this buffer package, we don't
1137  * have to worry about invalidating data in the buffers.
1138  *
1139  * This function is used at the end of recovery as paranoia to get the recovered
1140  * database out to disk.  It removes all references to the recovery log and cleans
1141  * all buffers.
1142  */
1143 long buf_CleanAndReset(void)
1144 {
1145     long i;
1146     cm_buf_t *bp;
1147     cm_req_t req;
1148
1149     lock_ObtainWrite(&buf_globalLock);
1150     for(i=0; i<cm_data.buf_hashSize; i++) {
1151         for(bp = cm_data.buf_hashTablepp[i]; bp; bp = bp->hashp) {
1152             if ((bp->flags & CM_BUF_DIRTY) == CM_BUF_DIRTY) {
1153                 buf_HoldLocked(bp);
1154                 lock_ReleaseWrite(&buf_globalLock);
1155
1156                 /* now no locks are held; clean buffer and go on */
1157                 cm_InitReq(&req);
1158                 req.flags |= CM_REQ_NORETRY;
1159
1160                 buf_CleanAsync(bp, &req);
1161                 buf_CleanWait(NULL, bp);
1162
1163                 /* relock and release buffer */
1164                 lock_ObtainWrite(&buf_globalLock);
1165                 buf_ReleaseLocked(bp);
1166             } /* dirty */
1167         } /* over one bucket */
1168     }   /* for loop over all hash buckets */
1169
1170     /* release locks */
1171     lock_ReleaseWrite(&buf_globalLock);
1172
1173 #ifdef TESTING
1174     buf_ValidateBufQueues();
1175 #endif /* TESTING */
1176     
1177     /* and we're done */
1178     return 0;
1179 }       
1180
1181 /* called without global lock being held, reserves buffers for callers
1182  * that need more than one held (not locked) at once.
1183  */
1184 void buf_ReserveBuffers(afs_uint64 nbuffers)
1185 {
1186     lock_ObtainWrite(&buf_globalLock);
1187     while (1) {
1188         if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1189             cm_data.buf_reserveWaiting = 1;
1190             osi_Log1(buf_logp, "buf_ReserveBuffers waiting for %d bufs", nbuffers);
1191             osi_SleepW((LONG_PTR) &cm_data.buf_reservedBufs, &buf_globalLock);
1192             lock_ObtainWrite(&buf_globalLock);
1193         }
1194         else {
1195             cm_data.buf_reservedBufs += nbuffers;
1196             break;
1197         }
1198     }
1199     lock_ReleaseWrite(&buf_globalLock);
1200 }
1201
1202 int buf_TryReserveBuffers(afs_uint64 nbuffers)
1203 {
1204     int code;
1205
1206     lock_ObtainWrite(&buf_globalLock);
1207     if (cm_data.buf_reservedBufs + nbuffers > cm_data.buf_maxReservedBufs) {
1208         code = 0;
1209     }
1210     else {
1211         cm_data.buf_reservedBufs += nbuffers;
1212         code = 1;
1213     }
1214     lock_ReleaseWrite(&buf_globalLock);
1215     return code;
1216 }       
1217
1218 /* called without global lock held, releases reservation held by
1219  * buf_ReserveBuffers.
1220  */
1221 void buf_UnreserveBuffers(afs_uint64 nbuffers)
1222 {
1223     lock_ObtainWrite(&buf_globalLock);
1224     cm_data.buf_reservedBufs -= nbuffers;
1225     if (cm_data.buf_reserveWaiting) {
1226         cm_data.buf_reserveWaiting = 0;
1227         osi_Wakeup((LONG_PTR) &cm_data.buf_reservedBufs);
1228     }
1229     lock_ReleaseWrite(&buf_globalLock);
1230 }       
1231
1232 /* truncate the buffers past sizep, zeroing out the page, if we don't
1233  * end on a page boundary.
1234  *
1235  * Requires cm_bufCreateLock to be write locked.
1236  */
1237 long buf_Truncate(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
1238                    osi_hyper_t *sizep)
1239 {
1240     cm_buf_t *bufp;
1241     cm_buf_t *nbufp;                    /* next buffer, if didRelease */
1242     osi_hyper_t bufEnd;
1243     long code;
1244     long bufferPos;
1245     long i;
1246
1247     /* assert that cm_bufCreateLock is held in write mode */
1248     lock_AssertWrite(&scp->bufCreateLock);
1249
1250     i = BUF_FILEHASH(&scp->fid);
1251
1252     lock_ObtainWrite(&buf_globalLock);
1253     bufp = cm_data.buf_fileHashTablepp[i];
1254     if (bufp == NULL) {
1255         lock_ReleaseWrite(&buf_globalLock);
1256         return 0;
1257     }
1258
1259     buf_HoldLocked(bufp);
1260     lock_ReleaseWrite(&buf_globalLock);
1261     for(; bufp; bufp = nbufp) {
1262         lock_ObtainMutex(&bufp->mx);
1263
1264         bufEnd.HighPart = 0;
1265         bufEnd.LowPart = cm_data.buf_blockSize;
1266         bufEnd = LargeIntegerAdd(bufEnd, bufp->offset);
1267
1268         if (cm_FidCmp(&bufp->fid, &scp->fid) == 0 &&
1269              LargeIntegerLessThan(*sizep, bufEnd)) {
1270             buf_WaitIO(scp, bufp);
1271         }
1272         lock_ObtainMutex(&scp->mx);
1273         
1274         /* make sure we have a callback (so we have the right value for
1275          * the length), and wait for it to be safe to do a truncate.
1276          */
1277         code = cm_SyncOp(scp, bufp, userp, reqp, 0,
1278                           CM_SCACHESYNC_NEEDCALLBACK
1279                           | CM_SCACHESYNC_GETSTATUS
1280                           | CM_SCACHESYNC_SETSIZE
1281                           | CM_SCACHESYNC_BUFLOCKED);
1282
1283         
1284         lock_ObtainWrite(&buf_globalLock);
1285         /* if we succeeded in our locking, and this applies to the right
1286          * file, and the truncate request overlaps the buffer either
1287          * totally or partially, then do something.
1288          */
1289         if (code == 0 && cm_FidCmp(&bufp->fid, &scp->fid) == 0
1290              && LargeIntegerLessThan(*sizep, bufEnd)) {
1291
1292
1293             /* destroy the buffer, turning off its dirty bit, if
1294              * we're truncating the whole buffer.  Otherwise, set
1295              * the dirty bit, and clear out the tail of the buffer
1296              * if we just overlap some.
1297              */
1298             if (LargeIntegerLessThanOrEqualTo(*sizep, bufp->offset)) {
1299                 /* truncating the entire page */
1300                 bufp->flags &= ~CM_BUF_DIRTY;
1301                 bufp->dataVersion = -1; /* known bad */
1302                 bufp->dirtyCounter++;
1303             }
1304             else {
1305                 /* don't set dirty, since dirty implies
1306                  * currently up-to-date.  Don't need to do this,
1307                  * since we'll update the length anyway.
1308                  *
1309                  * Zero out remainder of the page, in case we
1310                  * seek and write past EOF, and make this data
1311                  * visible again.
1312                  */
1313                 bufferPos = sizep->LowPart & (cm_data.buf_blockSize - 1);
1314                 osi_assert(bufferPos != 0);
1315                 memset(bufp->datap + bufferPos, 0,
1316                         cm_data.buf_blockSize - bufferPos);
1317             }
1318         }
1319                 
1320         cm_SyncOpDone( scp, bufp, 
1321                        CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
1322                        | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_BUFLOCKED);
1323
1324         lock_ReleaseMutex(&scp->mx);
1325         lock_ReleaseMutex(&bufp->mx);
1326     
1327         if (!code) {
1328             nbufp = bufp->fileHashp;
1329             if (nbufp) 
1330                 buf_HoldLocked(nbufp);
1331         } else {
1332             /* This forces the loop to end and the error code
1333              * to be returned. */
1334             nbufp = NULL;
1335         }
1336         buf_ReleaseLocked(bufp);
1337         lock_ReleaseWrite(&buf_globalLock);
1338     }
1339
1340 #ifdef TESTING
1341     buf_ValidateBufQueues();
1342 #endif /* TESTING */
1343
1344     /* done */
1345     return code;
1346 }
1347
1348 long buf_FlushCleanPages(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
1349 {
1350     long code;
1351     cm_buf_t *bp;               /* buffer we're hacking on */
1352     cm_buf_t *nbp;
1353     int didRelease;
1354     long i;
1355
1356     i = BUF_FILEHASH(&scp->fid);
1357
1358     code = 0;
1359     lock_ObtainWrite(&buf_globalLock);
1360     bp = cm_data.buf_fileHashTablepp[i];
1361     if (bp) 
1362         buf_HoldLocked(bp);
1363     lock_ReleaseWrite(&buf_globalLock);
1364     
1365     for (; bp; bp = nbp) {
1366         didRelease = 0; /* haven't released this buffer yet */
1367
1368         /* clean buffer synchronously */
1369         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1370             lock_ObtainMutex(&bp->mx);
1371
1372             /* start cleaning the buffer, and wait for it to finish */
1373             buf_CleanAsyncLocked(bp, reqp);
1374             buf_WaitIO(scp, bp);
1375             lock_ReleaseMutex(&bp->mx);
1376
1377             code = (*cm_buf_opsp->Stabilizep)(scp, userp, reqp);
1378             if (code) 
1379                 goto skip;
1380
1381             lock_ObtainWrite(&buf_globalLock);
1382             /* actually, we only know that buffer is clean if ref
1383              * count is 1, since we don't have buffer itself locked.
1384              */
1385             if (!(bp->flags & CM_BUF_DIRTY)) {
1386                 if (bp->refCount == 1) {        /* bp is held above */
1387                     nbp = bp->fileHashp;
1388                     if (nbp) 
1389                         buf_HoldLocked(nbp);
1390                     buf_ReleaseLocked(bp);
1391                     didRelease = 1;
1392                     buf_Recycle(bp);
1393                 }
1394             }
1395             lock_ReleaseWrite(&buf_globalLock);
1396
1397             (*cm_buf_opsp->Unstabilizep)(scp, userp);
1398         }
1399
1400       skip:
1401         if (!didRelease) {
1402             lock_ObtainWrite(&buf_globalLock);
1403             nbp = bp->fileHashp;
1404             if (nbp)
1405                 buf_HoldLocked(nbp);
1406             buf_ReleaseLocked(bp);
1407             lock_ReleaseWrite(&buf_globalLock);
1408         }
1409     }   /* for loop over a bunch of buffers */
1410
1411 #ifdef TESTING
1412     buf_ValidateBufQueues();
1413 #endif /* TESTING */
1414
1415     /* done */
1416     return code;
1417 }       
1418
1419 long buf_CleanVnode(struct cm_scache *scp, cm_user_t *userp, cm_req_t *reqp)
1420 {
1421     long code = 0;
1422     long wasDirty = 0;
1423     cm_buf_t *bp;               /* buffer we're hacking on */
1424     cm_buf_t *nbp;              /* next one */
1425     long i;
1426
1427     i = BUF_FILEHASH(&scp->fid);
1428
1429     lock_ObtainWrite(&buf_globalLock);
1430     bp = cm_data.buf_fileHashTablepp[i];
1431     if (bp) 
1432         buf_HoldLocked(bp);
1433     lock_ReleaseWrite(&buf_globalLock);
1434     for (; bp; bp = nbp) {
1435         /* clean buffer synchronously */
1436         if (cm_FidCmp(&bp->fid, &scp->fid) == 0) {
1437             if (userp) {
1438                 cm_HoldUser(userp);
1439                 lock_ObtainMutex(&bp->mx);
1440                 if (bp->userp) 
1441                     cm_ReleaseUser(bp->userp);
1442                 bp->userp = userp;
1443                 lock_ReleaseMutex(&bp->mx);
1444             }   
1445             wasDirty = buf_CleanAsync(bp, reqp);
1446             buf_CleanWait(scp, bp);
1447             lock_ObtainMutex(&bp->mx);
1448             if (bp->flags & CM_BUF_ERROR) {
1449                 code = bp->error;
1450                 if (code == 0) 
1451                     code = -1;
1452             }
1453             lock_ReleaseMutex(&bp->mx);
1454         }
1455
1456         lock_ObtainWrite(&buf_globalLock);
1457         nbp = bp->fileHashp;
1458         if (nbp) 
1459             buf_HoldLocked(nbp);
1460         buf_ReleaseLocked(bp);
1461         lock_ReleaseWrite(&buf_globalLock);
1462     }   /* for loop over a bunch of buffers */
1463
1464 #ifdef TESTING
1465     buf_ValidateBufQueues();
1466 #endif /* TESTING */
1467
1468     /* done */
1469     return code;
1470 }
1471
1472 #ifdef TESTING
1473 void
1474 buf_ValidateBufQueues(void)
1475 {
1476     cm_buf_t * bp, *bpb, *bpf, *bpa;
1477     afs_uint32 countf=0, countb=0, counta=0;
1478
1479     lock_ObtainRead(&buf_globalLock);
1480     for (bp = cm_data.buf_freeListEndp; bp; bp=(cm_buf_t *) osi_QPrev(&bp->q)) {
1481         if (bp->magic != CM_BUF_MAGIC)
1482             osi_panic("buf magic error",__FILE__,__LINE__);
1483         countb++;
1484         bpb = bp;
1485     }
1486
1487     for (bp = cm_data.buf_freeListp; bp; bp=(cm_buf_t *) osi_QNext(&bp->q)) {
1488         if (bp->magic != CM_BUF_MAGIC)
1489             osi_panic("buf magic error",__FILE__,__LINE__);
1490         countf++;
1491         bpf = bp;
1492     }
1493
1494     for (bp = cm_data.buf_allp; bp; bp=bp->allp) {
1495         if (bp->magic != CM_BUF_MAGIC)
1496             osi_panic("buf magic error",__FILE__,__LINE__);
1497         counta++;
1498         bpa = bp;
1499     }
1500     lock_ReleaseRead(&buf_globalLock);
1501
1502     if (countb != countf)
1503         osi_panic("buf magic error",__FILE__,__LINE__);
1504
1505     if (counta != cm_data.buf_nbuffers)
1506         osi_panic("buf magic error",__FILE__,__LINE__);
1507 }
1508 #endif /* TESTING */
1509
1510 /* dump the contents of the buf_hashTablepp. */
1511 int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock)
1512 {
1513     int zilch;
1514     cm_buf_t *bp;
1515     char output[1024];
1516     int i;
1517   
1518     if (cm_data.buf_hashTablepp == NULL)
1519         return -1;
1520
1521     if (lock)
1522         lock_ObtainRead(&buf_globalLock);
1523   
1524     StringCbPrintfA(output, sizeof(output), "%s - dumping buf_HashTable - buf_hashSize=%d\n", 
1525                     cookie, cm_data.buf_hashSize);
1526     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1527   
1528     for (i = 0; i < cm_data.buf_hashSize; i++)
1529     {
1530         for (bp = cm_data.buf_hashTablepp[i]; bp; bp=bp->hashp) 
1531         {
1532             if (bp->refCount)
1533             {
1534                 StringCbPrintfA(output, sizeof(output), "vnode=%d, unique=%d), size=%d refCount=%d\n", 
1535                         cookie, (void *)bp, i, bp->fid.cell, bp->fid.volume, 
1536                         bp->fid.vnode, bp->fid.unique, bp->size, bp->refCount);
1537                 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1538             }
1539         }
1540     }
1541   
1542     StringCbPrintfA(output, sizeof(output), "%s - Done dumping buf_HashTable.\n", cookie);
1543     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1544
1545     if (lock)
1546         lock_ReleaseRead(&buf_globalLock);
1547     return 0;
1548 }
1549
1550 void buf_ForceTrace(BOOL flush)
1551 {
1552     HANDLE handle;
1553     int len;
1554     char buf[256];
1555
1556     if (!buf_logp) 
1557         return;
1558
1559     len = GetTempPath(sizeof(buf)-10, buf);
1560     StringCbCopyA(&buf[len], sizeof(buf)-len, "/afs-buffer.log");
1561     handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
1562                             NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1563     if (handle == INVALID_HANDLE_VALUE) {
1564         osi_panic("Cannot create log file", __FILE__, __LINE__);
1565     }
1566     osi_LogPrint(buf_logp, handle);
1567     if (flush)
1568         FlushFileBuffers(handle);
1569     CloseHandle(handle);
1570 }
1571
1572 long buf_DirtyBuffersExist(cm_fid_t *fidp)
1573 {
1574     cm_buf_t *bp;
1575     afs_uint32 bcount = 0;
1576
1577     for (bp = cm_data.buf_allp; bp; bp=bp->allp, bcount++) {
1578         if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY))
1579             return 1;
1580     }
1581     return 0;
1582 }
1583
1584 #if 0
1585 long buf_CleanDirtyBuffers(cm_scache_t *scp)
1586 {
1587     cm_buf_t *bp;
1588     afs_uint32 bcount = 0;
1589     cm_fid_t * fidp = &scp->fid;
1590
1591     for (bp = cm_data.buf_allp; bp; bp=bp->allp, bcount++) {
1592         if (!cm_FidCmp(fidp, &bp->fid) && (bp->flags & CM_BUF_DIRTY)) {
1593                 buf_Hold(bp);
1594             lock_ObtainMutex(&bp->mx);
1595             bp->cmFlags &= ~CM_BUF_CMSTORING;
1596             bp->flags &= ~CM_BUF_DIRTY;
1597             bp->flags |= CM_BUF_ERROR;
1598             bp->error = VNOVNODE;
1599             bp->dataVersion = -1; /* bad */
1600             bp->dirtyCounter++;
1601             if (bp->flags & CM_BUF_WAITING) {
1602                 osi_Log2(buf_logp, "BUF CleanDirtyBuffers Waking [scp 0x%x] bp 0x%x", scp, bp);
1603                 osi_Wakeup((long) &bp);
1604             }
1605             lock_ReleaseMutex(&bp->mx);
1606             buf_Release(bp);
1607         }
1608     }
1609     return 0;
1610 }
1611 #endif