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