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