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