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