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