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