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