Windows: do not drop lock unnecessarily
[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, &tbase);
691         /* We cheat slightly by not locking the bp mutex. */
692         if (bp) {
693             if ((bp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING | CM_BUF_CMBKGFETCH)) == 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)
730 {
731     osi_hyper_t toffset;
732     long length;
733     cm_req_t req;
734     long code = 0;
735
736     if (scp->flags & CM_SCACHEFLAG_DELETED) {
737         osi_Log4(afsd_logp, "Skipping BKG store - Deleted scp 0x%p, offset 0x%x:%08x, length 0x%x", scp, p2, p1, p3);
738     } else {
739         cm_InitReq(&req);
740
741         /* Retries will be performed by the BkgDaemon thread if appropriate */
742         req.flags |= CM_REQ_NORETRY;
743
744         toffset.LowPart = p1;
745         toffset.HighPart = p2;
746         length = p3;
747
748         osi_Log4(afsd_logp, "Starting BKG store scp 0x%p, offset 0x%x:%08x, length 0x%x", scp, p2, p1, p3);
749
750         code = cm_BufWrite(scp, &toffset, length, /* flags */ 0, userp, &req);
751
752         osi_Log4(afsd_logp, "Finished BKG store scp 0x%p, offset 0x%x:%08x, code 0x%x", scp, p2, p1, code);
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     return code;
775 }
776
777 /* Called with scp locked */
778 void cm_ClearPrefetchFlag(long code, cm_scache_t *scp, osi_hyper_t *base, osi_hyper_t *length)
779 {
780     osi_hyper_t end;
781
782     if (code == 0) {
783         end =  LargeIntegerAdd(*base, *length);
784         if (LargeIntegerGreaterThan(*base, scp->prefetch.base))
785             scp->prefetch.base = *base;
786         if (LargeIntegerGreaterThan(end, scp->prefetch.end))
787             scp->prefetch.end = end;
788     }
789     _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_PREFETCHING);
790 }
791
792 /* do the prefetch.  if the prefetch fails, return 0 (success)
793  * because there is no harm done.  */
794 afs_int32
795 cm_BkgPrefetch(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
796                cm_user_t *userp)
797 {
798     osi_hyper_t length;
799     osi_hyper_t base;
800     osi_hyper_t offset;
801     osi_hyper_t end;
802     osi_hyper_t fetched;
803     osi_hyper_t tblocksize;
804     afs_int32 code;
805     int rxheld = 0;
806     cm_buf_t *bp = NULL;
807     cm_req_t req;
808
809     cm_InitReq(&req);
810
811     /* Retries will be performed by the BkgDaemon thread if appropriate */
812     req.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, &req, &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             _InterlockedAnd(&bp->cmFlags, ~CM_BUF_CMBKGFETCH);
847             buf_Release(bp);
848             bp = NULL;
849             continue;
850         }
851
852         if (!rxheld) {
853             lock_ObtainWrite(&scp->rw);
854             rxheld = 1;
855         }
856
857         code = cm_GetBuffer(scp, bp, NULL, userp, &req);
858         if (code == 0)
859             fetched = LargeIntegerAdd(fetched, tblocksize);
860         buf_Release(bp);
861         _InterlockedAnd(&bp->cmFlags, ~CM_BUF_CMBKGFETCH);
862     }
863
864     if (!rxheld) {
865         lock_ObtainWrite(&scp->rw);
866         rxheld = 1;
867     }
868
869     /* Clear flag from any remaining buffers */
870     for ( ;
871           LargeIntegerLessThan(offset, end);
872           offset = LargeIntegerAdd(offset, tblocksize) )
873     {
874         bp = buf_Find(scp, &offset);
875         if (bp) {
876             _InterlockedAnd(&bp->cmFlags, ~CM_BUF_CMBKGFETCH);
877             buf_Release(bp);
878         }
879     }
880     cm_ClearPrefetchFlag(LargeIntegerGreaterThanZero(fetched) ? 0 : code,
881                          scp, &base, &fetched);
882
883     /* wakeup anyone who is waiting */
884     if (scp->flags & CM_SCACHEFLAG_WAITING) {
885         osi_Log1(afsd_logp, "CM BkgPrefetch Waking scp 0x%p", scp);
886         osi_Wakeup((LONG_PTR) &scp->flags);
887     }
888     lock_ReleaseWrite(&scp->rw);
889
890     osi_Log4(afsd_logp, "Ending BKG prefetch scp 0x%p code 0x%x fetched 0x%x:%x",
891              scp, code, fetched.HighPart, fetched.LowPart);
892     return code;
893 }
894
895 /* a read was issued to offsetp, and we have to determine whether we should
896  * do a prefetch of the next chunk.
897  */
898 void cm_ConsiderPrefetch(cm_scache_t *scp, osi_hyper_t *offsetp, afs_uint32 count,
899                          cm_user_t *userp, cm_req_t *reqp)
900 {
901     long code;
902     int  rwheld = 0;
903     osi_hyper_t realBase;
904     osi_hyper_t readBase;
905     osi_hyper_t readLength;
906     osi_hyper_t readEnd;
907     osi_hyper_t offset;
908     osi_hyper_t tblocksize;             /* a long long temp variable */
909     cm_buf_t    *bp;
910
911     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
912
913     readBase = *offsetp;
914     /* round up to chunk boundary */
915     readBase.LowPart += (cm_chunkSize-1);
916     readBase.LowPart &= (-cm_chunkSize);
917
918     readLength = ConvertLongToLargeInteger(count);
919
920     lock_ObtainWrite(&scp->rw);
921     rwheld = 1;
922     if ((scp->flags & CM_SCACHEFLAG_PREFETCHING)
923          || LargeIntegerLessThanOrEqualTo(readBase, scp->prefetch.base)) {
924         lock_ReleaseWrite(&scp->rw);
925         return;
926     }
927     _InterlockedOr(&scp->flags, CM_SCACHEFLAG_PREFETCHING);
928
929     /* start the scan at the latter of the end of this read or
930      * the end of the last fetched region.
931      */
932     if (LargeIntegerGreaterThan(scp->prefetch.end, readBase))
933         readBase = scp->prefetch.end;
934
935     code = cm_CheckFetchRange(scp, &readBase, &readLength, userp, reqp,
936                               &realBase);
937     if (code) {
938         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_PREFETCHING);
939         lock_ReleaseWrite(&scp->rw);
940         return; /* can't find something to prefetch */
941     }
942
943     readEnd = LargeIntegerAdd(realBase, readLength);
944
945     /*
946      * Mark each buffer in the range as queued for a
947      * background fetch
948      */
949     for ( offset = realBase;
950           LargeIntegerLessThan(offset, readEnd);
951           offset = LargeIntegerAdd(offset, tblocksize) )
952     {
953         if (rwheld) {
954             lock_ReleaseWrite(&scp->rw);
955             rwheld = 0;
956         }
957
958         bp = buf_Find(scp, &offset);
959         if (!bp)
960             continue;
961
962         if (!rwheld) {
963             lock_ObtainWrite(&scp->rw);
964             rwheld = 1;
965         }
966
967         _InterlockedOr(&bp->cmFlags, CM_BUF_CMBKGFETCH);
968         buf_Release(bp);
969     }
970
971     if (rwheld)
972         lock_ReleaseWrite(&scp->rw);
973
974     osi_Log2(afsd_logp, "BKG Prefetch request scp 0x%p, base 0x%x",
975              scp, realBase.LowPart);
976
977     cm_QueueBKGRequest(scp, cm_BkgPrefetch,
978                        realBase.LowPart, realBase.HighPart,
979                        readLength.LowPart, readLength.HighPart,
980                        userp);
981 }
982
983 /* scp must be locked; temporarily unlocked during processing.
984  * If returns 0, returns buffers held in biop, and with
985  * CM_BUF_CMSTORING set.
986  *
987  * Caller *must* set CM_BUF_WRITING and reset the over.hEvent field if the
988  * buffer is ever unlocked before CM_BUF_DIRTY is cleared.  And if
989  * CM_BUF_WRITING is ever viewed by anyone, then it must be cleared, sleepers
990  * must be woken, and the event must be set when the I/O is done.  All of this
991  * is required so that buf_WaitIO synchronizes properly with the buffer as it
992  * is being written out.
993  */
994 long cm_SetupStoreBIOD(cm_scache_t *scp, osi_hyper_t *inOffsetp, long inSize,
995                        cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
996 {
997     cm_buf_t *bufp;
998     osi_queueData_t *qdp;
999     osi_hyper_t thyper;
1000     osi_hyper_t tbase;
1001     osi_hyper_t scanStart;              /* where to start scan for dirty pages */
1002     osi_hyper_t scanEnd;                /* where to stop scan for dirty pages */
1003     osi_hyper_t firstModOffset; /* offset of first modified page in range */
1004     long temp;
1005     long code;
1006     long flags;                 /* flags to cm_SyncOp */
1007
1008     /* clear things out */
1009     biop->scp = scp;                    /* do not hold; held by caller */
1010     biop->offset = *inOffsetp;
1011     biop->length = 0;
1012     biop->bufListp = NULL;
1013     biop->bufListEndp = NULL;
1014     biop->reserved = 0;
1015
1016     /* reserve a chunk's worth of buffers */
1017     lock_ReleaseWrite(&scp->rw);
1018     buf_ReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1019     lock_ObtainWrite(&scp->rw);
1020
1021     bufp = NULL;
1022     for (temp = 0; temp < inSize; temp += cm_data.buf_blockSize) {
1023         thyper = ConvertLongToLargeInteger(temp);
1024         tbase = LargeIntegerAdd(*inOffsetp, thyper);
1025
1026         bufp = buf_Find(scp, &tbase);
1027         if (bufp) {
1028             /* get buffer mutex and scp mutex safely */
1029             lock_ReleaseWrite(&scp->rw);
1030             lock_ObtainMutex(&bufp->mx);
1031
1032             /*
1033              * if the buffer is actively involved in I/O
1034              * we wait for the I/O to complete.
1035              */
1036             if (bufp->flags & (CM_BUF_WRITING|CM_BUF_READING))
1037                 buf_WaitIO(scp, bufp);
1038
1039             lock_ObtainWrite(&scp->rw);
1040             flags = CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_STOREDATA | CM_SCACHESYNC_BUFLOCKED;
1041             code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1042             if (code) {
1043                 lock_ReleaseMutex(&bufp->mx);
1044                 buf_Release(bufp);
1045                 bufp = NULL;
1046                 buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1047                 return code;
1048             }
1049
1050             /* if the buffer is dirty, we're done */
1051             if (bufp->flags & CM_BUF_DIRTY) {
1052                 osi_assertx(!(bufp->flags & CM_BUF_WRITING),
1053                             "WRITING w/o CMSTORING in SetupStoreBIOD");
1054                 _InterlockedOr(&bufp->flags, CM_BUF_WRITING);
1055                 break;
1056             }
1057
1058             /* this buffer is clean, so there's no reason to process it */
1059             cm_SyncOpDone(scp, bufp, flags);
1060             lock_ReleaseMutex(&bufp->mx);
1061             buf_Release(bufp);
1062             bufp = NULL;
1063         }
1064     }
1065
1066     biop->reserved = 1;
1067
1068     /* if we get here, if bufp is null, we didn't find any dirty buffers
1069      * that weren't already being stored back, so we just quit now.
1070      */
1071     if (!bufp) {
1072         return 0;
1073     }
1074
1075     /* don't need buffer mutex any more */
1076     lock_ReleaseMutex(&bufp->mx);
1077
1078     /* put this element in the list */
1079     qdp = osi_QDAlloc();
1080     osi_SetQData(qdp, bufp);
1081     /* don't have to hold bufp, since held by buf_Find above */
1082     osi_QAddH((osi_queue_t **) &biop->bufListp,
1083               (osi_queue_t **) &biop->bufListEndp,
1084               &qdp->q);
1085     biop->length = cm_data.buf_blockSize;
1086     firstModOffset = bufp->offset;
1087     biop->offset = firstModOffset;
1088     bufp = NULL;        /* this buffer and reference added to the queue */
1089
1090     /* compute the window surrounding *inOffsetp of size cm_chunkSize */
1091     scanStart = *inOffsetp;
1092     scanStart.LowPart &= (-cm_chunkSize);
1093     thyper = ConvertLongToLargeInteger(cm_chunkSize);
1094     scanEnd = LargeIntegerAdd(scanStart, thyper);
1095
1096     flags = CM_SCACHESYNC_GETSTATUS
1097         | CM_SCACHESYNC_STOREDATA
1098         | CM_SCACHESYNC_BUFLOCKED
1099         | CM_SCACHESYNC_NOWAIT;
1100
1101     /* start by looking backwards until scanStart */
1102     /* hyper version of cm_data.buf_blockSize */
1103     thyper = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1104     tbase = LargeIntegerSubtract(firstModOffset, thyper);
1105     while(LargeIntegerGreaterThanOrEqualTo(tbase, scanStart)) {
1106         /* see if we can find the buffer */
1107         bufp = buf_Find(scp, &tbase);
1108         if (!bufp)
1109             break;
1110
1111         /* try to lock it, and quit if we can't (simplifies locking) */
1112         lock_ReleaseWrite(&scp->rw);
1113         code = lock_TryMutex(&bufp->mx);
1114         lock_ObtainWrite(&scp->rw);
1115         if (code == 0) {
1116             buf_Release(bufp);
1117             bufp = NULL;
1118             break;
1119         }
1120
1121         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1122         if (code) {
1123             lock_ReleaseMutex(&bufp->mx);
1124             buf_Release(bufp);
1125             bufp = NULL;
1126             break;
1127         }
1128
1129         if (!(bufp->flags & CM_BUF_DIRTY)) {
1130             /* buffer is clean, so we shouldn't add it */
1131             cm_SyncOpDone(scp, bufp, flags);
1132             lock_ReleaseMutex(&bufp->mx);
1133             buf_Release(bufp);
1134             bufp = NULL;
1135             break;
1136         }
1137
1138         /* don't need buffer mutex any more */
1139         lock_ReleaseMutex(&bufp->mx);
1140
1141         /* we have a dirty buffer ready for storing.  Add it to the tail
1142          * of the list, since it immediately precedes all of the disk
1143          * addresses we've already collected.
1144          */
1145         qdp = osi_QDAlloc();
1146         osi_SetQData(qdp, bufp);
1147         /* no buf_hold necessary, since we have it held from buf_Find */
1148         osi_QAddT((osi_queue_t **) &biop->bufListp,
1149                   (osi_queue_t **) &biop->bufListEndp,
1150                   &qdp->q);
1151         bufp = NULL;            /* added to the queue */
1152
1153         /* update biod info describing the transfer */
1154         biop->offset = LargeIntegerSubtract(biop->offset, thyper);
1155         biop->length += cm_data.buf_blockSize;
1156
1157         /* update loop pointer */
1158         tbase = LargeIntegerSubtract(tbase, thyper);
1159     }   /* while loop looking for pages preceding the one we found */
1160
1161     /* now, find later dirty, contiguous pages, and add them to the list */
1162     /* hyper version of cm_data.buf_blockSize */
1163     thyper = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1164     tbase = LargeIntegerAdd(firstModOffset, thyper);
1165     while(LargeIntegerLessThan(tbase, scanEnd)) {
1166         /* see if we can find the buffer */
1167         bufp = buf_Find(scp, &tbase);
1168         if (!bufp)
1169             break;
1170
1171         /* try to lock it, and quit if we can't (simplifies locking) */
1172         lock_ReleaseWrite(&scp->rw);
1173         code = lock_TryMutex(&bufp->mx);
1174         lock_ObtainWrite(&scp->rw);
1175         if (code == 0) {
1176             buf_Release(bufp);
1177             bufp = NULL;
1178             break;
1179         }
1180
1181         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1182         if (code) {
1183             lock_ReleaseMutex(&bufp->mx);
1184             buf_Release(bufp);
1185             bufp = NULL;
1186             break;
1187         }
1188
1189         if (!(bufp->flags & CM_BUF_DIRTY)) {
1190             /* buffer is clean, so we shouldn't add it */
1191             cm_SyncOpDone(scp, bufp, flags);
1192             lock_ReleaseMutex(&bufp->mx);
1193             buf_Release(bufp);
1194             bufp = NULL;
1195             break;
1196         }
1197
1198         /* don't need buffer mutex any more */
1199         lock_ReleaseMutex(&bufp->mx);
1200
1201         /* we have a dirty buffer ready for storing.  Add it to the head
1202          * of the list, since it immediately follows all of the disk
1203          * addresses we've already collected.
1204          */
1205         qdp = osi_QDAlloc();
1206         osi_SetQData(qdp, bufp);
1207         /* no buf_hold necessary, since we have it held from buf_Find */
1208         osi_QAddH((osi_queue_t **) &biop->bufListp,
1209                   (osi_queue_t **) &biop->bufListEndp,
1210                   &qdp->q);
1211         bufp = NULL;
1212
1213         /* update biod info describing the transfer */
1214         biop->length += cm_data.buf_blockSize;
1215
1216         /* update loop pointer */
1217         tbase = LargeIntegerAdd(tbase, thyper);
1218     }   /* while loop looking for pages following the first page we found */
1219
1220     /* finally, we're done */
1221     return 0;
1222 }
1223
1224 /* scp must be locked; temporarily unlocked during processing.
1225  * If returns 0, returns buffers held in biop, and with
1226  * CM_BUF_CMFETCHING flags set.
1227  * If an error is returned, we don't return any buffers.
1228  */
1229 long cm_SetupFetchBIOD(cm_scache_t *scp, osi_hyper_t *offsetp,
1230                         cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
1231 {
1232     long code;
1233     cm_buf_t *tbp;
1234     osi_hyper_t tblocksize;             /* a long long temp variable */
1235     osi_hyper_t pageBase;               /* base offset we're looking at */
1236     osi_queueData_t *qdp;               /* one temp queue structure */
1237     osi_queueData_t *tqdp;              /* another temp queue structure */
1238     long collected;                     /* how many bytes have been collected */
1239     int isFirst;
1240     long flags;
1241     osi_hyper_t fileSize;               /* the # of bytes in the file */
1242     osi_queueData_t *heldBufListp;      /* we hold all buffers in this list */
1243     osi_queueData_t *heldBufListEndp;   /* first one */
1244     int reserving;
1245
1246     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1247
1248     biop->scp = scp;                    /* do not hold; held by caller */
1249     biop->offset = *offsetp;
1250     /* null out the list of buffers */
1251     biop->bufListp = biop->bufListEndp = NULL;
1252     biop->reserved = 0;
1253
1254     /* first lookup the file's length, so we know when to stop */
1255     code = cm_SyncOp(scp, NULL, userp, reqp, 0,
1256                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1257     if (code)
1258         return code;
1259
1260     /* copy out size, since it may change */
1261     fileSize = scp->serverLength;
1262
1263     lock_ReleaseWrite(&scp->rw);
1264
1265     pageBase = *offsetp;
1266     collected = pageBase.LowPart & (cm_chunkSize - 1);
1267     heldBufListp = NULL;
1268     heldBufListEndp = NULL;
1269
1270     /*
1271      * Obtaining buffers can cause dirty buffers to be recycled, which
1272      * can cause a storeback, so cannot be done while we have buffers
1273      * reserved.
1274      *
1275      * To get around this, we get buffers twice.  Before reserving buffers,
1276      * we obtain and release each one individually.  After reserving
1277      * buffers, we try to obtain them again, but only by lookup, not by
1278      * recycling.  If a buffer has gone away while we were waiting for
1279      * the others, we just use whatever buffers we already have.
1280      *
1281      * On entry to this function, we are already holding a buffer, so we
1282      * can't wait for reservation.  So we call buf_TryReserveBuffers()
1283      * instead.  Not only that, we can't really even call buf_Get(), for
1284      * the same reason.  We can't avoid that, though.  To avoid deadlock
1285      * we allow only one thread to be executing the buf_Get()-buf_Release()
1286      * sequence at a time.
1287      */
1288
1289     /* first hold all buffers, since we can't hold any locks in buf_Get */
1290     while (1) {
1291         /* stop at chunk boundary */
1292         if (collected >= cm_chunkSize)
1293             break;
1294
1295         /* see if the next page would be past EOF */
1296         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize))
1297             break;
1298
1299         code = buf_Get(scp, &pageBase, reqp, &tbp);
1300         if (code) {
1301             lock_ObtainWrite(&scp->rw);
1302             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1303             return code;
1304         }
1305
1306         buf_Release(tbp);
1307         tbp = NULL;
1308
1309         pageBase = LargeIntegerAdd(tblocksize, pageBase);
1310         collected += cm_data.buf_blockSize;
1311     }
1312
1313     /* reserve a chunk's worth of buffers if possible */
1314     reserving = buf_TryReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1315
1316     pageBase = *offsetp;
1317     collected = pageBase.LowPart & (cm_chunkSize - 1);
1318
1319     /* now hold all buffers, if they are still there */
1320     while (1) {
1321         /* stop at chunk boundary */
1322         if (collected >= cm_chunkSize)
1323             break;
1324
1325         /* see if the next page would be past EOF */
1326         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize))
1327             break;
1328
1329         tbp = buf_Find(scp, &pageBase);
1330         if (!tbp)
1331             break;
1332
1333         /* add the buffer to the list */
1334         qdp = osi_QDAlloc();
1335         osi_SetQData(qdp, tbp);
1336         osi_QAddH((osi_queue_t **)&heldBufListp,
1337                   (osi_queue_t **)&heldBufListEndp,
1338                   &qdp->q);
1339         /* leave tbp held (from buf_Get) */
1340
1341         if (!reserving)
1342             break;
1343
1344         collected += cm_data.buf_blockSize;
1345         pageBase = LargeIntegerAdd(tblocksize, pageBase);
1346     }
1347
1348     /* look at each buffer, adding it into the list if it looks idle and
1349      * filled with old data.  One special case: wait for idle if it is the
1350      * first buffer since we really need that one for our caller to make
1351      * any progress.
1352      */
1353     isFirst = 1;
1354     collected = 0;              /* now count how many we'll really use */
1355     for (tqdp = heldBufListEndp;
1356         tqdp;
1357           tqdp = (osi_queueData_t *) osi_QPrev(&tqdp->q)) {
1358         /* get a ptr to the held buffer */
1359         tbp = osi_GetQData(tqdp);
1360         pageBase = tbp->offset;
1361
1362         /* now lock the buffer lock */
1363         lock_ObtainMutex(&tbp->mx);
1364         lock_ObtainWrite(&scp->rw);
1365
1366         /* don't bother fetching over data that is already current */
1367         if (tbp->dataVersion <= scp->dataVersion && tbp->dataVersion >= scp->bufDataVersionLow) {
1368             /* we don't need this buffer, since it is current */
1369             lock_ReleaseWrite(&scp->rw);
1370             lock_ReleaseMutex(&tbp->mx);
1371             break;
1372         }
1373
1374         flags = CM_SCACHESYNC_FETCHDATA | CM_SCACHESYNC_BUFLOCKED;
1375         if (!isFirst)
1376             flags |= CM_SCACHESYNC_NOWAIT;
1377
1378         /* wait for the buffer to serialize, if required.  Doesn't
1379          * release the scp or buffer lock(s) if NOWAIT is specified.
1380          */
1381         code = cm_SyncOp(scp, tbp, userp, reqp, 0, flags);
1382         if (code) {
1383             lock_ReleaseWrite(&scp->rw);
1384             lock_ReleaseMutex(&tbp->mx);
1385             break;
1386         }
1387
1388         /* don't fetch over dirty buffers */
1389         if (tbp->flags & CM_BUF_DIRTY) {
1390             cm_SyncOpDone(scp, tbp, flags);
1391             lock_ReleaseWrite(&scp->rw);
1392             lock_ReleaseMutex(&tbp->mx);
1393             break;
1394         }
1395
1396         /* Release locks */
1397         lock_ReleaseWrite(&scp->rw);
1398         lock_ReleaseMutex(&tbp->mx);
1399
1400         /* add the buffer to the list */
1401         qdp = osi_QDAlloc();
1402         osi_SetQData(qdp, tbp);
1403         osi_QAddH((osi_queue_t **)&biop->bufListp,
1404                   (osi_queue_t **)&biop->bufListEndp,
1405                   &qdp->q);
1406         buf_Hold(tbp);
1407
1408         /* from now on, a failure just stops our collection process, but
1409          * we still do the I/O to whatever we've already managed to collect.
1410          */
1411         isFirst = 0;
1412         collected += cm_data.buf_blockSize;
1413     }
1414
1415     /* now, we've held in biop->bufListp all the buffer's we're really
1416      * interested in.  We also have holds left from heldBufListp, and we
1417      * now release those holds on the buffers.
1418      */
1419     for (qdp = heldBufListp; qdp; qdp = tqdp) {
1420         tqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1421         tbp = osi_GetQData(qdp);
1422         osi_QRemoveHT((osi_queue_t **) &heldBufListp,
1423                       (osi_queue_t **) &heldBufListEndp,
1424                       &qdp->q);
1425         osi_QDFree(qdp);
1426         buf_Release(tbp);
1427         tbp = NULL;
1428     }
1429
1430     /* Caller expects this */
1431     lock_ObtainWrite(&scp->rw);
1432
1433     /* if we got a failure setting up the first buffer, then we don't have
1434      * any side effects yet, and we also have failed an operation that the
1435      * caller requires to make any progress.  Give up now.
1436      */
1437     if (code && isFirst) {
1438         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1439         return code;
1440     }
1441
1442     /* otherwise, we're still OK, and should just return the I/O setup we've
1443      * got.
1444      */
1445     biop->length = collected;
1446     biop->reserved = reserving;
1447     return 0;
1448 }
1449
1450 /* release a bulk I/O structure that was setup by cm_SetupFetchBIOD or by
1451  * cm_SetupStoreBIOD
1452  */
1453 void cm_ReleaseBIOD(cm_bulkIO_t *biop, int isStore, long code, int scp_locked)
1454 {
1455     cm_scache_t *scp;           /* do not release; not held in biop */
1456     cm_buf_t *bufp;
1457     osi_queueData_t *qdp;
1458     osi_queueData_t *nqdp;
1459     int flags;
1460
1461     /* Give back reserved buffers */
1462     if (biop->reserved)
1463         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1464
1465     if (isStore)
1466         flags = CM_SCACHESYNC_STOREDATA;
1467     else
1468         flags = CM_SCACHESYNC_FETCHDATA;
1469
1470     scp = biop->scp;
1471     if (biop->bufListp) {
1472         for(qdp = biop->bufListp; qdp; qdp = nqdp) {
1473             /* lookup next guy first, since we're going to free this one */
1474             nqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1475
1476             /* extract buffer and free queue data */
1477             bufp = osi_GetQData(qdp);
1478             osi_QRemoveHT((osi_queue_t **) &biop->bufListp,
1479                            (osi_queue_t **) &biop->bufListEndp,
1480                            &qdp->q);
1481             osi_QDFree(qdp);
1482
1483             /* now, mark I/O as done, unlock the buffer and release it */
1484             if (scp_locked)
1485                 lock_ReleaseWrite(&scp->rw);
1486             lock_ObtainMutex(&bufp->mx);
1487             lock_ObtainWrite(&scp->rw);
1488             cm_SyncOpDone(scp, bufp, flags);
1489
1490             /* turn off writing and wakeup users */
1491             if (isStore) {
1492                 if (bufp->flags & CM_BUF_WAITING) {
1493                     osi_Log2(afsd_logp, "cm_ReleaseBIOD Waking [scp 0x%p] bp 0x%p", scp, bufp);
1494                     osi_Wakeup((LONG_PTR) bufp);
1495                 }
1496                 if (code) {
1497                     _InterlockedAnd(&bufp->flags, ~CM_BUF_WRITING);
1498                     switch (code) {
1499                     case CM_ERROR_NOSUCHFILE:
1500                     case CM_ERROR_BADFD:
1501                     case CM_ERROR_NOACCESS:
1502                     case CM_ERROR_QUOTA:
1503                     case CM_ERROR_SPACE:
1504                     case CM_ERROR_TOOBIG:
1505                     case CM_ERROR_READONLY:
1506                     case CM_ERROR_NOSUCHPATH:
1507                         /*
1508                          * Apply the fatal error to this buffer.
1509                          */
1510                         _InterlockedAnd(&bufp->flags, ~CM_BUF_DIRTY);
1511                         _InterlockedOr(&bufp->flags, CM_BUF_ERROR);
1512                         bufp->dirty_offset = 0;
1513                         bufp->dirty_length = 0;
1514                         bufp->error = code;
1515                         bufp->dataVersion = CM_BUF_VERSION_BAD;
1516                         bufp->dirtyCounter++;
1517                         break;
1518                     case CM_ERROR_TIMEDOUT:
1519                     case CM_ERROR_ALLDOWN:
1520                     case CM_ERROR_ALLBUSY:
1521                     case CM_ERROR_ALLOFFLINE:
1522                     case CM_ERROR_CLOCKSKEW:
1523                     default:
1524                         /* do not mark the buffer in error state but do
1525                         * not attempt to complete the rest either.
1526                         */
1527                         break;
1528                     }
1529                 } else {
1530                     _InterlockedAnd(&bufp->flags, ~(CM_BUF_WRITING | CM_BUF_DIRTY));
1531                     bufp->dirty_offset = bufp->dirty_length = 0;
1532                 }
1533             }
1534
1535             if (!scp_locked)
1536                 lock_ReleaseWrite(&scp->rw);
1537             lock_ReleaseMutex(&bufp->mx);
1538             buf_Release(bufp);
1539             bufp = NULL;
1540         }
1541     } else {
1542         if (!scp_locked)
1543             lock_ObtainWrite(&scp->rw);
1544         cm_SyncOpDone(scp, NULL, flags);
1545         if (!scp_locked)
1546             lock_ReleaseWrite(&scp->rw);
1547     }
1548
1549     /* clean things out */
1550     biop->bufListp = NULL;
1551     biop->bufListEndp = NULL;
1552 }
1553
1554 static int
1555 cm_CloneStatus(cm_scache_t *scp, cm_user_t *userp, int scp_locked,
1556                AFSFetchStatus *afsStatusp, AFSVolSync *volSyncp)
1557 {
1558     // setup the status based upon the scp data
1559     afsStatusp->InterfaceVersion = 0x1;
1560     switch (scp->fileType) {
1561     case CM_SCACHETYPE_FILE:
1562         afsStatusp->FileType = File;
1563         break;
1564     case CM_SCACHETYPE_DIRECTORY:
1565         afsStatusp->FileType = Directory;
1566         break;
1567     case CM_SCACHETYPE_MOUNTPOINT:
1568         afsStatusp->FileType = SymbolicLink;
1569         break;
1570     case CM_SCACHETYPE_SYMLINK:
1571     case CM_SCACHETYPE_DFSLINK:
1572         afsStatusp->FileType = SymbolicLink;
1573         break;
1574     default:
1575         afsStatusp->FileType = -1;    /* an invalid value */
1576     }
1577     afsStatusp->LinkCount = scp->linkCount;
1578     afsStatusp->Length = scp->length.LowPart;
1579     afsStatusp->DataVersion = (afs_uint32)(scp->dataVersion & MAX_AFS_UINT32);
1580     afsStatusp->Author = 0x1;
1581     afsStatusp->Owner = scp->owner;
1582     if (!scp_locked) {
1583         lock_ObtainWrite(&scp->rw);
1584         scp_locked = 1;
1585     }
1586     if (cm_FindACLCache(scp, userp, &afsStatusp->CallerAccess))
1587         afsStatusp->CallerAccess = scp->anyAccess;
1588     afsStatusp->AnonymousAccess = scp->anyAccess;
1589     afsStatusp->UnixModeBits = scp->unixModeBits;
1590     afsStatusp->ParentVnode = scp->parentVnode;
1591     afsStatusp->ParentUnique = scp->parentUnique;
1592     afsStatusp->ResidencyMask = 0;
1593     afsStatusp->ClientModTime = scp->clientModTime;
1594     afsStatusp->ServerModTime = scp->serverModTime;
1595     afsStatusp->Group = scp->group;
1596     afsStatusp->SyncCounter = 0;
1597     afsStatusp->dataVersionHigh = (afs_uint32)(scp->dataVersion >> 32);
1598     afsStatusp->lockCount = 0;
1599     afsStatusp->Length_hi = scp->length.HighPart;
1600     afsStatusp->errorCode = 0;
1601
1602     volSyncp->spare1 = scp->volumeCreationDate;
1603
1604     return scp_locked;
1605 }
1606
1607 /* Fetch a buffer.  Called with scp locked.
1608  * The scp is locked on return.
1609  */
1610 long cm_GetBuffer(cm_scache_t *scp, cm_buf_t *bufp, int *cpffp, cm_user_t *userp,
1611                   cm_req_t *reqp)
1612 {
1613     long code=0, code1=0;
1614     afs_uint32 nbytes;                  /* bytes in transfer */
1615     afs_uint32 nbytes_hi = 0;            /* high-order 32 bits of bytes in transfer */
1616     afs_uint64 length_found = 0;
1617     long rbytes;                        /* bytes in rx_Read call */
1618     long temp;
1619     AFSFetchStatus afsStatus;
1620     AFSCallBack callback;
1621     AFSVolSync volSync;
1622     char *bufferp;
1623     afs_uint32 buffer_offset;
1624     cm_buf_t *tbufp;                    /* buf we're filling */
1625     osi_queueData_t *qdp;               /* q element we're scanning */
1626     AFSFid tfid;
1627     struct rx_call *rxcallp;
1628     struct rx_connection *rxconnp;
1629     cm_bulkIO_t biod;           /* bulk IO descriptor */
1630     cm_conn_t *connp;
1631     int getroot;
1632     afs_int32 t1,t2;
1633     int require_64bit_ops = 0;
1634     int call_was_64bit = 0;
1635     int fs_fetchdata_offset_bug = 0;
1636     int first_read = 1;
1637     int scp_locked = 1;
1638
1639     memset(&volSync, 0, sizeof(volSync));
1640
1641     /* now, the buffer may or may not be filled with good data (buf_GetNewLocked
1642      * drops lots of locks, and may indeed return a properly initialized
1643      * buffer, although more likely it will just return a new, empty, buffer.
1644      */
1645
1646 #ifdef AFS_FREELANCE_CLIENT
1647
1648     // yj: if they're trying to get the /afs directory, we need to
1649     // handle it differently, since it's local rather than on any
1650     // server
1651
1652     getroot = (scp==cm_data.rootSCachep);
1653     if (getroot)
1654         osi_Log1(afsd_logp,"GetBuffer returns cm_data.rootSCachep=%x",cm_data.rootSCachep);
1655 #endif
1656
1657     if (cm_HaveCallback(scp) && bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow) {
1658         /* We already have this buffer don't do extra work */
1659         return 0;
1660     }
1661
1662     cm_AFSFidFromFid(&tfid, &scp->fid);
1663
1664     code = cm_SetupFetchBIOD(scp, &bufp->offset, &biod, userp, reqp);
1665     if (code) {
1666         /* couldn't even get the first page setup properly */
1667         osi_Log1(afsd_logp, "GetBuffer: SetupFetchBIOD failure code %d", code);
1668         return code;
1669     }
1670
1671     /* once we get here, we have the callback in place, we know that no one
1672      * is fetching the data now.  Check one last time that we still have
1673      * the wrong data, and then fetch it if we're still wrong.
1674      *
1675      * We can lose a race condition and end up with biod.length zero, in
1676      * which case we just retry.
1677      */
1678     if (bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow || biod.length == 0) {
1679         if ((bufp->dataVersion == CM_BUF_VERSION_BAD || bufp->dataVersion < scp->bufDataVersionLow) &&
1680              LargeIntegerGreaterThanOrEqualTo(bufp->offset, scp->serverLength))
1681         {
1682             osi_Log4(afsd_logp, "Bad DVs 0x%x != (0x%x -> 0x%x) or length 0x%x",
1683                      bufp->dataVersion, scp->bufDataVersionLow, scp->dataVersion, biod.length);
1684
1685             if (bufp->dataVersion == CM_BUF_VERSION_BAD)
1686                 memset(bufp->datap, 0, cm_data.buf_blockSize);
1687             bufp->dataVersion = scp->dataVersion;
1688         }
1689         cm_ReleaseBIOD(&biod, 0, 0, 1);
1690         return 0;
1691     } else if ((bufp->dataVersion == CM_BUF_VERSION_BAD || bufp->dataVersion < scp->bufDataVersionLow)
1692                 && (scp->mask & CM_SCACHEMASK_TRUNCPOS) &&
1693                 LargeIntegerGreaterThanOrEqualTo(bufp->offset, scp->truncPos)) {
1694         memset(bufp->datap, 0, cm_data.buf_blockSize);
1695         bufp->dataVersion = scp->dataVersion;
1696         cm_ReleaseBIOD(&biod, 0, 0, 1);
1697         return 0;
1698     }
1699
1700     lock_ReleaseWrite(&scp->rw);
1701     scp_locked = 0;
1702
1703     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
1704                                                 ConvertLongToLargeInteger(biod.length)),
1705                                 ConvertLongToLargeInteger(LONG_MAX))) {
1706         require_64bit_ops = 1;
1707     }
1708
1709     osi_Log2(afsd_logp, "cm_GetBuffer: fetching data scp %p bufp %p", scp, bufp);
1710     osi_Log3(afsd_logp, "cm_GetBuffer: fetching data scpDV 0x%x scpDVLow 0x%x bufDV 0x%x",
1711              scp->dataVersion, scp->bufDataVersionLow, bufp->dataVersion);
1712
1713 #ifdef AFS_FREELANCE_CLIENT
1714
1715     // yj code
1716     // if getroot then we don't need to make any calls
1717     // just return fake data
1718
1719     if (cm_freelanceEnabled && getroot) {
1720         // setup the fake status
1721         afsStatus.InterfaceVersion = 0x1;
1722         afsStatus.FileType = 0x2;
1723         afsStatus.LinkCount = scp->linkCount;
1724         afsStatus.Length = cm_fakeDirSize;
1725         afsStatus.DataVersion = (afs_uint32)(cm_data.fakeDirVersion & 0xFFFFFFFF);
1726         afsStatus.Author = 0x1;
1727         afsStatus.Owner = 0x0;
1728         afsStatus.CallerAccess = 0x9;
1729         afsStatus.AnonymousAccess = 0x9;
1730         afsStatus.UnixModeBits = 0x1ff;
1731         afsStatus.ParentVnode = 0x1;
1732         afsStatus.ParentUnique = 0x1;
1733         afsStatus.ResidencyMask = 0;
1734         afsStatus.ClientModTime = (afs_uint32)FakeFreelanceModTime;
1735         afsStatus.ServerModTime = (afs_uint32)FakeFreelanceModTime;
1736         afsStatus.Group = 0;
1737         afsStatus.SyncCounter = 0;
1738         afsStatus.dataVersionHigh = (afs_uint32)(cm_data.fakeDirVersion >> 32);
1739         afsStatus.lockCount = 0;
1740         afsStatus.Length_hi = 0;
1741         afsStatus.errorCode = 0;
1742         memset(&volSync, 0, sizeof(volSync));
1743
1744         // once we're done setting up the status info,
1745         // we just fill the buffer pages with fakedata
1746         // from cm_FakeRootDir. Extra pages are set to
1747         // 0.
1748
1749         lock_ObtainMutex(&cm_Freelance_Lock);
1750         t1 = bufp->offset.LowPart;
1751         qdp = biod.bufListEndp;
1752         while (qdp) {
1753             tbufp = osi_GetQData(qdp);
1754             bufferp=tbufp->datap;
1755             memset(bufferp, 0, cm_data.buf_blockSize);
1756             t2 = cm_fakeDirSize - t1;
1757             if (t2> (afs_int32)cm_data.buf_blockSize)
1758                 t2=cm_data.buf_blockSize;
1759             if (t2 > 0) {
1760                 memcpy(bufferp, cm_FakeRootDir+t1, t2);
1761             } else {
1762                 t2 = 0;
1763             }
1764             t1+=t2;
1765             qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1766
1767         }
1768         lock_ReleaseMutex(&cm_Freelance_Lock);
1769
1770         // once we're done, we skip over the part of the
1771         // code that does the ACTUAL fetching of data for
1772         // real files
1773
1774         goto fetchingcompleted;
1775     }
1776
1777 #endif /* AFS_FREELANCE_CLIENT */
1778
1779     /*
1780      * if the requested offset is greater than the file length,
1781      * the file server will return zero bytes of data and the
1782      * current status for the file which we already have since
1783      * we have just obtained a callback.  Instead, we can avoid
1784      * the network round trip by allocating zeroed buffers and
1785      * faking the status info.
1786      */
1787     if (biod.offset.QuadPart >= scp->length.QuadPart) {
1788         osi_Log5(afsd_logp, "SKIP FetchData64 scp 0x%p, off 0x%x:%08x > length 0x%x:%08x",
1789                  scp, biod.offset.HighPart, biod.offset.LowPart,
1790                  scp->length.HighPart, scp->length.LowPart);
1791
1792         /* Clone the current status info */
1793         scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
1794
1795         /* status info complete, fill pages with zeros */
1796         for (qdp = biod.bufListEndp;
1797              qdp;
1798              qdp = (osi_queueData_t *) osi_QPrev(&qdp->q)) {
1799             tbufp = osi_GetQData(qdp);
1800             bufferp=tbufp->datap;
1801             memset(bufferp, 0, cm_data.buf_blockSize);
1802         }
1803
1804         /* no need to contact the file server */
1805         goto fetchingcompleted;
1806     }
1807
1808     if (scp_locked) {
1809         lock_ReleaseWrite(&scp->rw);
1810         scp_locked = 0;
1811     }
1812
1813     /* now make the call */
1814     do {
1815         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
1816         if (code)
1817             continue;
1818
1819         rxconnp = cm_GetRxConn(connp);
1820         rxcallp = rx_NewCall(rxconnp);
1821         rx_PutConnection(rxconnp);
1822
1823         nbytes = nbytes_hi = 0;
1824
1825         if (SERVERHAS64BIT(connp)) {
1826             call_was_64bit = 1;
1827
1828             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
1829                      scp, biod.offset.HighPart, biod.offset.LowPart, biod.length);
1830
1831             code = StartRXAFS_FetchData64(rxcallp, &tfid, biod.offset.QuadPart, biod.length);
1832
1833             if (code == 0) {
1834                 temp = rx_Read32(rxcallp, &nbytes_hi);
1835                 if (temp == sizeof(afs_int32)) {
1836                     nbytes_hi = ntohl(nbytes_hi);
1837                 } else {
1838                     nbytes_hi = 0;
1839                     code = rxcallp->error;
1840                     code1 = rx_EndCall(rxcallp, code);
1841                     rxcallp = NULL;
1842                 }
1843             }
1844         } else {
1845             call_was_64bit = 0;
1846         }
1847
1848         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
1849             if (require_64bit_ops) {
1850                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
1851                 code = CM_ERROR_TOOBIG;
1852             } else {
1853                 if (!rxcallp) {
1854                     rxconnp = cm_GetRxConn(connp);
1855                     rxcallp = rx_NewCall(rxconnp);
1856                     rx_PutConnection(rxconnp);
1857                 }
1858
1859                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
1860                          scp, biod.offset.LowPart, biod.length);
1861
1862                 code = StartRXAFS_FetchData(rxcallp, &tfid, biod.offset.LowPart,
1863                                             biod.length);
1864
1865                 SET_SERVERHASNO64BIT(connp);
1866             }
1867         }
1868
1869         if (code == 0) {
1870             temp  = rx_Read32(rxcallp, &nbytes);
1871             if (temp == sizeof(afs_int32)) {
1872                 nbytes = ntohl(nbytes);
1873                 FillInt64(length_found, nbytes_hi, nbytes);
1874                 if (length_found > biod.length) {
1875                     /*
1876                      * prior to 1.4.12 and 1.5.65 the file server would return
1877                      * (filesize - offset) if the requested offset was greater than
1878                      * the filesize.  The correct return value would have been zero.
1879                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
1880                      * is a race between two RPCs issues by this cache manager, the
1881                      * correct thing will happen the second time.
1882                      */
1883                     osi_Log0(afsd_logp, "cm_GetBuffer length_found > biod.length");
1884                     fs_fetchdata_offset_bug = 1;
1885                 }
1886             } else {
1887                 osi_Log1(afsd_logp, "cm_GetBuffer rx_Read32 returns %d != 4", temp);
1888                 code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
1889             }
1890         }
1891         /* for the moment, nbytes_hi will always be 0 if code == 0
1892            because biod.length is a 32-bit quantity. */
1893
1894         if (code == 0) {
1895             qdp = biod.bufListEndp;
1896             if (qdp) {
1897                 tbufp = osi_GetQData(qdp);
1898                 bufferp = tbufp->datap;
1899                 buffer_offset = 0;
1900             }
1901             else
1902                 bufferp = NULL;
1903
1904             /* fill length_found of data from the pipe into the pages.
1905              * When we stop, qdp will point at the last page we're
1906              * dealing with, and bufferp will tell us where we
1907              * stopped.  We'll need this info below when we clear
1908              * the remainder of the last page out (and potentially
1909              * clear later pages out, if we fetch past EOF).
1910              */
1911             while (length_found > 0) {
1912 #ifdef USE_RX_IOVEC
1913                 struct iovec tiov[RX_MAXIOVECS];
1914                 afs_int32 tnio, iov, iov_offset;
1915
1916                 temp = rx_Readv(rxcallp, tiov, &tnio, RX_MAXIOVECS, length_found);
1917                 osi_Log1(afsd_logp, "cm_GetBuffer rx_Readv returns %d", temp);
1918                 if (temp != length_found && temp < cm_data.buf_blockSize) {
1919                     /*
1920                      * If the file server returned (filesize - offset),
1921                      * then the first rx_Read will return zero octets of data.
1922                      * If it does, do not treat it as an error.  Correct the
1923                      * length_found and continue as if the file server said
1924                      * it was sending us zero octets of data.
1925                      */
1926                     if (fs_fetchdata_offset_bug && first_read)
1927                         length_found = 0;
1928                     else
1929                         code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
1930                     break;
1931                 }
1932
1933                 iov = 0;
1934                 iov_offset = 0;
1935                 rbytes = temp;
1936
1937                 while (rbytes > 0) {
1938                     afs_int32 len;
1939
1940                     osi_assertx(bufferp != NULL, "null cm_buf_t");
1941
1942                     len = MIN(tiov[iov].iov_len - iov_offset, cm_data.buf_blockSize - buffer_offset);
1943                     memcpy(bufferp + buffer_offset, tiov[iov].iov_base + iov_offset, len);
1944                     iov_offset += len;
1945                     buffer_offset += len;
1946                     rbytes -= len;
1947
1948                     if (iov_offset == tiov[iov].iov_len) {
1949                         iov++;
1950                         iov_offset = 0;
1951                     }
1952
1953                     if (buffer_offset == cm_data.buf_blockSize) {
1954                         /* allow read-while-fetching.
1955                         * if this is the last buffer, clear the
1956                         * PREFETCHING flag, so the reader waiting for
1957                         * this buffer will start a prefetch.
1958                         */
1959                         _InterlockedOr(&tbufp->cmFlags, CM_BUF_CMFULLYFETCHED);
1960                         lock_ObtainWrite(&scp->rw);
1961                         if (scp->flags & CM_SCACHEFLAG_WAITING) {
1962                             osi_Log1(afsd_logp, "CM GetBuffer Waking scp 0x%p", scp);
1963                             osi_Wakeup((LONG_PTR) &scp->flags);
1964                         }
1965                         if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
1966                             osi_hyper_t tlength = ConvertLongToLargeInteger(biod.length);
1967                             *cpffp = 1;
1968                             cm_ClearPrefetchFlag(0, scp, &biod.offset, &tlength);
1969                         }
1970                         lock_ReleaseWrite(&scp->rw);
1971
1972                         /* Advance the buffer */
1973                         qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1974                         if (qdp) {
1975                             tbufp = osi_GetQData(qdp);
1976                             bufferp = tbufp->datap;
1977                             buffer_offset = 0;
1978                         }
1979                         else
1980                             bufferp = NULL;
1981                     }
1982                 }
1983
1984                 length_found -= temp;
1985 #else /* USE_RX_IOVEC */
1986                 /* assert that there are still more buffers;
1987                  * our check above for length_found being less than
1988                  * biod.length should ensure this.
1989                  */
1990                 osi_assertx(bufferp != NULL, "null cm_buf_t");
1991
1992                 /* read rbytes of data */
1993                 rbytes = (afs_uint32)(length_found > cm_data.buf_blockSize ? cm_data.buf_blockSize : length_found);
1994                 temp = rx_Read(rxcallp, bufferp, rbytes);
1995                 if (temp < rbytes) {
1996                     /*
1997                      * If the file server returned (filesize - offset),
1998                      * then the first rx_Read will return zero octets of data.
1999                      * If it does, do not treat it as an error.  Correct the
2000                      * length_found and continue as if the file server said
2001                      * it was sending us zero octets of data.
2002                      */
2003                     if (fs_fetchdata_offset_bug && first_read)
2004                         length_found = 0;
2005                     else
2006                         code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
2007                     break;
2008                 }
2009                 first_read = 0;
2010
2011                 /* allow read-while-fetching.
2012                  * if this is the last buffer, clear the
2013                  * PREFETCHING flag, so the reader waiting for
2014                  * this buffer will start a prefetch.
2015                  */
2016                 _InterlockedOr(&tbufp->cmFlags, CM_BUF_CMFULLYFETCHED);
2017                 lock_ObtainWrite(&scp->rw);
2018                 if (scp->flags & CM_SCACHEFLAG_WAITING) {
2019                     osi_Log1(afsd_logp, "CM GetBuffer Waking scp 0x%p", scp);
2020                     osi_Wakeup((LONG_PTR) &scp->flags);
2021                 }
2022                 if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
2023                     osi_hyper_t tlength = ConvertLongToLargeInteger(biod.length);
2024                     *cpffp = 1;
2025                     cm_ClearPrefetchFlag(0, scp, &biod.offset, &tlength);
2026                 }
2027                 lock_ReleaseWrite(&scp->rw);
2028
2029                 /* and adjust counters */
2030                 length_found -= temp;
2031
2032                 /* and move to the next buffer */
2033                 if (length_found != 0) {
2034                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2035                     if (qdp) {
2036                         tbufp = osi_GetQData(qdp);
2037                         bufferp = tbufp->datap;
2038                     }
2039                     else
2040                         bufferp = NULL;
2041                 } else
2042                     bufferp += temp;
2043 #endif /* USE_RX_IOVEC */
2044             }
2045
2046             /* zero out remainder of last pages, in case we are
2047              * fetching past EOF.  We were fetching an integral #
2048              * of pages, but stopped, potentially in the middle of
2049              * a page.  Zero the remainder of that page, and then
2050              * all of the rest of the pages.
2051              */
2052 #ifdef USE_RX_IOVEC
2053             rbytes = cm_data.buf_blockSize - buffer_offset;
2054             bufferp = tbufp->datap + buffer_offset;
2055 #else /* USE_RX_IOVEC */
2056             /* bytes fetched */
2057             osi_assertx((bufferp - tbufp->datap) < LONG_MAX, "data >= LONG_MAX");
2058             rbytes = (long) (bufferp - tbufp->datap);
2059
2060             /* bytes left to zero */
2061             rbytes = cm_data.buf_blockSize - rbytes;
2062 #endif /* USE_RX_IOVEC */
2063             while(qdp) {
2064                 if (rbytes != 0)
2065                     memset(bufferp, 0, rbytes);
2066                 qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2067                 if (qdp == NULL)
2068                     break;
2069                 tbufp = osi_GetQData(qdp);
2070                 bufferp = tbufp->datap;
2071                 /* bytes to clear in this page */
2072                 rbytes = cm_data.buf_blockSize;
2073             }
2074         }
2075
2076         if (code == 0) {
2077             if (call_was_64bit)
2078                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
2079             else
2080                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
2081         } else {
2082             if (call_was_64bit)
2083                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
2084             else
2085                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
2086         }
2087
2088         if (rxcallp)
2089             code1 = rx_EndCall(rxcallp, code);
2090
2091         if (code1 == RXKADUNKNOWNKEY)
2092             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
2093
2094         /* If we are avoiding a file server bug, ignore the error state */
2095         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
2096             /* Clone the current status info and clear the error state */
2097             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
2098             if (scp_locked) {
2099                 lock_ReleaseWrite(&scp->rw);
2100                 scp_locked = 0;
2101             }
2102             code = 0;
2103         /* Prefer the error value from FetchData over rx_EndCall */
2104         } else if (code == 0 && code1 != 0)
2105             code = code1;
2106         osi_Log0(afsd_logp, "CALL FetchData DONE");
2107
2108     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
2109
2110   fetchingcompleted:
2111     code = cm_MapRPCError(code, reqp);
2112
2113     if (!scp_locked)
2114         lock_ObtainWrite(&scp->rw);
2115
2116     /* we know that no one else has changed the buffer, since we still have
2117      * the fetching flag on the buffers, and we have the scp locked again.
2118      * Copy in the version # into the buffer if we got code 0 back from the
2119      * read.
2120      */
2121     if (code == 0) {
2122         for(qdp = biod.bufListp;
2123              qdp;
2124              qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
2125             tbufp = osi_GetQData(qdp);
2126             tbufp->dataVersion = afsStatus.dataVersionHigh;
2127             tbufp->dataVersion <<= 32;
2128             tbufp->dataVersion |= afsStatus.DataVersion;
2129
2130 #ifdef DISKCACHE95
2131             /* write buffer out to disk cache */
2132             diskcache_Update(tbufp->dcp, tbufp->datap, cm_data.buf_blockSize,
2133                               tbufp->dataVersion);
2134 #endif /* DISKCACHE95 */
2135         }
2136     }
2137
2138     /* release scatter/gather I/O structure (buffers, locks) */
2139     cm_ReleaseBIOD(&biod, 0, code, 1);
2140
2141     if (code == 0)
2142         cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, CM_MERGEFLAG_FETCHDATA);
2143
2144     return code;
2145 }
2146
2147 /*
2148  * Similar to cm_GetBuffer but doesn't use an allocated cm_buf_t object.
2149  * Instead the data is read from the file server and copied directly into
2150  * a provided buffer.  Called with scp locked. The scp is locked on return.
2151  */
2152 long cm_GetData(cm_scache_t *scp, osi_hyper_t *offsetp, char *datap, int data_length,
2153                 cm_user_t *userp, cm_req_t *reqp)
2154 {
2155     long code=0, code1=0;
2156     afs_uint32 nbytes;                  /* bytes in transfer */
2157     afs_uint32 nbytes_hi = 0;           /* high-order 32 bits of bytes in transfer */
2158     afs_uint64 length_found = 0;
2159     char *bufferp = datap;
2160     afs_uint32 buffer_offset = 0;
2161     long rbytes;                        /* bytes in rx_Read call */
2162     long temp;
2163     AFSFetchStatus afsStatus;
2164     AFSCallBack callback;
2165     AFSVolSync volSync;
2166     AFSFid tfid;
2167     struct rx_call *rxcallp;
2168     struct rx_connection *rxconnp;
2169     cm_conn_t *connp;
2170     int getroot;
2171     afs_int32 t1,t2;
2172     int require_64bit_ops = 0;
2173     int call_was_64bit = 0;
2174     int fs_fetchdata_offset_bug = 0;
2175     int first_read = 1;
2176     int scp_locked = 1;
2177
2178     memset(&volSync, 0, sizeof(volSync));
2179
2180     /* now, the buffer may or may not be filled with good data (buf_GetNewLocked
2181      * drops lots of locks, and may indeed return a properly initialized
2182      * buffer, although more likely it will just return a new, empty, buffer.
2183      */
2184
2185 #ifdef AFS_FREELANCE_CLIENT
2186
2187     // yj: if they're trying to get the /afs directory, we need to
2188     // handle it differently, since it's local rather than on any
2189     // server
2190
2191     getroot = (scp==cm_data.rootSCachep);
2192     if (getroot)
2193         osi_Log1(afsd_logp,"GetBuffer returns cm_data.rootSCachep=%x",cm_data.rootSCachep);
2194 #endif
2195
2196     cm_AFSFidFromFid(&tfid, &scp->fid);
2197
2198     if (LargeIntegerGreaterThan(LargeIntegerAdd(*offsetp,
2199                                                 ConvertLongToLargeInteger(data_length)),
2200                                 ConvertLongToLargeInteger(LONG_MAX))) {
2201         require_64bit_ops = 1;
2202     }
2203
2204     osi_Log2(afsd_logp, "cm_GetData: fetching data scp %p DV 0x%x", scp, scp->dataVersion);
2205
2206 #ifdef AFS_FREELANCE_CLIENT
2207
2208     // yj code
2209     // if getroot then we don't need to make any calls
2210     // just return fake data
2211
2212     if (cm_freelanceEnabled && getroot) {
2213         // setup the fake status
2214         afsStatus.InterfaceVersion = 0x1;
2215         afsStatus.FileType = 0x2;
2216         afsStatus.LinkCount = scp->linkCount;
2217         afsStatus.Length = cm_fakeDirSize;
2218         afsStatus.DataVersion = (afs_uint32)(cm_data.fakeDirVersion & 0xFFFFFFFF);
2219         afsStatus.Author = 0x1;
2220         afsStatus.Owner = 0x0;
2221         afsStatus.CallerAccess = 0x9;
2222         afsStatus.AnonymousAccess = 0x9;
2223         afsStatus.UnixModeBits = 0x1ff;
2224         afsStatus.ParentVnode = 0x1;
2225         afsStatus.ParentUnique = 0x1;
2226         afsStatus.ResidencyMask = 0;
2227         afsStatus.ClientModTime = (afs_uint32)FakeFreelanceModTime;
2228         afsStatus.ServerModTime = (afs_uint32)FakeFreelanceModTime;
2229         afsStatus.Group = 0;
2230         afsStatus.SyncCounter = 0;
2231         afsStatus.dataVersionHigh = (afs_uint32)(cm_data.fakeDirVersion >> 32);
2232         afsStatus.lockCount = 0;
2233         afsStatus.Length_hi = 0;
2234         afsStatus.errorCode = 0;
2235         memset(&volSync, 0, sizeof(volSync));
2236
2237         // once we're done setting up the status info,
2238         // we just fill the buffer pages with fakedata
2239         // from cm_FakeRootDir. Extra pages are set to
2240         // 0.
2241
2242         lock_ObtainMutex(&cm_Freelance_Lock);
2243         t1 = offsetp->LowPart;
2244         memset(datap, 0, data_length);
2245         t2 = cm_fakeDirSize - t1;
2246         if (t2 > data_length)
2247             t2 = data_length;
2248         if (t2 > 0)
2249             memcpy(datap, cm_FakeRootDir+t1, t2);
2250         lock_ReleaseMutex(&cm_Freelance_Lock);
2251
2252         // once we're done, we skip over the part of the
2253         // code that does the ACTUAL fetching of data for
2254         // real files
2255
2256         goto fetchingcompleted;
2257     }
2258
2259 #endif /* AFS_FREELANCE_CLIENT */
2260
2261     if (scp_locked) {
2262         lock_ReleaseWrite(&scp->rw);
2263         scp_locked = 0;
2264     }
2265
2266     /* now make the call */
2267     do {
2268         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2269         if (code)
2270             continue;
2271
2272         rxconnp = cm_GetRxConn(connp);
2273         rxcallp = rx_NewCall(rxconnp);
2274         rx_PutConnection(rxconnp);
2275
2276         nbytes = nbytes_hi = 0;
2277
2278         if (SERVERHAS64BIT(connp)) {
2279             call_was_64bit = 1;
2280
2281             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
2282                      scp, offsetp->HighPart, offsetp->LowPart, data_length);
2283
2284             code = StartRXAFS_FetchData64(rxcallp, &tfid, offsetp->QuadPart, data_length);
2285
2286             if (code == 0) {
2287                 temp = rx_Read32(rxcallp, &nbytes_hi);
2288                 if (temp == sizeof(afs_int32)) {
2289                     nbytes_hi = ntohl(nbytes_hi);
2290                 } else {
2291                     nbytes_hi = 0;
2292                     code = rxcallp->error;
2293                     code1 = rx_EndCall(rxcallp, code);
2294                     rxcallp = NULL;
2295                 }
2296             }
2297         } else {
2298             call_was_64bit = 0;
2299         }
2300
2301         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
2302             if (require_64bit_ops) {
2303                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
2304                 code = CM_ERROR_TOOBIG;
2305             } else {
2306                 if (!rxcallp) {
2307                     rxconnp = cm_GetRxConn(connp);
2308                     rxcallp = rx_NewCall(rxconnp);
2309                     rx_PutConnection(rxconnp);
2310                 }
2311
2312                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
2313                          scp, offsetp->LowPart, data_length);
2314
2315                 code = StartRXAFS_FetchData(rxcallp, &tfid, offsetp->LowPart, data_length);
2316
2317                 SET_SERVERHASNO64BIT(connp);
2318             }
2319         }
2320
2321         if (code == 0) {
2322             temp  = rx_Read32(rxcallp, &nbytes);
2323             if (temp == sizeof(afs_int32)) {
2324                 nbytes = ntohl(nbytes);
2325                 FillInt64(length_found, nbytes_hi, nbytes);
2326                 if (length_found > data_length) {
2327                     /*
2328                      * prior to 1.4.12 and 1.5.65 the file server would return
2329                      * (filesize - offset) if the requested offset was greater than
2330                      * the filesize.  The correct return value would have been zero.
2331                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
2332                      * is a race between two RPCs issues by this cache manager, the
2333                      * correct thing will happen the second time.
2334                      */
2335                     osi_Log0(afsd_logp, "cm_GetData length_found > data_length");
2336                     fs_fetchdata_offset_bug = 1;
2337                 }
2338             } else {
2339                 osi_Log1(afsd_logp, "cm_GetData rx_Read32 returns %d != 4", temp);
2340                 code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
2341             }
2342         }
2343         /* for the moment, nbytes_hi will always be 0 if code == 0
2344            because data_length is a 32-bit quantity. */
2345
2346         if (code == 0) {
2347             /* fill length_found of data from the pipe into the pages.
2348              * When we stop, qdp will point at the last page we're
2349              * dealing with, and bufferp will tell us where we
2350              * stopped.  We'll need this info below when we clear
2351              * the remainder of the last page out (and potentially
2352              * clear later pages out, if we fetch past EOF).
2353              */
2354             while (length_found > 0) {
2355 #ifdef USE_RX_IOVEC
2356                 struct iovec tiov[RX_MAXIOVECS];
2357                 afs_int32 tnio, iov, iov_offset;
2358
2359                 temp = rx_Readv(rxcallp, tiov, &tnio, RX_MAXIOVECS, length_found);
2360                 osi_Log1(afsd_logp, "cm_GetData rx_Readv returns %d", temp);
2361                 if (temp != length_found && temp < data_length) {
2362                     /*
2363                      * If the file server returned (filesize - offset),
2364                      * then the first rx_Read will return zero octets of data.
2365                      * If it does, do not treat it as an error.  Correct the
2366                      * length_found and continue as if the file server said
2367                      * it was sending us zero octets of data.
2368                      */
2369                     if (fs_fetchdata_offset_bug && first_read)
2370                         length_found = 0;
2371                     else
2372                         code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
2373                     break;
2374                 }
2375
2376                 iov = 0;
2377                 iov_offset = 0;
2378                 rbytes = temp;
2379
2380                 while (rbytes > 0) {
2381                     afs_int32 len;
2382
2383                     osi_assertx(bufferp != NULL, "null cm_buf_t");
2384
2385                     len = MIN(tiov[iov].iov_len - iov_offset, data_length - buffer_offset);
2386                     memcpy(bufferp + buffer_offset, tiov[iov].iov_base + iov_offset, len);
2387                     iov_offset += len;
2388                     buffer_offset += len;
2389                     rbytes -= len;
2390
2391                     if (iov_offset == tiov[iov].iov_len) {
2392                         iov++;
2393                         iov_offset = 0;
2394                     }
2395                 }
2396
2397                 length_found -= temp;
2398 #else /* USE_RX_IOVEC */
2399                 /* assert that there are still more buffers;
2400                  * our check above for length_found being less than
2401                  * data_length should ensure this.
2402                  */
2403                 osi_assertx(bufferp != NULL, "null cm_buf_t");
2404
2405                 /* read rbytes of data */
2406                 rbytes = (afs_uint32)(length_found > data_length ? data_length : length_found);
2407                 temp = rx_Read(rxcallp, bufferp, rbytes);
2408                 if (temp < rbytes) {
2409                     /*
2410                      * If the file server returned (filesize - offset),
2411                      * then the first rx_Read will return zero octets of data.
2412                      * If it does, do not treat it as an error.  Correct the
2413                      * length_found and continue as if the file server said
2414                      * it was sending us zero octets of data.
2415                      */
2416                     if (fs_fetchdata_offset_bug && first_read)
2417                         length_found = 0;
2418                     else
2419                         code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
2420                     break;
2421                 }
2422                 first_read = 0;
2423
2424                 /* and adjust counters */
2425                 length_found -= temp;
2426 #endif /* USE_RX_IOVEC */
2427             }
2428
2429             /* zero out remainder of last pages, in case we are
2430              * fetching past EOF.  We were fetching an integral #
2431              * of pages, but stopped, potentially in the middle of
2432              * a page.  Zero the remainder of that page, and then
2433              * all of the rest of the pages.
2434              */
2435 #ifdef USE_RX_IOVEC
2436             rbytes = data_length - buffer_offset;
2437             bufferp = datap + buffer_offset;
2438 #else /* USE_RX_IOVEC */
2439             /* bytes fetched */
2440             osi_assertx((bufferp - datap) < LONG_MAX, "data >= LONG_MAX");
2441             rbytes = (long) (bufferp - datap);
2442
2443             /* bytes left to zero */
2444             rbytes = data_length - rbytes;
2445 #endif /* USE_RX_IOVEC */
2446             if (rbytes != 0)
2447                 memset(bufferp, 0, rbytes);
2448         }
2449
2450         if (code == 0) {
2451             if (call_was_64bit)
2452                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
2453             else
2454                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
2455         } else {
2456             if (call_was_64bit)
2457                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
2458             else
2459                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
2460         }
2461
2462         if (rxcallp)
2463             code1 = rx_EndCall(rxcallp, code);
2464
2465         if (code1 == RXKADUNKNOWNKEY)
2466             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
2467
2468         /* If we are avoiding a file server bug, ignore the error state */
2469         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
2470             /* Clone the current status info and clear the error state */
2471             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
2472             if (scp_locked) {
2473                 lock_ReleaseWrite(&scp->rw);
2474                 scp_locked = 0;
2475             }
2476             code = 0;
2477         /* Prefer the error value from FetchData over rx_EndCall */
2478         } else if (code == 0 && code1 != 0)
2479             code = code1;
2480         osi_Log0(afsd_logp, "CALL FetchData DONE");
2481
2482     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
2483
2484   fetchingcompleted:
2485     code = cm_MapRPCError(code, reqp);
2486
2487     if (!scp_locked)
2488         lock_ObtainWrite(&scp->rw);
2489
2490     if (code == 0)
2491         cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, CM_MERGEFLAG_FETCHDATA);
2492
2493     return code;
2494 }