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