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