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