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