Windows: buffers whose offsets are beyond EOF should be zero filled and locally allocated
[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 #include <windows.h>
14 #include <winsock2.h>
15 #include <nb30.h>
16 #ifdef COMMENT
17 #include <malloc.h>
18 #endif
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 #ifdef AFS_FREELANCE_CLIENT
30 extern osi_mutex_t cm_Freelance_Lock;
31 #endif
32
33 #ifdef AFS_LARGEFILES
34 /* we can access connp->serverp without holding a lock because that
35    never changes since the connection is made. */
36 #define SERVERHAS64BIT(connp) (!((connp)->serverp->flags & CM_SERVERFLAG_NO64BIT))
37 #define SET_SERVERHASNO64BIT(connp) (cm_SetServerNo64Bit((connp)->serverp, TRUE))
38 #else
39 #define SERVERHAS64BIT(connp) (FALSE)
40 #define SET_SERVERHASNO64BIT(connp) (FALSE)
41 #endif
42
43 /* functions called back from the buffer package when reading or writing data,
44  * or when holding or releasing a vnode pointer.
45  */
46 long cm_BufWrite(void *vscp, osi_hyper_t *offsetp, long length, long flags,
47                  cm_user_t *userp, cm_req_t *reqp)
48 {
49     /* store the data back from this buffer; the buffer is locked and held,
50      * but the vnode involved isn't locked, yet.  It is held by its
51      * reference from the buffer, which won't change until the buffer is
52      * released by our caller.  Thus, we don't have to worry about holding
53      * bufp->scp.
54      */
55     long code, code1;
56     cm_scache_t *scp = vscp;
57     afs_int32 nbytes;
58 #ifdef AFS_LARGEFILES
59     afs_int32 save_nbytes;
60 #endif
61     long temp;
62     AFSFetchStatus outStatus;
63     AFSStoreStatus inStatus;
64     osi_hyper_t thyper;
65     AFSVolSync volSync;
66     AFSFid tfid;
67     struct rx_call *rxcallp;
68     struct rx_connection *rxconnp;
69     osi_queueData_t *qdp;
70     cm_buf_t *bufp;
71     afs_uint32 wbytes;
72     char *bufferp;
73     cm_conn_t *connp;
74     osi_hyper_t truncPos;
75     cm_bulkIO_t biod;           /* bulk IO descriptor */
76     int require_64bit_ops = 0;
77     int call_was_64bit = 0;
78
79     osi_assertx(userp != NULL, "null cm_user_t");
80     osi_assertx(scp != NULL, "null cm_scache_t");
81
82     memset(&volSync, 0, sizeof(volSync));
83
84     /* now, the buffer may or may not be filled with good data (buf_GetNew
85      * drops lots of locks, and may indeed return a properly initialized
86      * buffer, although more likely it will just return a new, empty, buffer.
87      */
88
89     lock_ObtainWrite(&scp->rw);
90     if (scp->flags & CM_SCACHEFLAG_DELETED) {
91         lock_ReleaseWrite(&scp->rw);
92         return CM_ERROR_NOSUCHFILE;
93     }
94
95     cm_AFSFidFromFid(&tfid, &scp->fid);
96
97     /* Serialize StoreData RPC's; for rationale see cm_scache.c */
98     (void) cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA_EXCL);
99
100     code = cm_SetupStoreBIOD(scp, offsetp, length, &biod, userp, reqp);
101     if (code) {
102         osi_Log1(afsd_logp, "cm_SetupStoreBIOD code %x", code);
103         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
104         lock_ReleaseWrite(&scp->rw);
105         return code;
106     }
107
108     if (biod.length == 0) {
109         osi_Log0(afsd_logp, "cm_SetupStoreBIOD length 0");
110         cm_ReleaseBIOD(&biod, 1, 0, 1); /* should be a NOOP */
111         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
112         lock_ReleaseWrite(&scp->rw);
113         return 0;
114     }
115
116     /* prepare the output status for the store */
117     scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
118     cm_StatusFromAttr(&inStatus, scp, NULL);
119     truncPos = scp->length;
120     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
121         && LargeIntegerLessThan(scp->truncPos, truncPos))
122         truncPos = scp->truncPos;
123         scp->mask &= ~CM_SCACHEMASK_TRUNCPOS;
124                 
125     /* compute how many bytes to write from this buffer */
126     thyper = LargeIntegerSubtract(scp->length, biod.offset);
127     if (LargeIntegerLessThanZero(thyper)) {
128         /* entire buffer is past EOF */
129         nbytes = 0;
130     }
131     else {
132         /* otherwise write out part of buffer before EOF, but not
133          * more than bufferSize bytes.
134          */
135         if (LargeIntegerGreaterThan(thyper,
136                                     ConvertLongToLargeInteger(biod.length))) {
137             nbytes = biod.length;
138         } else {
139             /* if thyper is less than or equal to biod.length, then we
140                can safely assume that the value fits in a long. */
141             nbytes = thyper.LowPart;
142         }
143     }
144
145     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
146                                                  ConvertLongToLargeInteger(nbytes)),
147                                  ConvertLongToLargeInteger(LONG_MAX)) ||
148          LargeIntegerGreaterThan(truncPos,
149                                  ConvertLongToLargeInteger(LONG_MAX))) {
150         require_64bit_ops = 1;
151     }
152         
153     lock_ReleaseWrite(&scp->rw);
154
155     /* now we're ready to do the store operation */
156 #ifdef AFS_LARGEFILES
157     save_nbytes = nbytes;
158 #endif
159     do {
160         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
161         if (code) 
162             continue;
163
164     retry:
165         rxconnp = cm_GetRxConn(connp);
166         rxcallp = rx_NewCall(rxconnp);
167         rx_PutConnection(rxconnp);
168
169 #ifdef AFS_LARGEFILES
170         if (SERVERHAS64BIT(connp)) {
171             call_was_64bit = 1;
172
173             osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData64 scp 0x%p, offset 0x%x:%08x, length 0x%x",
174                      scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
175
176             code = StartRXAFS_StoreData64(rxcallp, &tfid, &inStatus,
177                                           biod.offset.QuadPart,
178                                           nbytes,
179                                           truncPos.QuadPart);
180             if (code)
181                 osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData64 FAILURE, code 0x%x", code);
182             else
183                 osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData64 SUCCESS");
184         } else {
185             call_was_64bit = 0;
186
187             if (require_64bit_ops) {
188                 osi_Log0(afsd_logp, "Skipping StartRXAFS_StoreData.  The operation requires large file support in the server.");
189                 code = CM_ERROR_TOOBIG;
190             } else {
191                 osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData scp 0x%p, offset 0x%x:%08x, length 0x%x",
192                          scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
193
194                 code = StartRXAFS_StoreData(rxcallp, &tfid, &inStatus,
195                                             biod.offset.LowPart, nbytes, truncPos.LowPart);
196                 if (code)
197                     osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData FAILURE, code 0x%x", code);
198                 else
199                     osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData SUCCESS");
200             }
201         }
202 #else
203         osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData scp 0x%p, offset 0x%x:%08x, length 0x%x",
204                  scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
205
206         code = StartRXAFS_StoreData(rxcallp, &tfid, &inStatus,
207                                     biod.offset.LowPart, nbytes, truncPos.LowPart);
208         if (code)
209             osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData FAILURE, code 0x%x", code);
210         else
211             osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData SUCCESS");
212 #endif
213
214         if (code == 0) {
215             /* write the data from the the list of buffers */
216             qdp = NULL;
217             while(nbytes > 0) {
218                 afs_uint32 buf_offset;
219                 if (qdp == NULL) {
220                     qdp = biod.bufListEndp;
221                     buf_offset = offsetp->LowPart % cm_data.buf_blockSize;
222                 } else {
223                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
224                     buf_offset = 0;
225                 }
226                 osi_assertx(qdp != NULL, "null osi_queueData_t");
227                 bufp = osi_GetQData(qdp);
228                 bufferp = bufp->datap + buf_offset;
229                 wbytes = nbytes;
230                 if (wbytes > cm_data.buf_blockSize - buf_offset)
231                     wbytes = cm_data.buf_blockSize - buf_offset;
232
233                 /* write out wbytes of data from bufferp */
234                 temp = rx_Write(rxcallp, bufferp, wbytes);
235                 if (temp != wbytes) {
236                     osi_Log3(afsd_logp, "rx_Write failed bp 0x%p, %d != %d",bufp,temp,wbytes);
237                     code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
238                     break;
239                 } else {
240                     osi_Log2(afsd_logp, "rx_Write succeeded bp 0x%p, %d",bufp,temp);
241                 }       
242                 nbytes -= wbytes;
243             }   /* while more bytes to write */
244         }       /* if RPC started successfully */
245
246         if (code == 0) {
247             if (call_was_64bit) {
248                 code = EndRXAFS_StoreData64(rxcallp, &outStatus, &volSync);
249                 if (code)
250                     osi_Log2(afsd_logp, "EndRXAFS_StoreData64 FAILURE scp 0x%p code %lX", scp, code);
251                 else
252                     osi_Log0(afsd_logp, "EndRXAFS_StoreData64 SUCCESS");
253             } else {
254                 code = EndRXAFS_StoreData(rxcallp, &outStatus, &volSync);
255                 if (code)
256                     osi_Log2(afsd_logp, "EndRXAFS_StoreData FAILURE scp 0x%p code %lX",scp,code);
257                 else
258                     osi_Log0(afsd_logp, "EndRXAFS_StoreData SUCCESS");
259             }
260         }
261
262         code1 = rx_EndCall(rxcallp, code);
263
264 #ifdef AFS_LARGEFILES
265         if ((code == RXGEN_OPCODE || code1 == RXGEN_OPCODE) && SERVERHAS64BIT(connp)) {
266             SET_SERVERHASNO64BIT(connp);
267             qdp = NULL;
268             nbytes = save_nbytes;
269             goto retry;
270         }
271 #endif
272         /* Prefer StoreData error over rx_EndCall error */
273         if (code1 != 0)
274             code = code1;
275     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
276
277     code = cm_MapRPCError(code, reqp);
278
279     if (code)
280         osi_Log2(afsd_logp, "CALL StoreData FAILURE scp 0x%p, code 0x%x", scp, code);
281     else
282         osi_Log1(afsd_logp, "CALL StoreData SUCCESS scp 0x%p", scp);
283
284     /* now, clean up our state */
285     lock_ObtainWrite(&scp->rw);
286
287     cm_ReleaseBIOD(&biod, 1, code, 1);
288     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
289
290     if (code == 0) {
291         osi_hyper_t t;
292         /* now, here's something a little tricky: in AFS 3, a dirty
293          * length can't be directly stored, instead, a dirty chunk is
294          * stored that sets the file's size (by writing and by using
295          * the truncate-first option in the store call).
296          *
297          * At this point, we've just finished a store, and so the trunc
298          * pos field is clean.  If the file's size at the server is at
299          * least as big as we think it should be, then we turn off the
300          * length dirty bit, since all the other dirty buffers must
301          * precede this one in the file.
302          *
303          * The file's desired size shouldn't be smaller than what's
304          * stored at the server now, since we just did the trunc pos
305          * store.
306          *
307          * We have to turn off the length dirty bit as soon as we can,
308          * so that we see updates made by other machines.
309          */
310
311         if (call_was_64bit) {
312             t.LowPart = outStatus.Length;
313             t.HighPart = outStatus.Length_hi;
314         } else {
315             t = ConvertLongToLargeInteger(outStatus.Length);
316         }
317
318         if (LargeIntegerGreaterThanOrEqualTo(t, scp->length))
319             scp->mask &= ~CM_SCACHEMASK_LENGTH;
320
321         cm_MergeStatus(NULL, scp, &outStatus, &volSync, userp, reqp, CM_MERGEFLAG_STOREDATA);
322     } else {
323         if (code == CM_ERROR_SPACE)
324             scp->flags |= CM_SCACHEFLAG_OUTOFSPACE;
325         else if (code == CM_ERROR_QUOTA)
326             scp->flags |= CM_SCACHEFLAG_OVERQUOTA;
327     }
328     lock_ReleaseWrite(&scp->rw);
329
330     return code;
331 }
332
333 /*
334  * Truncate the file, by sending a StoreData RPC with zero length.
335  *
336  * Called with scp locked.  Releases and re-obtains the lock.
337  */
338 long cm_StoreMini(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
339 {
340     AFSFetchStatus outStatus;
341     AFSStoreStatus inStatus;
342     AFSVolSync volSync;
343     AFSFid tfid;
344     long code, code1;
345     osi_hyper_t truncPos;
346     cm_conn_t *connp;
347     struct rx_call *rxcallp;
348     struct rx_connection *rxconnp;
349     int require_64bit_ops = 0;
350     int call_was_64bit = 0;
351
352     memset(&volSync, 0, sizeof(volSync));
353
354     /* Serialize StoreData RPC's; for rationale see cm_scache.c */
355     (void) cm_SyncOp(scp, NULL, userp, reqp, 0,
356                      CM_SCACHESYNC_STOREDATA_EXCL);
357
358     /* prepare the output status for the store */
359     inStatus.Mask = AFS_SETMODTIME;
360     inStatus.ClientModTime = scp->clientModTime;
361     scp->mask &= ~CM_SCACHEMASK_CLIENTMODTIME;
362
363     /* calculate truncation position */
364     truncPos = scp->length;
365     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
366         && LargeIntegerLessThan(scp->truncPos, truncPos))
367         truncPos = scp->truncPos;
368     scp->mask &= ~CM_SCACHEMASK_TRUNCPOS;
369
370     if (LargeIntegerGreaterThan(truncPos,
371                                 ConvertLongToLargeInteger(LONG_MAX))) {
372
373         require_64bit_ops = 1;
374     }
375
376     lock_ReleaseWrite(&scp->rw);
377
378     cm_AFSFidFromFid(&tfid, &scp->fid);
379
380     /* now we're ready to do the store operation */
381     do {
382         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
383         if (code) 
384             continue;
385
386     retry:      
387         rxconnp = cm_GetRxConn(connp);
388         rxcallp = rx_NewCall(rxconnp);
389         rx_PutConnection(rxconnp);
390
391 #ifdef AFS_LARGEFILES
392         if (SERVERHAS64BIT(connp)) {
393             call_was_64bit = 1;
394
395             code = StartRXAFS_StoreData64(rxcallp, &tfid, &inStatus,
396                                           0, 0, truncPos.QuadPart);
397         } else {
398             call_was_64bit = 0;
399
400             if (require_64bit_ops) {
401                 code = CM_ERROR_TOOBIG;
402             } else {
403                 code = StartRXAFS_StoreData(rxcallp, &tfid, &inStatus,
404                                             0, 0, truncPos.LowPart);
405             }
406         }
407 #else
408         code = StartRXAFS_StoreData(rxcallp, &tfid, &inStatus,
409                                     0, 0, truncPos.LowPart);
410 #endif
411
412         if (code == 0) {
413             if (call_was_64bit)
414                 code = EndRXAFS_StoreData64(rxcallp, &outStatus, &volSync);
415             else
416                 code = EndRXAFS_StoreData(rxcallp, &outStatus, &volSync);
417         }
418         code1 = rx_EndCall(rxcallp, code);
419
420 #ifdef AFS_LARGEFILES
421         if ((code == RXGEN_OPCODE || code1 == RXGEN_OPCODE) && SERVERHAS64BIT(connp)) {
422             SET_SERVERHASNO64BIT(connp);
423             goto retry;
424         }
425 #endif
426         /* prefer StoreData error over rx_EndCall error */
427         if (code == 0 && code1 != 0)
428             code = code1;
429     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
430     code = cm_MapRPCError(code, reqp);
431         
432     /* now, clean up our state */
433     lock_ObtainWrite(&scp->rw);
434
435     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
436
437     if (code == 0) {
438         osi_hyper_t t;
439         /*
440          * For explanation of handling of CM_SCACHEMASK_LENGTH,
441          * see cm_BufWrite().
442          */
443         if (call_was_64bit) {
444             t.HighPart = outStatus.Length_hi;
445             t.LowPart = outStatus.Length;
446         } else {
447             t = ConvertLongToLargeInteger(outStatus.Length);
448         }
449
450         if (LargeIntegerGreaterThanOrEqualTo(t, scp->length))
451             scp->mask &= ~CM_SCACHEMASK_LENGTH;
452         cm_MergeStatus(NULL, scp, &outStatus, &volSync, userp, reqp, CM_MERGEFLAG_STOREDATA);
453     }
454
455     return code;
456 }
457
458 long cm_BufRead(cm_buf_t *bufp, long nbytes, long *bytesReadp, cm_user_t *userp)
459 {
460     *bytesReadp = 0;
461
462     /* now return a code that means that I/O is done */
463     return 0;
464 }
465
466 /* stabilize scache entry, and return with it locked so 
467  * it stays stable.
468  */
469 long cm_BufStabilize(void *vscp, cm_user_t *userp, cm_req_t *reqp)
470 {
471     cm_scache_t *scp = vscp;
472     long code;
473
474     lock_ObtainWrite(&scp->rw);
475     code = cm_SyncOp(scp, NULL, userp, reqp, 0, 
476                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
477     if (code) {
478         lock_ReleaseWrite(&scp->rw);
479         return code;
480     }
481         
482     return 0;
483 }
484
485 /* undoes the work that cm_BufStabilize does: releases lock so things can change again */
486 long cm_BufUnstabilize(void *vscp, cm_user_t *userp)
487 {
488     cm_scache_t *scp = vscp;
489         
490     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
491
492     lock_ReleaseWrite(&scp->rw);
493         
494     /* always succeeds */
495     return 0;
496 }
497
498 cm_buf_ops_t cm_bufOps = {
499     cm_BufWrite,
500     cm_BufRead,
501     cm_BufStabilize,
502     cm_BufUnstabilize
503 };
504
505 long cm_ValidateDCache(void)
506 {
507     return buf_ValidateBuffers();
508 }
509
510 long cm_ShutdownDCache(void)
511 {
512     return 0;
513 }
514
515 int cm_InitDCache(int newFile, long chunkSize, afs_uint64 nbuffers)
516 {
517     return buf_Init(newFile, &cm_bufOps, nbuffers);
518 }
519
520 /* check to see if we have an up-to-date buffer.  The buffer must have
521  * previously been obtained by calling buf_Get.
522  *
523  * Make sure we have a callback, and that the dataversion matches.
524  *
525  * Scp must be locked.
526  *
527  * Bufp *may* be locked.
528  */
529 int cm_HaveBuffer(cm_scache_t *scp, cm_buf_t *bufp, int isBufLocked)
530 {
531     int code;
532     if (!cm_HaveCallback(scp))
533         return 0;
534     if ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED))
535         return 1;
536     if (bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow)
537         return 1;
538     if (bufp->offset.QuadPart >= scp->serverLength.QuadPart)
539         return 1;
540     if (!isBufLocked) {
541         code = lock_TryMutex(&bufp->mx);
542         if (code == 0) {
543             /* don't have the lock, and can't lock it, then
544              * return failure.
545              */
546             return 0;
547         }
548     }
549
550     /* remember dirty flag for later */
551     code = bufp->flags & CM_BUF_DIRTY;
552
553     /* release lock if we obtained it here */
554     if (!isBufLocked) 
555         lock_ReleaseMutex(&bufp->mx);
556
557     /* if buffer was dirty, buffer is acceptable for use */
558     if (code) 
559         return 1;
560     else 
561         return 0;
562 }
563
564 /*
565  * used when deciding whether to do a background fetch or not.
566  * call with scp->rw write-locked.
567  */
568 afs_int32
569 cm_CheckFetchRange(cm_scache_t *scp, osi_hyper_t *startBasep, osi_hyper_t *length,
570                         cm_user_t *userp, cm_req_t *reqp, osi_hyper_t *realBasep)
571 {
572     osi_hyper_t tbase;
573     osi_hyper_t tlength;
574     osi_hyper_t tblocksize;
575     long code;
576     cm_buf_t *bp;
577     int stop;
578         
579     /* now scan all buffers in the range, looking for any that look like
580      * they need work.
581      */
582     tbase = *startBasep;
583     tlength = *length;
584     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
585     stop = 0;
586     while (LargeIntegerGreaterThanZero(tlength)) {
587         /* get callback so we can do a meaningful dataVersion comparison */
588         code = cm_SyncOp(scp, NULL, userp, reqp, 0,
589                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
590         if (code)
591             return code;
592                 
593         if (LargeIntegerGreaterThanOrEqualTo(tbase, scp->length)) {
594             /* we're past the end of file */
595             break;
596         }
597
598         bp = buf_Find(scp, &tbase);
599         /* We cheat slightly by not locking the bp mutex. */
600         if (bp) {
601             if ((bp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING | CM_BUF_CMBKGFETCH)) == 0
602                  && (bp->dataVersion < scp->bufDataVersionLow || bp->dataVersion > scp->dataVersion))
603                 stop = 1;
604             buf_Release(bp);
605             bp = NULL;
606         }
607         else 
608             stop = 1;
609
610         /* if this buffer is essentially guaranteed to require a fetch,
611          * break out here and return this position.
612          */
613         if (stop) 
614             break;
615                 
616         tbase = LargeIntegerAdd(tbase, tblocksize);
617         tlength = LargeIntegerSubtract(tlength,  tblocksize);
618     }
619         
620     /* if we get here, either everything is fine or 'stop' stopped us at a
621      * particular buffer in the range that definitely needs to be fetched.
622      */
623     if (stop == 0) {
624         /* return non-zero code since realBasep won't be valid */
625         code = -1;
626     }   
627     else {
628         /* successfully found a page that will need fetching */
629         *realBasep = tbase;
630         code = 0;
631     }
632     return code;
633 }
634
635 afs_int32
636 cm_BkgStore(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
637             cm_user_t *userp)
638 {
639     osi_hyper_t toffset;
640     long length;
641     cm_req_t req;
642     long code = 0;
643
644     if (scp->flags & CM_SCACHEFLAG_DELETED) {
645         osi_Log4(afsd_logp, "Skipping BKG store - Deleted scp 0x%p, offset 0x%x:%08x, length 0x%x", scp, p2, p1, p3);
646     } else {
647         cm_InitReq(&req);
648
649         /* Retries will be performed by the BkgDaemon thread if appropriate */
650         req.flags |= CM_REQ_NORETRY;
651
652         toffset.LowPart = p1;
653         toffset.HighPart = p2;
654         length = p3;
655
656         osi_Log4(afsd_logp, "Starting BKG store scp 0x%p, offset 0x%x:%08x, length 0x%x", scp, p2, p1, p3);
657
658         code = cm_BufWrite(scp, &toffset, length, /* flags */ 0, userp, &req);
659
660         osi_Log4(afsd_logp, "Finished BKG store scp 0x%p, offset 0x%x:%08x, code 0x%x", scp, p2, p1, code);
661     }
662
663     /* 
664      * Keep the following list synchronized with the
665      * error code list in cm_BkgDaemon 
666      */
667     switch ( code ) {
668     case CM_ERROR_TIMEDOUT: /* or server restarting */
669     case CM_ERROR_RETRY:
670     case CM_ERROR_WOULDBLOCK:
671     case CM_ERROR_ALLBUSY:
672     case CM_ERROR_ALLDOWN:
673     case CM_ERROR_ALLOFFLINE:
674     case CM_ERROR_PARTIALWRITE:
675         break;  /* cm_BkgDaemon will re-insert the request in the queue */
676     case 0:
677     default:
678         lock_ObtainWrite(&scp->rw);
679         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_ASYNCSTORE);
680         lock_ReleaseWrite(&scp->rw);
681     }
682     return code;
683 }
684
685 /* Called with scp locked */
686 void cm_ClearPrefetchFlag(long code, cm_scache_t *scp, osi_hyper_t *base, osi_hyper_t *length)
687 {
688     osi_hyper_t end;
689
690     if (code == 0) {
691         end =  LargeIntegerAdd(*base, *length);
692         if (LargeIntegerGreaterThan(*base, scp->prefetch.base))
693             scp->prefetch.base = *base;
694         if (LargeIntegerGreaterThan(end, scp->prefetch.end))
695             scp->prefetch.end = end;
696     }
697     scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
698 }
699
700 /* do the prefetch.  if the prefetch fails, return 0 (success)
701  * because there is no harm done.  */
702 afs_int32
703 cm_BkgPrefetch(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
704                cm_user_t *userp)
705 {
706     osi_hyper_t length;
707     osi_hyper_t base;
708     osi_hyper_t offset;
709     osi_hyper_t end;
710     osi_hyper_t fetched;
711     osi_hyper_t tblocksize;
712     afs_int32 code;
713     int rxheld = 0;
714     cm_buf_t *bp = NULL;
715     cm_req_t req;
716
717     cm_InitReq(&req);
718
719     /* Retries will be performed by the BkgDaemon thread if appropriate */
720     req.flags |= CM_REQ_NORETRY;
721         
722     fetched.LowPart = 0;
723     fetched.HighPart = 0;
724     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
725     base.LowPart = p1;
726     base.HighPart = p2;
727     length.LowPart = p3;
728     length.HighPart = p4;
729
730     end = LargeIntegerAdd(base, length);
731         
732     osi_Log5(afsd_logp, "Starting BKG prefetch scp 0x%p offset 0x%x:%x length 0x%x:%x",
733              scp, p2, p1, p4, p3);
734
735     for ( code = 0, offset = base;
736           code == 0 && LargeIntegerLessThan(offset, end); 
737           offset = LargeIntegerAdd(offset, tblocksize) )
738     {
739         if (rxheld) {
740             lock_ReleaseWrite(&scp->rw);
741             rxheld = 0;
742         }
743
744         code = buf_Get(scp, &offset, &req, &bp);
745         if (code)
746             break;
747
748         if (bp->cmFlags & CM_BUF_CMFETCHING) {
749             /* skip this buffer as another thread is already fetching it */
750             if (!rxheld) {
751                 lock_ObtainWrite(&scp->rw);
752                 rxheld = 1;
753             }
754             bp->cmFlags &= ~CM_BUF_CMBKGFETCH;
755             buf_Release(bp);
756             bp = NULL;
757             continue;
758         }
759
760         if (!rxheld) {
761             lock_ObtainWrite(&scp->rw);
762             rxheld = 1;
763         }
764
765         code = cm_GetBuffer(scp, bp, NULL, userp, &req);
766         if (code == 0)
767             fetched = LargeIntegerAdd(fetched, tblocksize); 
768         buf_Release(bp);
769         bp->cmFlags &= ~CM_BUF_CMBKGFETCH;
770     }
771     
772     if (!rxheld) {
773         lock_ObtainWrite(&scp->rw);
774         rxheld = 1;
775     }
776
777     /* Clear flag from any remaining buffers */
778     for ( ;
779           LargeIntegerLessThan(offset, end);
780           offset = LargeIntegerAdd(offset, tblocksize) )
781     {
782         bp = buf_Find(scp, &offset);
783         if (bp) {
784             bp->cmFlags &= ~CM_BUF_CMBKGFETCH;
785             buf_Release(bp);
786         }
787     }
788     cm_ClearPrefetchFlag(LargeIntegerGreaterThanZero(fetched) ? 0 : code, 
789                          scp, &base, &fetched);
790
791     /* wakeup anyone who is waiting */
792     if (scp->flags & CM_SCACHEFLAG_WAITING) {
793         osi_Log1(afsd_logp, "CM BkgPrefetch Waking scp 0x%p", scp);
794         osi_Wakeup((LONG_PTR) &scp->flags);
795     }
796     lock_ReleaseWrite(&scp->rw);
797
798     osi_Log4(afsd_logp, "Ending BKG prefetch scp 0x%p code 0x%x fetched 0x%x:%x",
799              scp, code, fetched.HighPart, fetched.LowPart);
800     return code;
801 }
802
803 /* a read was issued to offsetp, and we have to determine whether we should
804  * do a prefetch of the next chunk.
805  */
806 void cm_ConsiderPrefetch(cm_scache_t *scp, osi_hyper_t *offsetp, afs_uint32 count,
807                          cm_user_t *userp, cm_req_t *reqp)
808 {
809     long code;
810     int  rwheld = 0;
811     osi_hyper_t realBase;
812     osi_hyper_t readBase;
813     osi_hyper_t readLength;
814     osi_hyper_t readEnd;
815     osi_hyper_t offset;
816     osi_hyper_t tblocksize;             /* a long long temp variable */
817     cm_buf_t    *bp;
818
819     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
820         
821     readBase = *offsetp;
822     /* round up to chunk boundary */
823     readBase.LowPart += (cm_chunkSize-1);
824     readBase.LowPart &= (-cm_chunkSize);
825
826     readLength = ConvertLongToLargeInteger(count);
827
828     lock_ObtainWrite(&scp->rw);
829     rwheld = 1;
830     if ((scp->flags & CM_SCACHEFLAG_PREFETCHING)
831          || LargeIntegerLessThanOrEqualTo(readBase, scp->prefetch.base)) {
832         lock_ReleaseWrite(&scp->rw);
833         return;
834     }
835     scp->flags |= CM_SCACHEFLAG_PREFETCHING;
836
837     /* start the scan at the latter of the end of this read or
838      * the end of the last fetched region.
839      */
840     if (LargeIntegerGreaterThan(scp->prefetch.end, readBase))
841         readBase = scp->prefetch.end;
842
843     code = cm_CheckFetchRange(scp, &readBase, &readLength, userp, reqp,
844                               &realBase);
845     if (code) {
846         scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
847         lock_ReleaseWrite(&scp->rw);
848         return; /* can't find something to prefetch */
849     }
850
851     readEnd = LargeIntegerAdd(realBase, readLength);
852
853     /*
854      * Mark each buffer in the range as queued for a
855      * background fetch
856      */
857     for ( offset = realBase;
858           LargeIntegerLessThan(offset, readEnd);
859           offset = LargeIntegerAdd(offset, tblocksize) )
860     {
861         if (rwheld) {
862             lock_ReleaseWrite(&scp->rw);
863             rwheld = 0;
864         }
865
866         bp = buf_Find(scp, &offset);
867         if (!bp)
868             continue;
869
870         if (!rwheld) {
871             lock_ObtainWrite(&scp->rw);
872             rwheld = 1;
873         }
874
875         bp->cmFlags |= CM_BUF_CMBKGFETCH;
876         buf_Release(bp);
877     }
878
879     if (rwheld)
880         lock_ReleaseWrite(&scp->rw);
881
882     osi_Log2(afsd_logp, "BKG Prefetch request scp 0x%p, base 0x%x",
883              scp, realBase.LowPart);
884
885     cm_QueueBKGRequest(scp, cm_BkgPrefetch, 
886                        realBase.LowPart, realBase.HighPart, 
887                        readLength.LowPart, readLength.HighPart, 
888                        userp);
889 }
890
891 /* scp must be locked; temporarily unlocked during processing.
892  * If returns 0, returns buffers held in biop, and with
893  * CM_BUF_CMSTORING set.
894  *
895  * Caller *must* set CM_BUF_WRITING and reset the over.hEvent field if the
896  * buffer is ever unlocked before CM_BUF_DIRTY is cleared.  And if
897  * CM_BUF_WRITING is ever viewed by anyone, then it must be cleared, sleepers
898  * must be woken, and the event must be set when the I/O is done.  All of this
899  * is required so that buf_WaitIO synchronizes properly with the buffer as it
900  * is being written out.
901  */
902 long cm_SetupStoreBIOD(cm_scache_t *scp, osi_hyper_t *inOffsetp, long inSize,
903                        cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
904 {
905     cm_buf_t *bufp;
906     osi_queueData_t *qdp;
907     osi_hyper_t thyper;
908     osi_hyper_t tbase;
909     osi_hyper_t scanStart;              /* where to start scan for dirty pages */
910     osi_hyper_t scanEnd;                /* where to stop scan for dirty pages */
911     osi_hyper_t firstModOffset; /* offset of first modified page in range */
912     long temp;
913     long code;
914     long flags;                 /* flags to cm_SyncOp */
915         
916     /* clear things out */
917     biop->scp = scp;                    /* do not hold; held by caller */
918     biop->offset = *inOffsetp;
919     biop->length = 0;
920     biop->bufListp = NULL;
921     biop->bufListEndp = NULL;
922     biop->reserved = 0;
923
924     /* reserve a chunk's worth of buffers */
925     lock_ReleaseWrite(&scp->rw);
926     buf_ReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
927     lock_ObtainWrite(&scp->rw);
928
929     bufp = NULL;
930     for (temp = 0; temp < inSize; temp += cm_data.buf_blockSize) {
931         thyper = ConvertLongToLargeInteger(temp);
932         tbase = LargeIntegerAdd(*inOffsetp, thyper);
933
934         bufp = buf_Find(scp, &tbase);
935         if (bufp) {
936             /* get buffer mutex and scp mutex safely */
937             lock_ReleaseWrite(&scp->rw);
938             lock_ObtainMutex(&bufp->mx);
939             lock_ObtainWrite(&scp->rw);
940
941             flags = CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_STOREDATA | CM_SCACHESYNC_BUFLOCKED;
942             code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags); 
943             if (code) {
944                 lock_ReleaseMutex(&bufp->mx);
945                 buf_Release(bufp);
946                 bufp = NULL;
947                 buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
948                 return code;
949             }   
950                         
951             /* if the buffer is dirty, we're done */
952             if (bufp->flags & CM_BUF_DIRTY) {
953                 osi_assertx(!(bufp->flags & CM_BUF_WRITING),
954                             "WRITING w/o CMSTORING in SetupStoreBIOD");
955                 bufp->flags |= CM_BUF_WRITING;
956                 break;
957             }
958
959             /* this buffer is clean, so there's no reason to process it */
960             cm_SyncOpDone(scp, bufp, flags);
961             lock_ReleaseMutex(&bufp->mx);
962             buf_Release(bufp);
963             bufp = NULL;
964         }       
965     }
966
967     biop->reserved = 1;
968         
969     /* if we get here, if bufp is null, we didn't find any dirty buffers
970      * that weren't already being stored back, so we just quit now.
971      */
972     if (!bufp) {
973         return 0;
974     }
975
976     /* don't need buffer mutex any more */
977     lock_ReleaseMutex(&bufp->mx);
978         
979     /* put this element in the list */
980     qdp = osi_QDAlloc();
981     osi_SetQData(qdp, bufp);
982     /* don't have to hold bufp, since held by buf_Find above */
983     osi_QAddH((osi_queue_t **) &biop->bufListp,
984               (osi_queue_t **) &biop->bufListEndp,
985               &qdp->q);
986     biop->length = cm_data.buf_blockSize;
987     firstModOffset = bufp->offset;
988     biop->offset = firstModOffset;
989     bufp = NULL;        /* this buffer and reference added to the queue */
990
991     /* compute the window surrounding *inOffsetp of size cm_chunkSize */
992     scanStart = *inOffsetp;
993     scanStart.LowPart &= (-cm_chunkSize);
994     thyper = ConvertLongToLargeInteger(cm_chunkSize);
995     scanEnd = LargeIntegerAdd(scanStart, thyper);
996
997     flags = CM_SCACHESYNC_GETSTATUS
998         | CM_SCACHESYNC_STOREDATA
999         | CM_SCACHESYNC_BUFLOCKED
1000         | CM_SCACHESYNC_NOWAIT;
1001
1002     /* start by looking backwards until scanStart */
1003     /* hyper version of cm_data.buf_blockSize */
1004     thyper = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1005     tbase = LargeIntegerSubtract(firstModOffset, thyper);
1006     while(LargeIntegerGreaterThanOrEqualTo(tbase, scanStart)) {
1007         /* see if we can find the buffer */
1008         bufp = buf_Find(scp, &tbase);
1009         if (!bufp) 
1010             break;
1011
1012         /* try to lock it, and quit if we can't (simplifies locking) */
1013         lock_ReleaseWrite(&scp->rw);
1014         code = lock_TryMutex(&bufp->mx);
1015         lock_ObtainWrite(&scp->rw);
1016         if (code == 0) {
1017             buf_Release(bufp);
1018             bufp = NULL;
1019             break;
1020         }
1021                 
1022         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1023         if (code) {
1024             lock_ReleaseMutex(&bufp->mx);
1025             buf_Release(bufp);
1026             bufp = NULL;
1027             break;
1028         }
1029                 
1030         if (!(bufp->flags & CM_BUF_DIRTY)) {
1031             /* buffer is clean, so we shouldn't add it */
1032             cm_SyncOpDone(scp, bufp, flags);
1033             lock_ReleaseMutex(&bufp->mx);
1034             buf_Release(bufp);
1035             bufp = NULL;
1036             break;
1037         }
1038
1039         /* don't need buffer mutex any more */
1040         lock_ReleaseMutex(&bufp->mx);
1041
1042         /* we have a dirty buffer ready for storing.  Add it to the tail
1043          * of the list, since it immediately precedes all of the disk
1044          * addresses we've already collected.
1045          */
1046         qdp = osi_QDAlloc();
1047         osi_SetQData(qdp, bufp);
1048         /* no buf_hold necessary, since we have it held from buf_Find */
1049         osi_QAddT((osi_queue_t **) &biop->bufListp,
1050                   (osi_queue_t **) &biop->bufListEndp,
1051                   &qdp->q);
1052         bufp = NULL;            /* added to the queue */
1053
1054         /* update biod info describing the transfer */
1055         biop->offset = LargeIntegerSubtract(biop->offset, thyper);
1056         biop->length += cm_data.buf_blockSize;
1057
1058         /* update loop pointer */
1059         tbase = LargeIntegerSubtract(tbase, thyper);
1060     }   /* while loop looking for pages preceding the one we found */
1061
1062     /* now, find later dirty, contiguous pages, and add them to the list */
1063     /* hyper version of cm_data.buf_blockSize */
1064     thyper = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1065     tbase = LargeIntegerAdd(firstModOffset, thyper);
1066     while(LargeIntegerLessThan(tbase, scanEnd)) {
1067         /* see if we can find the buffer */
1068         bufp = buf_Find(scp, &tbase);
1069         if (!bufp) 
1070             break;
1071
1072         /* try to lock it, and quit if we can't (simplifies locking) */
1073         lock_ReleaseWrite(&scp->rw);
1074         code = lock_TryMutex(&bufp->mx);
1075         lock_ObtainWrite(&scp->rw);
1076         if (code == 0) {
1077             buf_Release(bufp);
1078             bufp = NULL;
1079             break;
1080         }
1081
1082         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1083         if (code) {
1084             lock_ReleaseMutex(&bufp->mx);
1085             buf_Release(bufp);
1086             bufp = NULL;
1087             break;
1088         }
1089                 
1090         if (!(bufp->flags & CM_BUF_DIRTY)) {
1091             /* buffer is clean, so we shouldn't add it */
1092             cm_SyncOpDone(scp, bufp, flags);
1093             lock_ReleaseMutex(&bufp->mx);
1094             buf_Release(bufp);
1095             bufp = NULL;
1096             break;
1097         }
1098
1099         /* don't need buffer mutex any more */
1100         lock_ReleaseMutex(&bufp->mx);
1101
1102         /* we have a dirty buffer ready for storing.  Add it to the head
1103          * of the list, since it immediately follows all of the disk
1104          * addresses we've already collected.
1105          */
1106         qdp = osi_QDAlloc();
1107         osi_SetQData(qdp, bufp);
1108         /* no buf_hold necessary, since we have it held from buf_Find */
1109         osi_QAddH((osi_queue_t **) &biop->bufListp,
1110                   (osi_queue_t **) &biop->bufListEndp,
1111                   &qdp->q);
1112         bufp = NULL;
1113
1114         /* update biod info describing the transfer */
1115         biop->length += cm_data.buf_blockSize;
1116                 
1117         /* update loop pointer */
1118         tbase = LargeIntegerAdd(tbase, thyper);
1119     }   /* while loop looking for pages following the first page we found */
1120         
1121     /* finally, we're done */
1122     return 0;
1123 }
1124
1125 /* scp must be locked; temporarily unlocked during processing.
1126  * If returns 0, returns buffers held in biop, and with
1127  * CM_BUF_CMFETCHING flags set.
1128  * If an error is returned, we don't return any buffers.
1129  */
1130 long cm_SetupFetchBIOD(cm_scache_t *scp, osi_hyper_t *offsetp,
1131                         cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
1132 {
1133     long code;
1134     cm_buf_t *tbp;
1135     osi_hyper_t tblocksize;             /* a long long temp variable */
1136     osi_hyper_t pageBase;               /* base offset we're looking at */
1137     osi_queueData_t *qdp;               /* one temp queue structure */
1138     osi_queueData_t *tqdp;              /* another temp queue structure */
1139     long collected;                     /* how many bytes have been collected */
1140     int isFirst;
1141     long flags;
1142     osi_hyper_t fileSize;               /* the # of bytes in the file */
1143     osi_queueData_t *heldBufListp;      /* we hold all buffers in this list */
1144     osi_queueData_t *heldBufListEndp;   /* first one */
1145     int reserving;
1146
1147     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1148
1149     biop->scp = scp;                    /* do not hold; held by caller */
1150     biop->offset = *offsetp;
1151     /* null out the list of buffers */
1152     biop->bufListp = biop->bufListEndp = NULL;
1153     biop->reserved = 0;
1154
1155     /* first lookup the file's length, so we know when to stop */
1156     code = cm_SyncOp(scp, NULL, userp, reqp, 0, 
1157                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1158     if (code) 
1159         return code;
1160         
1161     /* copy out size, since it may change */
1162     fileSize = scp->serverLength;
1163         
1164     lock_ReleaseWrite(&scp->rw);
1165
1166     pageBase = *offsetp;
1167     collected = pageBase.LowPart & (cm_chunkSize - 1);
1168     heldBufListp = NULL;
1169     heldBufListEndp = NULL;
1170
1171     /*
1172      * Obtaining buffers can cause dirty buffers to be recycled, which
1173      * can cause a storeback, so cannot be done while we have buffers
1174      * reserved.
1175      *
1176      * To get around this, we get buffers twice.  Before reserving buffers,
1177      * we obtain and release each one individually.  After reserving
1178      * buffers, we try to obtain them again, but only by lookup, not by
1179      * recycling.  If a buffer has gone away while we were waiting for
1180      * the others, we just use whatever buffers we already have.
1181      *
1182      * On entry to this function, we are already holding a buffer, so we
1183      * can't wait for reservation.  So we call buf_TryReserveBuffers()
1184      * instead.  Not only that, we can't really even call buf_Get(), for
1185      * the same reason.  We can't avoid that, though.  To avoid deadlock
1186      * we allow only one thread to be executing the buf_Get()-buf_Release()
1187      * sequence at a time.
1188      */
1189
1190     /* first hold all buffers, since we can't hold any locks in buf_Get */
1191     while (1) {
1192         /* stop at chunk boundary */
1193         if (collected >= cm_chunkSize) 
1194             break;
1195                 
1196         /* see if the next page would be past EOF */
1197         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize)) 
1198             break;
1199
1200         code = buf_Get(scp, &pageBase, reqp, &tbp);
1201         if (code) {
1202             lock_ObtainWrite(&scp->rw);
1203             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1204             return code;
1205         }
1206                 
1207         buf_Release(tbp);
1208         tbp = NULL;
1209
1210         pageBase = LargeIntegerAdd(tblocksize, pageBase);
1211         collected += cm_data.buf_blockSize;
1212     }
1213
1214     /* reserve a chunk's worth of buffers if possible */
1215     reserving = buf_TryReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1216
1217     pageBase = *offsetp;
1218     collected = pageBase.LowPart & (cm_chunkSize - 1);
1219
1220     /* now hold all buffers, if they are still there */
1221     while (1) {
1222         /* stop at chunk boundary */
1223         if (collected >= cm_chunkSize) 
1224             break;
1225                 
1226         /* see if the next page would be past EOF */
1227         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize)) 
1228             break;
1229
1230         tbp = buf_Find(scp, &pageBase);
1231         if (!tbp) 
1232             break;
1233
1234         /* add the buffer to the list */
1235         qdp = osi_QDAlloc();
1236         osi_SetQData(qdp, tbp);
1237         osi_QAddH((osi_queue_t **)&heldBufListp, 
1238                   (osi_queue_t **)&heldBufListEndp, 
1239                   &qdp->q);
1240         /* leave tbp held (from buf_Get) */
1241
1242         if (!reserving) 
1243             break;
1244
1245         collected += cm_data.buf_blockSize;
1246         pageBase = LargeIntegerAdd(tblocksize, pageBase);
1247     }
1248
1249     /* look at each buffer, adding it into the list if it looks idle and
1250      * filled with old data.  One special case: wait for idle if it is the
1251      * first buffer since we really need that one for our caller to make
1252      * any progress.
1253      */
1254     isFirst = 1;
1255     collected = 0;              /* now count how many we'll really use */
1256     for (tqdp = heldBufListEndp;
1257         tqdp;
1258           tqdp = (osi_queueData_t *) osi_QPrev(&tqdp->q)) {
1259         /* get a ptr to the held buffer */
1260         tbp = osi_GetQData(tqdp);
1261         pageBase = tbp->offset;
1262
1263         /* now lock the buffer lock */
1264         lock_ObtainMutex(&tbp->mx);
1265         lock_ObtainWrite(&scp->rw);
1266
1267         /* don't bother fetching over data that is already current */
1268         if (tbp->dataVersion <= scp->dataVersion && tbp->dataVersion >= scp->bufDataVersionLow) {
1269             /* we don't need this buffer, since it is current */
1270             lock_ReleaseWrite(&scp->rw);
1271             lock_ReleaseMutex(&tbp->mx);
1272             break;
1273         }
1274
1275         flags = CM_SCACHESYNC_FETCHDATA | CM_SCACHESYNC_BUFLOCKED;
1276         if (!isFirst) 
1277             flags |= CM_SCACHESYNC_NOWAIT;
1278
1279         /* wait for the buffer to serialize, if required.  Doesn't
1280          * release the scp or buffer lock(s) if NOWAIT is specified.
1281          */
1282         code = cm_SyncOp(scp, tbp, userp, reqp, 0, flags);
1283         if (code) {
1284             lock_ReleaseWrite(&scp->rw);
1285             lock_ReleaseMutex(&tbp->mx);
1286             break;
1287         }
1288                 
1289         /* don't fetch over dirty buffers */
1290         if (tbp->flags & CM_BUF_DIRTY) {
1291             cm_SyncOpDone(scp, tbp, flags);
1292             lock_ReleaseWrite(&scp->rw);
1293             lock_ReleaseMutex(&tbp->mx);
1294             break;
1295         }
1296
1297         /* Release locks */
1298         lock_ReleaseWrite(&scp->rw);
1299         lock_ReleaseMutex(&tbp->mx);
1300
1301         /* add the buffer to the list */
1302         qdp = osi_QDAlloc();
1303         osi_SetQData(qdp, tbp);
1304         osi_QAddH((osi_queue_t **)&biop->bufListp, 
1305                   (osi_queue_t **)&biop->bufListEndp, 
1306                   &qdp->q);
1307         buf_Hold(tbp);
1308
1309         /* from now on, a failure just stops our collection process, but
1310          * we still do the I/O to whatever we've already managed to collect.
1311          */
1312         isFirst = 0;
1313         collected += cm_data.buf_blockSize;
1314     }
1315         
1316     /* now, we've held in biop->bufListp all the buffer's we're really
1317      * interested in.  We also have holds left from heldBufListp, and we
1318      * now release those holds on the buffers.
1319      */
1320     for (qdp = heldBufListp; qdp; qdp = tqdp) {
1321         tqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1322         tbp = osi_GetQData(qdp);
1323         osi_QRemoveHT((osi_queue_t **) &heldBufListp,
1324                       (osi_queue_t **) &heldBufListEndp,
1325                       &qdp->q);
1326         osi_QDFree(qdp);
1327         buf_Release(tbp);
1328         tbp = NULL;
1329     }
1330
1331     /* Caller expects this */
1332     lock_ObtainWrite(&scp->rw);
1333  
1334     /* if we got a failure setting up the first buffer, then we don't have
1335      * any side effects yet, and we also have failed an operation that the
1336      * caller requires to make any progress.  Give up now.
1337      */
1338     if (code && isFirst) {
1339         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1340         return code;
1341     }
1342         
1343     /* otherwise, we're still OK, and should just return the I/O setup we've
1344      * got.
1345      */
1346     biop->length = collected;
1347     biop->reserved = reserving;
1348     return 0;
1349 }
1350
1351 /* release a bulk I/O structure that was setup by cm_SetupFetchBIOD or by
1352  * cm_SetupStoreBIOD
1353  */
1354 void cm_ReleaseBIOD(cm_bulkIO_t *biop, int isStore, long code, int scp_locked)
1355 {
1356     cm_scache_t *scp;           /* do not release; not held in biop */
1357     cm_buf_t *bufp;
1358     osi_queueData_t *qdp;
1359     osi_queueData_t *nqdp;
1360     int flags;
1361
1362     /* Give back reserved buffers */
1363     if (biop->reserved)
1364         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1365         
1366     if (isStore)
1367         flags = CM_SCACHESYNC_STOREDATA;
1368     else
1369         flags = CM_SCACHESYNC_FETCHDATA;
1370
1371     scp = biop->scp;
1372     if (biop->bufListp) {
1373         for(qdp = biop->bufListp; qdp; qdp = nqdp) {
1374             /* lookup next guy first, since we're going to free this one */
1375             nqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1376                 
1377             /* extract buffer and free queue data */
1378             bufp = osi_GetQData(qdp);
1379             osi_QRemoveHT((osi_queue_t **) &biop->bufListp,
1380                            (osi_queue_t **) &biop->bufListEndp,
1381                            &qdp->q);
1382             osi_QDFree(qdp);
1383
1384             /* now, mark I/O as done, unlock the buffer and release it */
1385             if (scp_locked)
1386                 lock_ReleaseWrite(&scp->rw);
1387             lock_ObtainMutex(&bufp->mx);
1388             lock_ObtainWrite(&scp->rw);
1389             cm_SyncOpDone(scp, bufp, flags);
1390                 
1391             /* turn off writing and wakeup users */
1392             if (isStore) {
1393                 if (bufp->flags & CM_BUF_WAITING) {
1394                     osi_Log2(afsd_logp, "cm_ReleaseBIOD Waking [scp 0x%p] bp 0x%p", scp, bufp);
1395                     osi_Wakeup((LONG_PTR) bufp);
1396                 }
1397                 if (code) {
1398                     bufp->flags &= ~CM_BUF_WRITING;
1399                     switch (code) {
1400                     case CM_ERROR_NOSUCHFILE:
1401                     case CM_ERROR_BADFD:
1402                     case CM_ERROR_NOACCESS:
1403                     case CM_ERROR_QUOTA:
1404                     case CM_ERROR_SPACE:
1405                     case CM_ERROR_TOOBIG:
1406                     case CM_ERROR_READONLY:
1407                     case CM_ERROR_NOSUCHPATH:
1408                         /*
1409                          * Apply the fatal error to this buffer.
1410                          */
1411                         bufp->flags &= ~CM_BUF_DIRTY;
1412                         bufp->flags |= CM_BUF_ERROR;
1413                         bufp->dirty_offset = 0;
1414                         bufp->dirty_length = 0;
1415                         bufp->error = code;
1416                         bufp->dataVersion = CM_BUF_VERSION_BAD;
1417                         bufp->dirtyCounter++;
1418                         break;
1419                     case CM_ERROR_TIMEDOUT:
1420                     case CM_ERROR_ALLDOWN:
1421                     case CM_ERROR_ALLBUSY:
1422                     case CM_ERROR_ALLOFFLINE:
1423                     case CM_ERROR_CLOCKSKEW:
1424                     default:
1425                         /* do not mark the buffer in error state but do
1426                         * not attempt to complete the rest either.
1427                         */
1428                         break;
1429                     }
1430                 } else {
1431                     bufp->flags &= ~(CM_BUF_WRITING | CM_BUF_DIRTY);
1432                     bufp->dirty_offset = bufp->dirty_length = 0;
1433                 }
1434             }
1435
1436             if (!scp_locked)
1437                 lock_ReleaseWrite(&scp->rw);
1438             lock_ReleaseMutex(&bufp->mx);
1439             buf_Release(bufp);
1440             bufp = NULL;
1441         }
1442     } else {
1443         if (!scp_locked)
1444             lock_ObtainWrite(&scp->rw);
1445         cm_SyncOpDone(scp, NULL, flags);
1446         if (!scp_locked)
1447             lock_ReleaseWrite(&scp->rw);
1448     }
1449
1450     /* clean things out */
1451     biop->bufListp = NULL;
1452     biop->bufListEndp = NULL;
1453 }   
1454
1455 static int
1456 cm_CloneStatus(cm_scache_t *scp, cm_user_t *userp, int scp_locked,
1457                AFSFetchStatus *afsStatusp, AFSVolSync *volSyncp)
1458 {
1459     // setup the status based upon the scp data
1460     afsStatusp->InterfaceVersion = 0x1;
1461     switch (scp->fileType) {
1462     case CM_SCACHETYPE_FILE:
1463         afsStatusp->FileType = File;
1464         break;
1465     case CM_SCACHETYPE_DIRECTORY:
1466         afsStatusp->FileType = Directory;
1467         break;
1468     case CM_SCACHETYPE_MOUNTPOINT:
1469         afsStatusp->FileType = SymbolicLink;
1470         break;
1471     case CM_SCACHETYPE_SYMLINK:
1472     case CM_SCACHETYPE_DFSLINK:
1473         afsStatusp->FileType = SymbolicLink;
1474         break;
1475     default:
1476         afsStatusp->FileType = -1;    /* an invalid value */
1477     }
1478     afsStatusp->LinkCount = scp->linkCount;
1479     afsStatusp->Length = scp->length.LowPart;
1480     afsStatusp->DataVersion = (afs_uint32)(scp->dataVersion & MAX_AFS_UINT32);
1481     afsStatusp->Author = 0x1;
1482     afsStatusp->Owner = scp->owner;
1483     if (!scp_locked) {
1484         lock_ObtainWrite(&scp->rw);
1485         scp_locked = 1;
1486     }
1487     if (cm_FindACLCache(scp, userp, &afsStatusp->CallerAccess))
1488         afsStatusp->CallerAccess = scp->anyAccess;
1489     afsStatusp->AnonymousAccess = scp->anyAccess;
1490     afsStatusp->UnixModeBits = scp->unixModeBits;
1491     afsStatusp->ParentVnode = scp->parentVnode;
1492     afsStatusp->ParentUnique = scp->parentUnique;
1493     afsStatusp->ResidencyMask = 0;
1494     afsStatusp->ClientModTime = scp->clientModTime;
1495     afsStatusp->ServerModTime = scp->serverModTime;
1496     afsStatusp->Group = scp->group;
1497     afsStatusp->SyncCounter = 0;
1498     afsStatusp->dataVersionHigh = (afs_uint32)(scp->dataVersion >> 32);
1499     afsStatusp->lockCount = 0;
1500     afsStatusp->Length_hi = scp->length.HighPart;
1501     afsStatusp->errorCode = 0;
1502
1503     volSyncp->spare1 = scp->volumeCreationDate;
1504
1505     return scp_locked;
1506 }
1507
1508 /* Fetch a buffer.  Called with scp locked.
1509  * The scp is locked on return.
1510  */
1511 long cm_GetBuffer(cm_scache_t *scp, cm_buf_t *bufp, int *cpffp, cm_user_t *userp,
1512                   cm_req_t *reqp)
1513 {
1514     long code=0, code1=0;
1515     afs_uint32 nbytes;                  /* bytes in transfer */
1516     afs_uint32 nbytes_hi = 0;            /* high-order 32 bits of bytes in transfer */
1517     afs_uint64 length_found = 0;
1518     long rbytes;                        /* bytes in rx_Read call */
1519     long temp;
1520     AFSFetchStatus afsStatus;
1521     AFSCallBack callback;
1522     AFSVolSync volSync;
1523     char *bufferp;
1524     cm_buf_t *tbufp;                    /* buf we're filling */
1525     osi_queueData_t *qdp;               /* q element we're scanning */
1526     AFSFid tfid;
1527     struct rx_call *rxcallp;
1528     struct rx_connection *rxconnp;
1529     cm_bulkIO_t biod;           /* bulk IO descriptor */
1530     cm_conn_t *connp;
1531     int getroot;
1532     afs_int32 t1,t2;
1533     int require_64bit_ops = 0;
1534     int call_was_64bit = 0;
1535     int fs_fetchdata_offset_bug = 0;
1536     int first_read = 1;
1537     int scp_locked = 1;
1538
1539     memset(&volSync, 0, sizeof(volSync));
1540
1541     /* now, the buffer may or may not be filled with good data (buf_GetNew
1542      * drops lots of locks, and may indeed return a properly initialized
1543      * buffer, although more likely it will just return a new, empty, buffer.
1544      */
1545
1546 #ifdef AFS_FREELANCE_CLIENT
1547
1548     // yj: if they're trying to get the /afs directory, we need to
1549     // handle it differently, since it's local rather than on any
1550     // server
1551
1552     getroot = (scp==cm_data.rootSCachep);
1553     if (getroot)
1554         osi_Log1(afsd_logp,"GetBuffer returns cm_data.rootSCachep=%x",cm_data.rootSCachep);
1555 #endif
1556
1557     if (cm_HaveCallback(scp) && bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow) {
1558         /* We already have this buffer don't do extra work */
1559         return 0;
1560     }
1561
1562     cm_AFSFidFromFid(&tfid, &scp->fid);
1563
1564     code = cm_SetupFetchBIOD(scp, &bufp->offset, &biod, userp, reqp);
1565     if (code) {
1566         /* couldn't even get the first page setup properly */
1567         osi_Log1(afsd_logp, "GetBuffer: SetupFetchBIOD failure code %d", code);
1568         return code;
1569     }
1570
1571     /* once we get here, we have the callback in place, we know that no one
1572      * is fetching the data now.  Check one last time that we still have
1573      * the wrong data, and then fetch it if we're still wrong.
1574      *
1575      * We can lose a race condition and end up with biod.length zero, in
1576      * which case we just retry.
1577      */
1578     if (bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow || biod.length == 0) {
1579         if ((bufp->dataVersion == CM_BUF_VERSION_BAD || bufp->dataVersion < scp->bufDataVersionLow) && 
1580              LargeIntegerGreaterThanOrEqualTo(bufp->offset, scp->serverLength)) 
1581         {
1582             osi_Log4(afsd_logp, "Bad DVs 0x%x != (0x%x -> 0x%x) or length 0x%x",
1583                      bufp->dataVersion, scp->bufDataVersionLow, scp->dataVersion, biod.length);
1584
1585             if (bufp->dataVersion == CM_BUF_VERSION_BAD)
1586                 memset(bufp->datap, 0, cm_data.buf_blockSize);
1587             bufp->dataVersion = scp->dataVersion;
1588         }
1589         cm_ReleaseBIOD(&biod, 0, 0, 1);
1590         return 0;
1591     } else if ((bufp->dataVersion == CM_BUF_VERSION_BAD || bufp->dataVersion < scp->bufDataVersionLow)
1592                 && (scp->mask & CM_SCACHEMASK_TRUNCPOS) &&
1593                 LargeIntegerGreaterThanOrEqualTo(bufp->offset, scp->truncPos)) {
1594         memset(bufp->datap, 0, cm_data.buf_blockSize);
1595         bufp->dataVersion = scp->dataVersion;
1596         cm_ReleaseBIOD(&biod, 0, 0, 1);
1597         return 0;
1598     }
1599
1600     lock_ReleaseWrite(&scp->rw);
1601     scp_locked = 0;
1602
1603     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
1604                                                 ConvertLongToLargeInteger(biod.length)),
1605                                 ConvertLongToLargeInteger(LONG_MAX))) {
1606         require_64bit_ops = 1;
1607     }
1608
1609     osi_Log2(afsd_logp, "cm_GetBuffer: fetching data scp %p bufp %p", scp, bufp);
1610     osi_Log3(afsd_logp, "cm_GetBuffer: fetching data scpDV 0x%x scpDVLow 0x%x bufDV 0x%x",
1611              scp->dataVersion, scp->bufDataVersionLow, bufp->dataVersion);
1612
1613 #ifdef AFS_FREELANCE_CLIENT
1614
1615     // yj code
1616     // if getroot then we don't need to make any calls
1617     // just return fake data
1618         
1619     if (cm_freelanceEnabled && getroot) {
1620         // setup the fake status                        
1621         afsStatus.InterfaceVersion = 0x1;
1622         afsStatus.FileType = 0x2;
1623         afsStatus.LinkCount = scp->linkCount;
1624         afsStatus.Length = cm_fakeDirSize;
1625         afsStatus.DataVersion = (afs_uint32)(cm_data.fakeDirVersion & 0xFFFFFFFF);
1626         afsStatus.Author = 0x1;
1627         afsStatus.Owner = 0x0;
1628         afsStatus.CallerAccess = 0x9;
1629         afsStatus.AnonymousAccess = 0x9;
1630         afsStatus.UnixModeBits = 0x1ff;
1631         afsStatus.ParentVnode = 0x1;
1632         afsStatus.ParentUnique = 0x1;
1633         afsStatus.ResidencyMask = 0;
1634         afsStatus.ClientModTime = (afs_uint32)FakeFreelanceModTime;
1635         afsStatus.ServerModTime = (afs_uint32)FakeFreelanceModTime;
1636         afsStatus.Group = 0;
1637         afsStatus.SyncCounter = 0;
1638         afsStatus.dataVersionHigh = (afs_uint32)(cm_data.fakeDirVersion >> 32);
1639         afsStatus.lockCount = 0;
1640         afsStatus.Length_hi = 0;
1641         afsStatus.errorCode = 0;
1642         memset(&volSync, 0, sizeof(volSync));
1643
1644         // once we're done setting up the status info,
1645         // we just fill the buffer pages with fakedata
1646         // from cm_FakeRootDir. Extra pages are set to
1647         // 0. 
1648                 
1649         lock_ObtainMutex(&cm_Freelance_Lock);
1650         t1 = bufp->offset.LowPart;
1651         qdp = biod.bufListEndp;
1652         while (qdp) {
1653             tbufp = osi_GetQData(qdp);
1654             bufferp=tbufp->datap;
1655             memset(bufferp, 0, cm_data.buf_blockSize);
1656             t2 = cm_fakeDirSize - t1;
1657             if (t2> (afs_int32)cm_data.buf_blockSize) 
1658                 t2=cm_data.buf_blockSize;
1659             if (t2 > 0) {
1660                 memcpy(bufferp, cm_FakeRootDir+t1, t2);
1661             } else {
1662                 t2 = 0;
1663             }
1664             t1+=t2;
1665             qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1666
1667         }
1668         lock_ReleaseMutex(&cm_Freelance_Lock);
1669         
1670         // once we're done, we skip over the part of the
1671         // code that does the ACTUAL fetching of data for
1672         // real files
1673
1674         goto fetchingcompleted;
1675     }
1676
1677 #endif /* AFS_FREELANCE_CLIENT */
1678
1679     /*
1680      * if the requested offset is greater than the file length,
1681      * the file server will return zero bytes of data and the
1682      * current status for the file which we already have since
1683      * we have just obtained a callback.  Instead, we can avoid
1684      * the network round trip by allocating zeroed buffers and
1685      * faking the status info.
1686      */
1687     if (biod.offset.QuadPart >= scp->length.QuadPart) {
1688         osi_Log5(afsd_logp, "SKIP FetchData64 scp 0x%p, off 0x%x:%08x > length 0x%x:%08x",
1689                  scp, biod.offset.HighPart, biod.offset.LowPart,
1690                  scp->length.HighPart, scp->length.LowPart);
1691
1692         /* Clone the current status info */
1693         scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
1694
1695         /* status info complete, fill pages with zeros */
1696         for (qdp = biod.bufListEndp;
1697              qdp;
1698              qdp = (osi_queueData_t *) osi_QPrev(&qdp->q)) {
1699             tbufp = osi_GetQData(qdp);
1700             bufferp=tbufp->datap;
1701             memset(bufferp, 0, cm_data.buf_blockSize);
1702         }
1703
1704         /* no need to contact the file server */
1705         goto fetchingcompleted;
1706     }
1707
1708     if (scp_locked) {
1709         lock_ReleaseWrite(&scp->rw);
1710         scp_locked = 0;
1711     }
1712
1713     /* now make the call */
1714     do {
1715         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
1716         if (code) 
1717             continue;
1718
1719         rxconnp = cm_GetRxConn(connp);
1720         rxcallp = rx_NewCall(rxconnp);
1721         rx_PutConnection(rxconnp);
1722
1723 #ifdef AFS_LARGEFILES
1724         nbytes = nbytes_hi = 0;
1725
1726         if (SERVERHAS64BIT(connp)) {
1727             call_was_64bit = 1;
1728
1729             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
1730                      scp, biod.offset.HighPart, biod.offset.LowPart, biod.length);
1731
1732             code = StartRXAFS_FetchData64(rxcallp, &tfid, biod.offset.QuadPart, biod.length);
1733
1734             if (code == 0) {
1735                 temp = rx_Read32(rxcallp, &nbytes_hi);
1736                 if (temp == sizeof(afs_int32)) {
1737                     nbytes_hi = ntohl(nbytes_hi);
1738                 } else {
1739                     nbytes_hi = 0;
1740                     code = rxcallp->error;
1741                     code1 = rx_EndCall(rxcallp, code);
1742                     rxcallp = NULL;
1743                 }
1744             }
1745         } else {
1746             call_was_64bit = 0;
1747         }
1748
1749         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
1750             if (require_64bit_ops) {
1751                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
1752                 code = CM_ERROR_TOOBIG;
1753             } else {
1754                 if (!rxcallp) {
1755                     rxconnp = cm_GetRxConn(connp);
1756                     rxcallp = rx_NewCall(rxconnp);
1757                     rx_PutConnection(rxconnp);
1758                 }
1759
1760                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
1761                          scp, biod.offset.LowPart, biod.length);
1762
1763                 code = StartRXAFS_FetchData(rxcallp, &tfid, biod.offset.LowPart,
1764                                             biod.length);
1765
1766                 SET_SERVERHASNO64BIT(connp);
1767             }
1768         }
1769
1770         if (code == 0) {
1771             temp  = rx_Read32(rxcallp, &nbytes);
1772             if (temp == sizeof(afs_int32)) {
1773                 nbytes = ntohl(nbytes);
1774                 FillInt64(length_found, nbytes_hi, nbytes);
1775                 if (length_found > biod.length) {
1776                     /*
1777                      * prior to 1.4.12 and 1.5.65 the file server would return
1778                      * (filesize - offset) if the requested offset was greater than
1779                      * the filesize.  The correct return value would have been zero.
1780                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
1781                      * is a race between two RPCs issues by this cache manager, the
1782                      * correct thing will happen the second time.
1783                      */
1784                     osi_Log0(afsd_logp, "cm_GetBuffer length_found > biod.length");
1785                     fs_fetchdata_offset_bug = 1;
1786                 }
1787             } else {
1788                 osi_Log1(afsd_logp, "cm_GetBuffer rx_Read32 returns %d != 4", temp);
1789                 code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
1790             }
1791         }
1792         /* for the moment, nbytes_hi will always be 0 if code == 0
1793            because biod.length is a 32-bit quantity. */
1794 #else
1795         osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
1796                  scp, biod.offset.LowPart, biod.length);
1797
1798         code = StartRXAFS_FetchData(rxcallp, &tfid, biod.offset.LowPart,
1799                                     biod.length);
1800
1801         /* now copy the data out of the pipe and put it in the buffer */
1802         if (code == 0) {
1803             temp  = rx_Read32(rxcallp, &nbytes);
1804             if (temp == sizeof(afs_int32)) {
1805                 length_found = ntohl(nbytes);
1806                 if (length_found > biod.length) {
1807                     /*
1808                      * prior to 1.4.12 and 1.5.65 the file server would return
1809                      * (filesize - offset) if the requested offset was greater than
1810                      * the filesize.  The correct return value would have been zero.
1811                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
1812                      * is a race between two RPCs issues by this cache manager, the
1813                      * correct thing will happen the second time.
1814                      */
1815                     osi_Log0(afsd_logp, "cm_GetBuffer length_found > biod.length");
1816                     fs_fetchdata_offset_bug = 1;
1817                 }
1818             }
1819             else {
1820                 osi_Log1(afsd_logp, "cm_GetBuffer rx_Read32 returns %d != 4", temp);
1821                 code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
1822             }
1823         }
1824 #endif
1825
1826         if (code == 0) {
1827             qdp = biod.bufListEndp;
1828             if (qdp) {
1829                 tbufp = osi_GetQData(qdp);
1830                 bufferp = tbufp->datap;
1831             }
1832             else 
1833                 bufferp = NULL;
1834             /* fill length_found of data from the pipe into the pages.
1835              * When we stop, qdp will point at the last page we're
1836              * dealing with, and bufferp will tell us where we
1837              * stopped.  We'll need this info below when we clear
1838              * the remainder of the last page out (and potentially
1839              * clear later pages out, if we fetch past EOF).
1840              */
1841             while (length_found > 0) {
1842                 /* assert that there are still more buffers;
1843                  * our check above for length_found being less than
1844                  * biod.length should ensure this.
1845                  */
1846                 osi_assertx(bufferp != NULL, "null cm_buf_t");
1847
1848                 /* read rbytes of data */
1849                 rbytes = (afs_uint32)(length_found > cm_data.buf_blockSize ? cm_data.buf_blockSize : length_found);
1850                 temp = rx_Read(rxcallp, bufferp, rbytes);
1851                 if (temp < rbytes) {
1852                     /*
1853                      * If the file server returned (filesize - offset),
1854                      * then the first rx_Read will return zero octets of data.
1855                      * If it does, do not treat it as an error.  Correct the
1856                      * length_found and continue as if the file server said
1857                      * it was sending us zero octets of data.
1858                      */
1859                     if (fs_fetchdata_offset_bug && first_read)
1860                         length_found = 0;
1861                     else
1862                         code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
1863                     break;
1864                 }
1865                 first_read = 0;
1866
1867                 /* allow read-while-fetching.
1868                  * if this is the last buffer, clear the
1869                  * PREFETCHING flag, so the reader waiting for
1870                  * this buffer will start a prefetch.
1871                  */
1872                 tbufp->cmFlags |= CM_BUF_CMFULLYFETCHED;
1873                 lock_ObtainWrite(&scp->rw);
1874                 if (scp->flags & CM_SCACHEFLAG_WAITING) {
1875                     osi_Log1(afsd_logp, "CM GetBuffer Waking scp 0x%p", scp);
1876                     osi_Wakeup((LONG_PTR) &scp->flags);
1877                 }
1878                 if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
1879                     osi_hyper_t tlength = ConvertLongToLargeInteger(biod.length);
1880                     *cpffp = 1;
1881                     cm_ClearPrefetchFlag(0, scp, &biod.offset, &tlength);
1882                 }
1883                 lock_ReleaseWrite(&scp->rw);
1884
1885                 /* and adjust counters */
1886                 length_found -= temp;
1887
1888                 /* and move to the next buffer */
1889                 if (length_found != 0) {
1890                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1891                     if (qdp) {
1892                         tbufp = osi_GetQData(qdp);
1893                         bufferp = tbufp->datap;
1894                     }
1895                     else 
1896                         bufferp = NULL;
1897                 } else 
1898                     bufferp += temp;
1899             }
1900
1901             /* zero out remainder of last pages, in case we are
1902              * fetching past EOF.  We were fetching an integral #
1903              * of pages, but stopped, potentially in the middle of
1904              * a page.  Zero the remainder of that page, and then
1905              * all of the rest of the pages.
1906              */
1907             /* bytes fetched */
1908             osi_assertx((bufferp - tbufp->datap) < LONG_MAX, "data >= LONG_MAX");
1909             rbytes = (long) (bufferp - tbufp->datap);
1910
1911             /* bytes left to zero */
1912             rbytes = cm_data.buf_blockSize - rbytes;
1913             while(qdp) {
1914                 if (rbytes != 0)
1915                     memset(bufferp, 0, rbytes);
1916                 qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1917                 if (qdp == NULL) 
1918                     break;
1919                 tbufp = osi_GetQData(qdp);
1920                 bufferp = tbufp->datap;
1921                 /* bytes to clear in this page */
1922                 rbytes = cm_data.buf_blockSize;
1923             }   
1924         }
1925
1926         if (code == 0) {
1927             if (call_was_64bit)
1928                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
1929             else
1930                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
1931         } else {
1932             if (call_was_64bit)
1933                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
1934             else
1935                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
1936         }
1937
1938         if (rxcallp)
1939             code1 = rx_EndCall(rxcallp, code);
1940
1941         if (code1 == RXKADUNKNOWNKEY)
1942             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
1943
1944         /* If we are avoiding a file server bug, ignore the error state */
1945         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
1946             /* Clone the current status info and clear the error state */
1947             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
1948             if (scp_locked) {
1949                 lock_ReleaseWrite(&scp->rw);
1950                 scp_locked = 0;
1951             }
1952             code = 0;
1953         /* Prefer the error value from FetchData over rx_EndCall */
1954         } else if (code == 0 && code1 != 0)
1955             code = code1;
1956         osi_Log0(afsd_logp, "CALL FetchData DONE");
1957
1958     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
1959
1960   fetchingcompleted:
1961     code = cm_MapRPCError(code, reqp);
1962
1963     if (!scp_locked)
1964         lock_ObtainWrite(&scp->rw);
1965     
1966     /* we know that no one else has changed the buffer, since we still have
1967      * the fetching flag on the buffers, and we have the scp locked again.
1968      * Copy in the version # into the buffer if we got code 0 back from the
1969      * read.
1970      */
1971     if (code == 0) {
1972         for(qdp = biod.bufListp;
1973              qdp;
1974              qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1975             tbufp = osi_GetQData(qdp);
1976             tbufp->dataVersion = afsStatus.dataVersionHigh;
1977             tbufp->dataVersion <<= 32;
1978             tbufp->dataVersion |= afsStatus.DataVersion;
1979
1980 #ifdef DISKCACHE95
1981             /* write buffer out to disk cache */
1982             diskcache_Update(tbufp->dcp, tbufp->datap, cm_data.buf_blockSize,
1983                               tbufp->dataVersion);
1984 #endif /* DISKCACHE95 */
1985         }
1986     }
1987
1988     /* release scatter/gather I/O structure (buffers, locks) */
1989     cm_ReleaseBIOD(&biod, 0, code, 1);
1990
1991     if (code == 0) 
1992         cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, 0);
1993     
1994     return code;
1995 }