freelance-misc-20040807
[openafs.git] / src / WINNT / afsd / cm_dcache.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 #include <afs/param.h>
11 #include <afs/stds.h>
12
13 #ifndef DJGPP
14 #include <windows.h>
15 #include <winsock2.h>
16 #include <nb30.h>
17 #endif /* !DJGPP */
18 #include <malloc.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <osi.h>
22
23 #include "afsd.h"
24
25 #ifdef DEBUG
26 extern void afsi_log(char *pattern, ...);
27 #endif
28
29 osi_mutex_t cm_bufGetMutex;
30 #ifdef AFS_FREELANCE_CLIENT
31 extern osi_mutex_t cm_Freelance_Lock;
32 #endif
33
34 /* functions called back from the buffer package when reading or writing data,
35  * or when holding or releasing a vnode pointer.
36  */
37 long cm_BufWrite(void *vfidp, osi_hyper_t *offsetp, long length, long flags,
38         cm_user_t *userp, cm_req_t *reqp)
39 {
40         /* store the data back from this buffer; the buffer is locked and held,
41          * but the vnode involved isn't locked, yet.  It is held by its
42          * reference from the buffer, which won't change until the buffer is
43          * released by our caller.  Thus, we don't have to worry about holding
44          * bufp->scp.
45          */
46         long code;
47         cm_fid_t *fidp = vfidp;
48     cm_scache_t *scp;
49     long nbytes;
50     long temp;
51     AFSFetchStatus outStatus;
52     AFSStoreStatus inStatus;
53     osi_hyper_t thyper;
54     AFSVolSync volSync;
55     AFSFid tfid;
56     struct rx_call *callp;
57     osi_queueData_t *qdp;
58     cm_buf_t *bufp;
59     long wbytes;
60     char *bufferp;
61     cm_conn_t *connp;
62     long truncPos;
63     cm_bulkIO_t biod;           /* bulk IO descriptor */
64
65     osi_assert(userp != NULL);
66
67     /* now, the buffer may or may not be filled with good data (buf_GetNew
68      * drops lots of locks, and may indeed return a properly initialized
69      * buffer, although more likely it will just return a new, empty, buffer.
70      */
71         scp = cm_FindSCache(fidp);
72         if (scp == NULL)
73                 return CM_ERROR_NOSUCHFILE;     /* shouldn't happen */
74
75         cm_AFSFidFromFid(&tfid, fidp);
76
77         lock_ObtainMutex(&scp->mx);
78         
79     code = cm_SetupStoreBIOD(scp, offsetp, length, &biod, userp, reqp);
80     if (code) {
81                 osi_Log1(afsd_logp, "cm_SetupStoreBIOD code %x", code);
82                 lock_ReleaseMutex(&scp->mx);
83                 cm_ReleaseSCache(scp);
84         return code;
85     }
86
87         if (biod.length == 0) {
88                 osi_Log0(afsd_logp, "cm_SetupStoreBIOD length 0");
89                 lock_ReleaseMutex(&scp->mx);
90                 cm_ReleaseBIOD(&biod, 1);       /* should be a NOOP */
91                 cm_ReleaseSCache(scp);
92         return 0;
93         }   
94
95         /* Serialize StoreData RPC's; for rationale see cm_scache.c */
96         (void) cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA_EXCL);
97
98         /* prepare the output status for the store */
99         scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
100     cm_StatusFromAttr(&inStatus, scp, NULL);
101     truncPos = scp->length.LowPart;
102     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
103          && scp->truncPos.LowPart < (unsigned long) truncPos)
104         truncPos = scp->truncPos.LowPart;
105         scp->mask &= ~CM_SCACHEMASK_TRUNCPOS;
106                 
107         /* compute how many bytes to write from this buffer */
108     thyper = LargeIntegerSubtract(scp->length, biod.offset);
109     if (LargeIntegerLessThanZero(thyper)) {
110                 /* entire buffer is past EOF */
111                 nbytes = 0;
112     }
113     else {
114                 /* otherwise write out part of buffer before EOF, but not
115          * more than bufferSize bytes.
116          */
117                 nbytes = thyper.LowPart;
118         if (nbytes > biod.length) 
119             nbytes = biod.length;
120     }
121
122         lock_ReleaseMutex(&scp->mx);
123         
124     /* now we're ready to do the store operation */
125     do {
126                 code = cm_Conn(&scp->fid, userp, reqp, &connp);
127         if (code) 
128             continue;
129                 
130                 callp = rx_NewCall(connp->callp);
131
132                 osi_Log3(afsd_logp, "CALL StoreData vp %x, off 0x%x, size 0x%x",
133                  (long) scp, biod.offset.LowPart, nbytes);
134
135         code = StartRXAFS_StoreData(callp, &tfid, &inStatus,
136                                     biod.offset.LowPart, nbytes, truncPos);
137
138                 if (code == 0) {
139             /* write the data from the the list of buffers */
140             qdp = NULL;
141                         while(nbytes > 0) {
142                                 if (qdp == NULL)
143                                         qdp = biod.bufListEndp;
144                                 else
145                                         qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
146                                 osi_assert(qdp != NULL);
147                 bufp = osi_GetQData(qdp);
148                 bufferp = bufp->datap;
149                 wbytes = nbytes;
150                 if (wbytes > buf_bufferSize) 
151                     wbytes = buf_bufferSize;
152
153                 /* write out wbytes of data from bufferp */
154                 temp = rx_Write(callp, bufferp, wbytes);
155                 if (temp != wbytes) {
156                     osi_Log2(afsd_logp, "rx_Write failed %d != %d",temp,wbytes);
157                     code = -1;
158                                         break;
159                                 } else {
160                     osi_Log1(afsd_logp, "rx_Write succeeded %d",temp);
161                 }
162                 nbytes -= wbytes;
163             }   /* while more bytes to write */
164                 }               /* if RPC started successfully */
165         else {
166             osi_Log1(afsd_logp, "StartRXAFS_StoreData failed (%lX)",code);
167         }
168                 if (code == 0) {
169                         code = EndRXAFS_StoreData(callp, &outStatus, &volSync);
170             if (code)
171                 osi_Log1(afsd_logp, "EndRXAFS_StoreData failed (%lX)",code);
172         }
173         code = rx_EndCall(callp, code);
174         osi_Log0(afsd_logp, "CALL StoreData DONE");
175                 
176         } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
177     code = cm_MapRPCError(code, reqp);
178         
179     /* now, clean up our state */
180     lock_ObtainMutex(&scp->mx);
181
182         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
183
184         if (code == 0) {
185                 /* now, here's something a little tricky: in AFS 3, a dirty
186                  * length can't be directly stored, instead, a dirty chunk is
187                  * stored that sets the file's size (by writing and by using
188                  * the truncate-first option in the store call).
189                  *
190          * At this point, we've just finished a store, and so the trunc
191                  * pos field is clean.  If the file's size at the server is at
192                  * least as big as we think it should be, then we turn off the
193                  * length dirty bit, since all the other dirty buffers must
194                  * precede this one in the file.
195          *
196          * The file's desired size shouldn't be smaller than what's
197                  * stored at the server now, since we just did the trunc pos
198                  * store.
199          *
200          * We have to turn off the length dirty bit as soon as we can,
201                  * so that we see updates made by other machines.
202          */
203                 if (outStatus.Length >= scp->length.LowPart)
204             scp->mask &= ~CM_SCACHEMASK_LENGTH;
205                 cm_MergeStatus(scp, &outStatus, &volSync, userp, 0);
206         } else {
207                 if (code == CM_ERROR_SPACE)
208                         scp->flags |= CM_SCACHEFLAG_OUTOFSPACE;
209                 else if (code == CM_ERROR_QUOTA)
210                         scp->flags |= CM_SCACHEFLAG_OVERQUOTA;
211         }
212     lock_ReleaseMutex(&scp->mx);
213     cm_ReleaseBIOD(&biod, 1);
214         cm_ReleaseSCache(scp);
215
216     return code;
217 }
218
219 /*
220  * Truncate the file, by sending a StoreData RPC with zero length.
221  *
222  * Called with scp locked.  Releases and re-obtains the lock.
223  */
224 long cm_StoreMini(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
225 {
226     AFSFetchStatus outStatus;
227     AFSStoreStatus inStatus;
228     AFSVolSync volSync;
229     AFSFid tfid;
230         long code;
231         long truncPos;
232         cm_conn_t *connp;
233     struct rx_call *callp;
234
235         /* Serialize StoreData RPC's; for rationale see cm_scache.c */
236         (void) cm_SyncOp(scp, NULL, userp, reqp, 0,
237                      CM_SCACHESYNC_STOREDATA_EXCL);
238
239         /* prepare the output status for the store */
240         inStatus.Mask = AFS_SETMODTIME;
241         inStatus.ClientModTime = scp->clientModTime;
242         scp->mask &= ~CM_SCACHEMASK_CLIENTMODTIME;
243
244         /* calculate truncation position */
245     truncPos = scp->length.LowPart;
246     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
247          && scp->truncPos.LowPart < (unsigned long) truncPos)
248         truncPos = scp->truncPos.LowPart;
249         scp->mask &= ~CM_SCACHEMASK_TRUNCPOS;
250                 
251         lock_ReleaseMutex(&scp->mx);
252
253         cm_AFSFidFromFid(&tfid, &scp->fid);
254
255     /* now we're ready to do the store operation */
256     do {
257                 code = cm_Conn(&scp->fid, userp, reqp, &connp);
258         if (code) 
259             continue;
260                 
261                 callp = rx_NewCall(connp->callp);
262
263         code = StartRXAFS_StoreData(callp, &tfid, &inStatus,
264                                     0, 0, truncPos);
265
266                 if (code == 0)
267                         code = EndRXAFS_StoreData(callp, &outStatus, &volSync);
268         code = rx_EndCall(callp, code);
269         } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
270     code = cm_MapRPCError(code, reqp);
271         
272     /* now, clean up our state */
273     lock_ObtainMutex(&scp->mx);
274
275         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
276
277         if (code == 0) {
278                 /*
279                  * For explanation of handling of CM_SCACHEMASK_LENGTH,
280                  * see cm_BufWrite().
281                  */
282                 if (outStatus.Length >= scp->length.LowPart)
283             scp->mask &= ~CM_SCACHEMASK_LENGTH;
284                 cm_MergeStatus(scp, &outStatus, &volSync, userp, 0);
285         }
286
287         return code;
288 }
289
290 long cm_BufRead(cm_buf_t *bufp, long nbytes, long *bytesReadp, cm_user_t *userp)
291 {
292         *bytesReadp = buf_bufferSize;
293
294         /* now return a code that means that I/O is done */
295     return 0;
296 }
297
298 /* stabilize scache entry, and return with it locked so 
299  * it stays stable.
300  */
301 long cm_BufStabilize(void *parmp, cm_user_t *userp, cm_req_t *reqp)
302 {
303         cm_scache_t *scp;
304     long code;
305
306     scp = parmp;
307         
308         lock_ObtainMutex(&scp->mx);
309     code = cm_SyncOp(scp, NULL, userp, reqp, 0, 
310                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
311         if (code) {
312                 lock_ReleaseMutex(&scp->mx);
313         return code;
314         }
315         
316     return 0;
317 }
318
319 /* undoes the work that cm_BufStabilize does: releases lock so things can change again */
320 long cm_BufUnstabilize(void *parmp, cm_user_t *userp)
321 {
322         cm_scache_t *scp;
323         
324     scp = parmp;
325         
326     lock_ReleaseMutex(&scp->mx);
327         
328         /* always succeeds */
329     return 0;
330 }
331
332 cm_buf_ops_t cm_bufOps = {
333         cm_BufWrite,
334     cm_BufRead,
335     cm_BufStabilize,
336     cm_BufUnstabilize
337 };
338
339 int cm_InitDCache(long chunkSize, long nbuffers)
340 {
341         lock_InitializeMutex(&cm_bufGetMutex, "buf_Get mutex");
342         if (nbuffers) 
343         buf_nbuffers = nbuffers;
344         return buf_Init(&cm_bufOps);
345 }
346
347 /* check to see if we have an up-to-date buffer.  The buffer must have
348  * previously been obtained by calling buf_Get.
349  *
350  * Make sure we have a callback, and that the dataversion matches.
351  *
352  * Scp must be locked.
353  *
354  * Bufp *may* be locked.
355  */
356 int cm_HaveBuffer(cm_scache_t *scp, cm_buf_t *bufp, int isBufLocked)
357 {
358         int code;
359         if (!cm_HaveCallback(scp))
360                 return 0;
361         if ((bufp->cmFlags
362              & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED))
363                 == (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED))
364                 return 1;
365         if (bufp->dataVersion == scp->dataVersion)
366                 return 1;
367         if (!isBufLocked) {
368                 code = lock_TryMutex(&bufp->mx);
369         if (code == 0) {
370                         /* don't have the lock, and can't lock it, then
371              * return failure.
372              */
373             return 0;
374         }
375     }
376
377         /* remember dirty flag for later */
378         code = bufp->flags & CM_BUF_DIRTY;
379
380         /* release lock if we obtained it here */
381         if (!isBufLocked) 
382         lock_ReleaseMutex(&bufp->mx);
383
384         /* if buffer was dirty, buffer is acceptable for use */
385         if (code) 
386             return 1;
387         else 
388             return 0;
389 }
390
391 /* used when deciding whether to do a prefetch or not */
392 long cm_CheckFetchRange(cm_scache_t *scp, osi_hyper_t *startBasep, long length,
393         cm_user_t *up, cm_req_t *reqp, osi_hyper_t *realBasep)
394 {
395         osi_hyper_t toffset;
396     osi_hyper_t tbase;
397     long code;
398     cm_buf_t *bp;
399     int stop;
400         
401     /* now scan all buffers in the range, looking for any that look like
402      * they need work.
403      */
404         tbase = *startBasep;
405         stop = 0;
406         lock_ObtainMutex(&scp->mx);
407     while(length > 0) {
408                 /* get callback so we can do a meaningful dataVersion comparison */
409         code = cm_SyncOp(scp, NULL, up, reqp, 0,
410                          CM_SCACHESYNC_NEEDCALLBACK
411                          | CM_SCACHESYNC_GETSTATUS);
412                 if (code) {
413                         scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
414                         lock_ReleaseMutex(&scp->mx);
415             return code;
416         }
417                 
418         if (LargeIntegerGreaterThanOrEqualTo(tbase, scp->length)) {
419                         /* we're past the end of file */
420             break;
421         }
422
423                 bp = buf_Find(scp, &tbase);
424                 /* We cheat slightly by not locking the bp mutex. */
425         if (bp) {
426             if ((bp->cmFlags
427                               & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING)) == 0
428                  && bp->dataVersion != scp->dataVersion)
429                 stop = 1;
430             buf_Release(bp);
431                 }
432         else 
433             stop = 1;
434
435                 /* if this buffer is essentially guaranteed to require a fetch,
436          * break out here and return this position.
437          */
438         if (stop) 
439             break;
440                 
441         toffset.LowPart = buf_bufferSize;
442         toffset.HighPart = 0;
443         tbase = LargeIntegerAdd(toffset, tbase);
444         length -= buf_bufferSize;
445     }
446         
447     /* if we get here, either everything is fine or stop stopped us at a
448      * particular buffer in the range that definitely needs to be fetched.
449      */
450     if (stop == 0) {
451                 /* return non-zero code since realBasep won't be valid */
452                 scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
453                 code = -1;
454     }
455     else {
456                 /* successfully found a page that will need fetching */
457                 *realBasep = tbase;
458         code = 0;
459     }
460     lock_ReleaseMutex(&scp->mx);
461     return code;
462 }
463
464 void cm_BkgStore(cm_scache_t *scp, long p1, long p2, long p3, long p4,
465         cm_user_t *userp)
466 {
467         osi_hyper_t toffset;
468     long length;
469         cm_req_t req;
470
471         cm_InitReq(&req);
472         req.flags |= CM_REQ_NORETRY;
473
474     toffset.LowPart = p1;
475     toffset.HighPart = p2;
476     length = p3;
477
478         osi_Log2(afsd_logp, "Starting BKG store vp 0x%x, base 0x%x", scp, p1);
479
480         cm_BufWrite(&scp->fid, &toffset, length, /* flags */ 0, userp, &req);
481
482         lock_ObtainMutex(&scp->mx);
483         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_ASYNCSTORE);
484     lock_ReleaseMutex(&scp->mx);
485 }
486
487 void cm_ClearPrefetchFlag(long code, cm_scache_t *scp, osi_hyper_t *base)
488 {
489         osi_hyper_t thyper;
490
491         if (code == 0) {
492                 thyper.LowPart = cm_chunkSize;
493                 thyper.HighPart = 0;
494                 thyper =  LargeIntegerAdd(*base, thyper);
495                 thyper.LowPart &= (-cm_chunkSize);
496                 if (LargeIntegerGreaterThan(*base, scp->prefetch.base))
497             scp->prefetch.base = *base;
498                 if (LargeIntegerGreaterThan(thyper, scp->prefetch.end))
499             scp->prefetch.end = thyper;
500         }
501         scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
502 }
503
504 /* do the prefetch */
505 void cm_BkgPrefetch(cm_scache_t *scp, long p1, long p2, long p3, long p4,
506         cm_user_t *userp)
507 {
508         long length;
509     osi_hyper_t base;
510     long code;
511     cm_buf_t *bp;
512         int cpff = 0;                   /* cleared prefetch flag */
513         cm_req_t req;
514
515         cm_InitReq(&req);
516         req.flags |= CM_REQ_NORETRY;
517         
518         base.LowPart = p1;
519     base.HighPart = p2;
520     length = p3;
521         
522         osi_Log2(afsd_logp, "Starting BKG prefetch vp 0x%x, base 0x%x", scp, p1);
523
524     code = buf_Get(scp, &base, &bp);
525
526         lock_ObtainMutex(&scp->mx);
527
528     if (code || (bp->cmFlags & CM_BUF_CMFETCHING)) {
529                 scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
530                 lock_ReleaseMutex(&scp->mx);
531                 return;
532         }
533
534     code = cm_GetBuffer(scp, bp, &cpff, userp, &req);
535         if (!cpff) 
536         cm_ClearPrefetchFlag(code, scp, &base);
537         lock_ReleaseMutex(&scp->mx);
538     buf_Release(bp);
539     return;
540 }
541
542 /* a read was issued to offsetp, and we have to determine whether we should
543  * do a prefetch.
544  */
545 void cm_ConsiderPrefetch(cm_scache_t *scp, osi_hyper_t *offsetp,
546         cm_user_t *userp, cm_req_t *reqp)
547 {
548         long code;
549     osi_hyper_t realBase;
550     osi_hyper_t readBase;
551         
552     readBase = *offsetp;
553         /* round up to chunk boundary */
554         readBase.LowPart += (cm_chunkSize-1);
555         readBase.LowPart &= (-cm_chunkSize);
556
557         lock_ObtainMutex(&scp->mx);
558         if ((scp->flags & CM_SCACHEFLAG_PREFETCHING)
559          || LargeIntegerLessThanOrEqualTo(readBase, scp->prefetch.base)) {
560                 lock_ReleaseMutex(&scp->mx);
561         return;
562         }
563         scp->flags |= CM_SCACHEFLAG_PREFETCHING;
564
565         /* start the scan at the latter of the end of this read or
566      * the end of the last fetched region.
567      */
568         if (LargeIntegerGreaterThan(scp->prefetch.end, readBase))
569         readBase = scp->prefetch.end;
570
571     lock_ReleaseMutex(&scp->mx);
572
573     code = cm_CheckFetchRange(scp, &readBase, cm_chunkSize, userp, reqp,
574                                   &realBase);
575         if (code) 
576         return; /* can't find something to prefetch */
577
578     osi_Log2(afsd_logp, "BKG Prefetch request vp 0x%x, base 0x%x",
579              scp, realBase.LowPart);
580
581     cm_QueueBKGRequest(scp, cm_BkgPrefetch, realBase.LowPart,
582                        realBase.HighPart, cm_chunkSize, 0, userp);
583 }
584
585 /* scp must be locked; temporarily unlocked during processing.
586  * If returns 0, returns buffers held in biop, and with
587  * CM_BUF_CMSTORING set.
588  *
589  * Caller *must* set CM_BUF_WRITING and reset the over.hEvent field if the
590  * buffer is ever unlocked before CM_BUF_DIRTY is cleared.  And if
591  * CM_BUF_WRITING is ever viewed by anyone, then it must be cleared, sleepers
592  * must be woken, and the event must be set when the I/O is done.  All of this
593  * is required so that buf_WaitIO synchronizes properly with the buffer as it
594  * is being written out.
595  */
596 long cm_SetupStoreBIOD(cm_scache_t *scp, osi_hyper_t *inOffsetp, long inSize,
597         cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
598 {
599     cm_buf_t *bufp;
600     osi_queueData_t *qdp;
601     osi_hyper_t thyper;
602     osi_hyper_t tbase;
603     osi_hyper_t scanStart;              /* where to start scan for dirty pages */
604     osi_hyper_t scanEnd;                /* where to stop scan for dirty pages */
605     osi_hyper_t firstModOffset; /* offset of first modified page in range */
606     long temp;
607     long code;
608     long flags;                 /* flags to cm_SyncOp */
609         
610         /* clear things out */
611         biop->scp = scp;                /* don't hold */
612     biop->offset = *inOffsetp;
613     biop->length = 0;
614     biop->bufListp = NULL;
615     biop->bufListEndp = NULL;
616         biop->reserved = 0;
617
618         /* reserve a chunk's worth of buffers */
619         lock_ReleaseMutex(&scp->mx);
620         buf_ReserveBuffers(cm_chunkSize / buf_bufferSize);
621         lock_ObtainMutex(&scp->mx);
622
623     bufp = NULL;
624     for(temp = 0; temp < inSize; temp += buf_bufferSize, bufp = NULL) {
625                 thyper.HighPart = 0;
626                 thyper.LowPart = temp;
627         tbase = LargeIntegerAdd(*inOffsetp, thyper);
628
629         bufp = buf_Find(scp, &tbase);
630         if (bufp) {
631                         /* get buffer mutex and scp mutex safely */
632                         lock_ReleaseMutex(&scp->mx);
633                         lock_ObtainMutex(&bufp->mx);
634                         lock_ObtainMutex(&scp->mx);
635
636                         flags = CM_SCACHESYNC_NEEDCALLBACK
637                                 | CM_SCACHESYNC_GETSTATUS
638                                 | CM_SCACHESYNC_STOREDATA
639                                 | CM_SCACHESYNC_BUFLOCKED;
640                         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags); 
641             if (code) {
642                                 lock_ReleaseMutex(&bufp->mx);
643                 buf_Release(bufp);
644                                 buf_UnreserveBuffers(cm_chunkSize / buf_bufferSize);
645                 return code;
646             }
647                         
648                         /* if the buffer is dirty, we're done */
649             if (bufp->flags & CM_BUF_DIRTY) {
650                 osi_assertx(!(bufp->flags & CM_BUF_WRITING),
651                             "WRITING w/o CMSTORING in SetupStoreBIOD");
652                                 bufp->flags |= CM_BUF_WRITING;
653                                 break;
654             }
655
656                         /* this buffer is clean, so there's no reason to process it */
657                         cm_SyncOpDone(scp, bufp, flags);
658                         lock_ReleaseMutex(&bufp->mx);
659                         buf_Release(bufp);
660         }
661     }
662
663         biop->reserved = 1;
664         
665     /* if we get here, if bufp is null, we didn't find any dirty buffers
666          * that weren't already being stored back, so we just quit now.
667      */
668         if (!bufp) {
669                 return 0;
670         }
671
672         /* don't need buffer mutex any more */
673         lock_ReleaseMutex(&bufp->mx);
674         
675         /* put this element in the list */
676     qdp = osi_QDAlloc();
677     osi_SetQData(qdp, bufp);
678         /* don't have to hold bufp, since held by buf_Find above */
679     osi_QAddH((osi_queue_t **) &biop->bufListp,
680               (osi_queue_t **) &biop->bufListEndp,
681               &qdp->q);
682     biop->length = buf_bufferSize;
683     firstModOffset = bufp->offset;
684     biop->offset = firstModOffset;
685
686         /* compute the window surrounding *inOffsetp of size cm_chunkSize */
687         scanStart = *inOffsetp;
688     scanStart.LowPart &= (-cm_chunkSize);
689         thyper.LowPart = cm_chunkSize;
690     thyper.HighPart = 0;
691         scanEnd = LargeIntegerAdd(scanStart, thyper);
692
693         flags = CM_SCACHESYNC_NEEDCALLBACK
694                 | CM_SCACHESYNC_GETSTATUS
695         | CM_SCACHESYNC_STOREDATA
696         | CM_SCACHESYNC_BUFLOCKED
697         | CM_SCACHESYNC_NOWAIT;
698
699         /* start by looking backwards until scanStart */
700         thyper.HighPart = 0;            /* hyper version of buf_bufferSize */
701     thyper.LowPart = buf_bufferSize;
702         tbase = LargeIntegerSubtract(firstModOffset, thyper);
703     while(LargeIntegerGreaterThanOrEqualTo(tbase, scanStart)) {
704         /* see if we can find the buffer */
705                 bufp = buf_Find(scp, &tbase);
706         if (!bufp) 
707             break;
708
709                 /* try to lock it, and quit if we can't (simplifies locking) */
710         code = lock_TryMutex(&bufp->mx);
711         if (code == 0) {
712                         buf_Release(bufp);
713             break;
714         }
715                 
716         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
717         if (code) {
718                         lock_ReleaseMutex(&bufp->mx);
719                         buf_Release(bufp);
720             break;
721         }
722                 
723                 if (!(bufp->flags & CM_BUF_DIRTY)) {
724                         /* buffer is clean, so we shouldn't add it */
725                         cm_SyncOpDone(scp, bufp, flags);
726                         lock_ReleaseMutex(&bufp->mx);
727                         buf_Release(bufp);
728             break;
729         }
730
731                 /* don't need buffer mutex any more */
732                 lock_ReleaseMutex(&bufp->mx);
733
734         /* we have a dirty buffer ready for storing.  Add it to the tail
735          * of the list, since it immediately precedes all of the disk
736          * addresses we've already collected.
737          */
738                 qdp = osi_QDAlloc();
739         osi_SetQData(qdp, bufp);
740         /* no buf_hold necessary, since we have it held from buf_Find */
741         osi_QAddT((osi_queue_t **) &biop->bufListp,
742                   (osi_queue_t **) &biop->bufListEndp,
743                   &qdp->q);
744
745                 /* update biod info describing the transfer */
746         biop->offset = LargeIntegerSubtract(biop->offset, thyper);
747         biop->length += buf_bufferSize;
748
749         /* update loop pointer */
750         tbase = LargeIntegerSubtract(tbase, thyper);
751     }   /* while loop looking for pages preceding the one we found */
752
753         /* now, find later dirty, contiguous pages, and add them to the list */
754         thyper.HighPart = 0;            /* hyper version of buf_bufferSize */
755     thyper.LowPart = buf_bufferSize;
756         tbase = LargeIntegerAdd(firstModOffset, thyper);
757     while(LargeIntegerLessThan(tbase, scanEnd)) {
758                 /* see if we can find the buffer */
759                 bufp = buf_Find(scp, &tbase);
760         if (!bufp) 
761             break;
762
763                 /* try to lock it, and quit if we can't (simplifies locking) */
764         code = lock_TryMutex(&bufp->mx);
765         if (code == 0) {
766                         buf_Release(bufp);
767             break;
768         }
769
770         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
771         if (code) {
772                         lock_ReleaseMutex(&bufp->mx);
773                         buf_Release(bufp);
774             break;
775         }
776                 
777                 if (!(bufp->flags & CM_BUF_DIRTY)) {
778                         /* buffer is clean, so we shouldn't add it */
779                         cm_SyncOpDone(scp, bufp, flags);
780                         lock_ReleaseMutex(&bufp->mx);
781                         buf_Release(bufp);
782             break;
783         }
784
785                 /* don't need buffer mutex any more */
786                 lock_ReleaseMutex(&bufp->mx);
787
788         /* we have a dirty buffer ready for storing.  Add it to the head
789          * of the list, since it immediately follows all of the disk
790          * addresses we've already collected.
791          */
792                 qdp = osi_QDAlloc();
793         osi_SetQData(qdp, bufp);
794         /* no buf_hold necessary, since we have it held from buf_Find */
795         osi_QAddH((osi_queue_t **) &biop->bufListp,
796                   (osi_queue_t **) &biop->bufListEndp,
797                   &qdp->q);
798
799                 /* update biod info describing the transfer */
800         biop->length += buf_bufferSize;
801                 
802         /* update loop pointer */
803         tbase = LargeIntegerAdd(tbase, thyper);
804     }   /* while loop looking for pages following the first page we found */
805         
806     /* finally, we're done */
807     return 0;
808 }
809
810 /* scp must be locked; temporarily unlocked during processing.
811  * If returns 0, returns buffers held in biop, and with
812  * CM_BUF_CMFETCHING flags set.
813  * If an error is returned, we don't return any buffers.
814  */
815 long cm_SetupFetchBIOD(cm_scache_t *scp, osi_hyper_t *offsetp,
816                         cm_bulkIO_t *biop, cm_user_t *up, cm_req_t *reqp)
817 {
818         long code;
819     cm_buf_t *tbp;
820     osi_hyper_t toffset;                /* a long long temp variable */
821     osi_hyper_t pageBase;               /* base offset we're looking at */
822     osi_queueData_t *qdp;               /* one temp queue structure */
823     osi_queueData_t *tqdp;              /* another temp queue structure */
824     long collected;                     /* how many bytes have been collected */
825     int isFirst;
826     long flags;
827     osi_hyper_t fileSize;               /* the # of bytes in the file */
828     osi_queueData_t *heldBufListp;      /* we hold all buffers in this list */
829     osi_queueData_t *heldBufListEndp;   /* first one */
830         int reserving;
831
832     biop->scp = scp;
833     biop->offset = *offsetp;
834         /* null out the list of buffers */
835     biop->bufListp = biop->bufListEndp = NULL;
836         biop->reserved = 0;
837
838         /* first lookup the file's length, so we know when to stop */
839     code = cm_SyncOp(scp, NULL, up, reqp, 0, CM_SCACHESYNC_NEEDCALLBACK
840                      | CM_SCACHESYNC_GETSTATUS);
841     if (code) 
842         return code;
843         
844         /* copy out size, since it may change */
845     fileSize = scp->serverLength;
846         
847     lock_ReleaseMutex(&scp->mx);
848
849         pageBase = *offsetp;
850     collected = pageBase.LowPart & (cm_chunkSize - 1);
851     heldBufListp = NULL;
852     heldBufListEndp = NULL;
853
854         /*
855          * Obtaining buffers can cause dirty buffers to be recycled, which
856          * can cause a storeback, so cannot be done while we have buffers
857          * reserved.
858          *
859          * To get around this, we get buffers twice.  Before reserving buffers,
860          * we obtain and release each one individually.  After reserving
861          * buffers, we try to obtain them again, but only by lookup, not by
862          * recycling.  If a buffer has gone away while we were waiting for
863          * the others, we just use whatever buffers we already have.
864          *
865          * On entry to this function, we are already holding a buffer, so we
866          * can't wait for reservation.  So we call buf_TryReserveBuffers()
867          * instead.  Not only that, we can't really even call buf_Get(), for
868          * the same reason.  We can't avoid that, though.  To avoid deadlock
869          * we allow only one thread to be executing the buf_Get()-buf_Release()
870          * sequence at a time.
871          */
872
873         /* first hold all buffers, since we can't hold any locks in buf_Get */
874     while (1) {
875                 /* stop at chunk boundary */
876                 if (collected >= cm_chunkSize) break;
877                 
878         /* see if the next page would be past EOF */
879         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize)) break;
880
881                 lock_ObtainMutex(&cm_bufGetMutex);
882
883                 code = buf_Get(scp, &pageBase, &tbp);
884         if (code) {
885                         lock_ReleaseMutex(&cm_bufGetMutex);
886                         lock_ObtainMutex(&scp->mx);
887                         return code;
888                 }
889                 
890                 buf_Release(tbp);
891
892                 lock_ReleaseMutex(&cm_bufGetMutex);
893
894         toffset.HighPart = 0;
895         toffset.LowPart = buf_bufferSize;
896         pageBase = LargeIntegerAdd(toffset, pageBase);
897                 collected += buf_bufferSize;
898     }
899
900     /* reserve a chunk's worth of buffers if possible */
901         reserving = buf_TryReserveBuffers(cm_chunkSize / buf_bufferSize);
902
903         pageBase = *offsetp;
904     collected = pageBase.LowPart & (cm_chunkSize - 1);
905
906         /* now hold all buffers, if they are still there */
907     while (1) {
908                 /* stop at chunk boundary */
909                 if (collected >= cm_chunkSize) 
910             break;
911                 
912         /* see if the next page would be past EOF */
913         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize)) 
914             break;
915
916         tbp = buf_Find(scp, &pageBase);
917                 if (!tbp) 
918             break;
919
920         /* add the buffer to the list */
921                 qdp = osi_QDAlloc();
922         osi_SetQData(qdp, tbp);
923         osi_QAdd((osi_queue_t **)&heldBufListp, &qdp->q);
924         if (!heldBufListEndp) heldBufListEndp = qdp;
925                 /* leave tbp held (from buf_Get) */
926
927                 if (!reserving) 
928             break;
929
930         collected += buf_bufferSize;
931         toffset.HighPart = 0;
932         toffset.LowPart = buf_bufferSize;
933         pageBase = LargeIntegerAdd(toffset, pageBase);
934     }
935
936     /* look at each buffer, adding it into the list if it looks idle and
937          * filled with old data.  One special case: wait for idle if it is the
938          * first buffer since we really need that one for our caller to make
939          * any progress.
940      */
941     isFirst = 1;
942     collected = 0;              /* now count how many we'll really use */
943         for(tqdp = heldBufListEndp;
944         tqdp;
945             tqdp = (osi_queueData_t *) osi_QPrev(&tqdp->q)) {
946                 /* get a ptr to the held buffer */
947                 tbp = osi_GetQData(tqdp);
948         pageBase = tbp->offset;
949
950                 /* now lock the buffer lock */
951                 lock_ObtainMutex(&tbp->mx);
952                 lock_ObtainMutex(&scp->mx);
953
954                 /* don't bother fetching over data that is already current */
955                 if (tbp->dataVersion == scp->dataVersion) {
956                         /* we don't need this buffer, since it is current */
957                         lock_ReleaseMutex(&scp->mx);
958             lock_ReleaseMutex(&tbp->mx);
959             break;
960         }
961
962                 flags = CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_FETCHDATA
963                         | CM_SCACHESYNC_BUFLOCKED;
964                 if (!isFirst) 
965             flags |= CM_SCACHESYNC_NOWAIT;
966
967                 /* wait for the buffer to serialize, if required.  Doesn't
968                  * release the scp or buffer lock(s) if NOWAIT is specified.
969          */
970                 code = cm_SyncOp(scp, tbp, up, reqp, 0, flags);
971         if (code) {
972                         lock_ReleaseMutex(&scp->mx);
973                         lock_ReleaseMutex(&tbp->mx);
974             break;
975                 }
976                 
977                 /* don't fetch over dirty buffers */
978         if (tbp->flags & CM_BUF_DIRTY) {
979                         cm_SyncOpDone(scp, tbp, flags);
980                         lock_ReleaseMutex(&scp->mx);
981             lock_ReleaseMutex(&tbp->mx);
982             break;
983                 }
984
985                 /* Release locks */
986                 lock_ReleaseMutex(&scp->mx);
987                 lock_ReleaseMutex(&tbp->mx);
988
989         /* add the buffer to the list */
990                 qdp = osi_QDAlloc();
991         osi_SetQData(qdp, tbp);
992         osi_QAdd((osi_queue_t **)&biop->bufListp, &qdp->q);
993         if (!biop->bufListEndp) 
994             biop->bufListEndp = qdp;
995                 buf_Hold(tbp);
996
997                 /* from now on, a failure just stops our collection process, but
998          * we still do the I/O to whatever we've already managed to collect.
999          */
1000         isFirst = 0;
1001         collected += buf_bufferSize;
1002     }
1003         
1004     /* now, we've held in biop->bufListp all the buffer's we're really
1005          * interested in.  We also have holds left from heldBufListp, and we
1006          * now release those holds on the buffers.
1007      */
1008         for(qdp = heldBufListp; qdp; qdp = tqdp) {
1009                 tqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1010                 tbp = osi_GetQData(qdp);
1011         osi_QDFree(qdp);
1012         buf_Release(tbp);
1013     }
1014
1015         /* Caller expects this */
1016         lock_ObtainMutex(&scp->mx);
1017  
1018         /* if we got a failure setting up the first buffer, then we don't have
1019      * any side effects yet, and we also have failed an operation that the
1020      * caller requires to make any progress.  Give up now.
1021      */
1022     if (code && isFirst) {
1023                 buf_UnreserveBuffers(cm_chunkSize / buf_bufferSize);
1024                 return code;
1025         }
1026         
1027     /* otherwise, we're still OK, and should just return the I/O setup we've
1028      * got.
1029      */
1030         biop->length = collected;
1031         biop->reserved = reserving;
1032     return 0;
1033 }
1034
1035 /* release a bulk I/O structure that was setup by cm_SetupFetchBIOD or by
1036  * cm_SetupStoreBIOD
1037  */
1038 void cm_ReleaseBIOD(cm_bulkIO_t *biop, int isStore)
1039 {
1040         cm_scache_t *scp;
1041     cm_buf_t *bufp;
1042     osi_queueData_t *qdp;
1043     osi_queueData_t *nqdp;
1044     int flags;
1045
1046         /* Give back reserved buffers */
1047         if (biop->reserved)
1048                 buf_UnreserveBuffers(cm_chunkSize / buf_bufferSize);
1049         
1050         flags = CM_SCACHESYNC_NEEDCALLBACK;
1051     if (isStore)
1052         flags |= CM_SCACHESYNC_STOREDATA;
1053         else
1054                 flags |= CM_SCACHESYNC_FETCHDATA;
1055
1056         scp = biop->scp;
1057     for(qdp = biop->bufListp; qdp; qdp = nqdp) {
1058                 /* lookup next guy first, since we're going to free this one */
1059                 nqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1060                 
1061                 /* extract buffer and free queue data */
1062         bufp = osi_GetQData(qdp);
1063         osi_QDFree(qdp);
1064
1065         /* now, mark I/O as done, unlock the buffer and release it */
1066                 lock_ObtainMutex(&bufp->mx);
1067                 lock_ObtainMutex(&scp->mx);
1068         cm_SyncOpDone(scp, bufp, flags);
1069                 lock_ReleaseMutex(&scp->mx);
1070                 
1071                 /* turn off writing and wakeup users */
1072         if (isStore) {
1073             if (bufp->flags & CM_BUF_WAITING) {
1074                                 osi_Wakeup((long) bufp);
1075             }
1076                         bufp->flags &= ~(CM_BUF_WAITING | CM_BUF_WRITING
1077                              | CM_BUF_DIRTY);
1078         }
1079
1080         lock_ReleaseMutex(&bufp->mx);
1081         buf_Release(bufp);
1082     }
1083
1084     /* clean things out */
1085     biop->bufListp = NULL;
1086     biop->bufListEndp = NULL;
1087 }   
1088
1089 /* Fetch a buffer.  Called with scp locked.
1090  * The scp is locked on return.
1091  */
1092 long cm_GetBuffer(cm_scache_t *scp, cm_buf_t *bufp, int *cpffp, cm_user_t *up,
1093         cm_req_t *reqp)
1094 {
1095         long code;
1096     long nbytes;                        /* bytes in transfer */
1097     long rbytes;                        /* bytes in rx_Read call */
1098     long temp;
1099     AFSFetchStatus afsStatus;
1100     AFSCallBack callback;
1101     AFSVolSync volSync;
1102     char *bufferp;
1103     cm_buf_t *tbufp;            /* buf we're filling */
1104     osi_queueData_t *qdp;               /* q element we're scanning */
1105     AFSFid tfid;
1106     struct rx_call *callp;
1107     cm_bulkIO_t biod;           /* bulk IO descriptor */
1108     cm_conn_t *connp;
1109         int getroot;
1110         long t1, t2;
1111
1112     /* now, the buffer may or may not be filled with good data (buf_GetNew
1113      * drops lots of locks, and may indeed return a properly initialized
1114      * buffer, although more likely it will just return a new, empty, buffer.
1115      */
1116
1117 #ifdef AFS_FREELANCE_CLIENT
1118
1119         // yj: if they're trying to get the /afs directory, we need to
1120         // handle it differently, since it's local rather than on any
1121         // server
1122
1123         getroot = (scp==cm_rootSCachep);
1124         if (getroot)
1125                 osi_Log1(afsd_logp,"GetBuffer returns cm_rootSCachep=%x",cm_rootSCachep);
1126 #endif
1127
1128         cm_AFSFidFromFid(&tfid, &scp->fid);
1129
1130         code = cm_SetupFetchBIOD(scp, &bufp->offset, &biod, up, reqp);
1131         if (code) {
1132                 /* couldn't even get the first page setup properly */
1133                 osi_Log1(afsd_logp, "SetupFetchBIOD failure code %d", code);
1134         return code;
1135         }
1136
1137     /* once we get here, we have the callback in place, we know that no one
1138          * is fetching the data now.  Check one last time that we still have
1139          * the wrong data, and then fetch it if we're still wrong.
1140          *
1141      * We can lose a race condition and end up with biod.length zero, in
1142          * which case we just retry.
1143      */
1144     if (bufp->dataVersion == scp->dataVersion || biod.length == 0) {
1145                 osi_Log3(afsd_logp, "Bad DVs %d, %d or length 0x%x",
1146                  bufp->dataVersion, scp->dataVersion, biod.length);
1147                 if ((bufp->dataVersion == -1
1148                      || bufp->dataVersion < scp->dataVersion)
1149              && LargeIntegerGreaterThanOrEqualTo(bufp->offset,
1150                                                  scp->serverLength)) {
1151                         if (bufp->dataVersion == -1)
1152                                 memset(bufp->datap, 0, buf_bufferSize);
1153                         bufp->dataVersion = scp->dataVersion;
1154                 }
1155                 lock_ReleaseMutex(&scp->mx);
1156                 cm_ReleaseBIOD(&biod, 0);
1157                 lock_ObtainMutex(&scp->mx);
1158         return 0;
1159     }
1160         
1161     lock_ReleaseMutex(&scp->mx);
1162
1163 #ifdef DISKCACHE95
1164     DPRINTF("cm_GetBuffer: fetching data scpDV=%d bufDV=%d scp=%x bp=%x dcp=%x\n",
1165             scp->dataVersion, bufp->dataVersion, scp, bufp, bufp->dcp);
1166 #endif /* DISKCACHE95 */
1167
1168 #ifdef AFS_FREELANCE_CLIENT
1169
1170         // yj code
1171         // if getroot then we don't need to make any calls
1172         // just return fake data
1173         
1174          if (cm_freelanceEnabled && getroot) {
1175                 // setup the fake status                        
1176                 afsStatus.InterfaceVersion = 0x1;
1177                 afsStatus.FileType = 0x2;
1178                 afsStatus.LinkCount = scp->linkCount;
1179                 afsStatus.Length = cm_fakeDirSize;
1180                 afsStatus.DataVersion = cm_fakeDirVersion;
1181                 afsStatus.Author = 0x1;
1182                 afsStatus.Owner = 0x0;
1183                 afsStatus.CallerAccess = 0x9;
1184                 afsStatus.AnonymousAccess = 0x9;
1185                 afsStatus.UnixModeBits = 0x1ff;
1186                 afsStatus.ParentVnode = 0x1;
1187                 afsStatus.ParentUnique = 0x1;
1188                 afsStatus.ResidencyMask = 0;
1189                 afsStatus.ClientModTime = FakeFreelanceModTime;
1190                 afsStatus.ServerModTime = FakeFreelanceModTime;
1191                 afsStatus.Group = 0;
1192                 afsStatus.SyncCounter = 0;
1193                 afsStatus.dataVersionHigh = 0;
1194         
1195                 // once we're done setting up the status info,
1196                 // we just fill the buffer pages with fakedata
1197                 // from cm_FakeRootDir. Extra pages are set to
1198                 // 0. 
1199                 
1200                 lock_ObtainMutex(&cm_Freelance_Lock);
1201                 t1 = bufp->offset.LowPart;
1202                 qdp = biod.bufListEndp;
1203                 while (qdp) {
1204                         tbufp = osi_GetQData(qdp);
1205                         bufferp=tbufp->datap;
1206                         memset(bufferp, 0, buf_bufferSize);
1207                         t2 = cm_fakeDirSize - t1;
1208                         if (t2>buf_bufferSize) t2=buf_bufferSize;
1209                         if (t2 > 0) {
1210                                 memcpy(bufferp, cm_FakeRootDir+t1, t2);
1211                         } else {
1212                                 t2 = 0;
1213                         }
1214                         t1+=t2;
1215                         qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1216                         
1217                 }
1218                 lock_ReleaseMutex(&cm_Freelance_Lock);
1219         
1220                 // once we're done, we skip over the part of the
1221                 // code that does the ACTUAL fetching of data for
1222                 // real files
1223
1224                 goto fetchingcompleted;
1225         }
1226
1227 #endif /* AFS_FREELANCE_CLIENT */
1228
1229         /* now make the call */
1230     do {
1231                 code = cm_Conn(&scp->fid, up, reqp, &connp);
1232         if (code) 
1233             continue;
1234                 
1235                 callp = rx_NewCall(connp->callp);
1236
1237                 osi_Log3(afsd_logp, "CALL FetchData vp %x, off 0x%x, size 0x%x",
1238                  (long) scp, biod.offset.LowPart, biod.length);
1239
1240         code = StartRXAFS_FetchData(callp, &tfid, biod.offset.LowPart,
1241                                     biod.length);
1242
1243                 /* now copy the data out of the pipe and put it in the buffer */
1244                 temp  = rx_Read(callp, (char *)&nbytes, 4);
1245                 if (temp == 4) {
1246                         nbytes = ntohl(nbytes);
1247             if (nbytes > biod.length) 
1248                 code = (callp->error < 0) ? callp->error : -1;
1249         }
1250         else 
1251             code = (callp->error < 0) ? callp->error : -1;
1252
1253                 if (code == 0) {
1254             qdp = biod.bufListEndp;
1255             if (qdp) {
1256                                 tbufp = osi_GetQData(qdp);
1257                 bufferp = tbufp->datap;
1258             }
1259             else 
1260                 bufferp = NULL;
1261                         /* fill nbytes of data from the pipe into the pages.
1262                          * When we stop, qdp will point at the last page we're
1263                          * dealing with, and bufferp will tell us where we
1264                          * stopped.  We'll need this info below when we clear
1265                          * the remainder of the last page out (and potentially
1266              * clear later pages out, if we fetch past EOF).
1267              */
1268             while(nbytes > 0) {
1269                                 /* assert that there are still more buffers;
1270                                  * our check above for nbytes being less than
1271                                  * biod.length should ensure this.
1272                  */
1273                                 osi_assert(bufferp != NULL);
1274
1275                                 /* read rbytes of data */
1276                 rbytes = (nbytes > buf_bufferSize? buf_bufferSize : nbytes);
1277                 temp = rx_Read(callp, bufferp, rbytes);
1278                 if (temp < rbytes) {
1279                     code = (callp->error < 0) ? callp->error : -1;
1280                     break;
1281                                 }
1282
1283                                 /* allow read-while-fetching.
1284                                  * if this is the last buffer, clear the
1285                                  * PREFETCHING flag, so the reader waiting for
1286                                  * this buffer will start a prefetch.
1287                                  */
1288                                 tbufp->cmFlags |= CM_BUF_CMFULLYFETCHED;
1289                                 lock_ObtainMutex(&scp->mx);
1290                                 if (scp->flags & CM_SCACHEFLAG_WAITING) {
1291                                         scp->flags &= ~CM_SCACHEFLAG_WAITING;
1292                                         osi_Wakeup((long) &scp->flags);
1293                                 }
1294                                 if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
1295                                         *cpffp = 1;
1296                                         cm_ClearPrefetchFlag(0, scp, &biod.offset);
1297                                 }
1298                                 lock_ReleaseMutex(&scp->mx);
1299
1300                                 /* and adjust counters */
1301                 nbytes -= temp;
1302                                 
1303                 /* and move to the next buffer */
1304                                 if (nbytes != 0) {
1305                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1306                     if (qdp) {
1307                                                 tbufp = osi_GetQData(qdp);
1308                         bufferp = tbufp->datap;
1309                     }
1310                     else 
1311                         bufferp = NULL;
1312                                 } else 
1313                     bufferp += temp;
1314             }
1315
1316             /* zero out remainder of last pages, in case we are
1317                          * fetching past EOF.  We were fetching an integral #
1318                          * of pages, but stopped, potentially in the middle of
1319                          * a page.  Zero the remainder of that page, and then
1320                          * all of the rest of the pages.
1321              */
1322                         /* bytes fetched */
1323             rbytes = bufferp - tbufp->datap;
1324                         /* bytes left to zero */
1325             rbytes = buf_bufferSize - rbytes;
1326             while(qdp) {
1327                 if (rbytes != 0)
1328                                         memset(bufferp, 0, rbytes);
1329                 qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1330                                 if (qdp == NULL) 
1331                     break;
1332                                 tbufp = osi_GetQData(qdp);
1333                 bufferp = tbufp->datap;
1334                                 /* bytes to clear in this page */
1335                                 rbytes = buf_bufferSize;
1336             }
1337                 }
1338
1339                 if (code == 0)
1340                         code = EndRXAFS_FetchData(callp, &afsStatus, &callback, &volSync);
1341                 else
1342                         osi_Log0(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error");
1343         code = rx_EndCall(callp, code);
1344         if (code == RXKADUNKNOWNKEY)
1345             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
1346         osi_Log0(afsd_logp, "CALL FetchData DONE");
1347
1348         } while (cm_Analyze(connp, up, reqp, &scp->fid, &volSync, NULL, NULL, code));
1349
1350   fetchingcompleted:
1351     code = cm_MapRPCError(code, reqp);
1352
1353     lock_ObtainMutex(&scp->mx);
1354         /* we know that no one else has changed the buffer, since we still have
1355          * the fetching flag on the buffers, and we have the scp locked again.
1356          * Copy in the version # into the buffer if we got code 0 back from the
1357          * read.
1358      */
1359         if (code == 0) {
1360                 for(qdp = biod.bufListp;
1361                     qdp;
1362                     qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1363                         tbufp = osi_GetQData(qdp);
1364             tbufp->dataVersion = afsStatus.DataVersion;
1365
1366 #ifdef DISKCACHE95
1367             /* write buffer out to disk cache */
1368             diskcache_Update(tbufp->dcp, tbufp->datap, buf_bufferSize,
1369                               tbufp->dataVersion);
1370 #endif /* DISKCACHE95 */
1371         }
1372     }
1373
1374         /* release scatter/gather I/O structure (buffers, locks) */
1375         lock_ReleaseMutex(&scp->mx);
1376         cm_ReleaseBIOD(&biod, 0);
1377         lock_ObtainMutex(&scp->mx);
1378
1379     if (code == 0) 
1380         cm_MergeStatus(scp, &afsStatus, &volSync, up, 0);
1381         return code;
1382 }