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