4eb008597682c664baf285563ac4fa42ced12b23
[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, NULL, 1, &outStatus, &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         code = 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, NULL, 1, &outStatus, &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         code = 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 (!osi_QIsEmpty(&scp->waitQueueH)) {
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                     case EIO:
1538                         /*
1539                          * Apply the fatal error to this buffer.
1540                          */
1541                         _InterlockedAnd(&bufp->flags, ~CM_BUF_DIRTY);
1542                         _InterlockedOr(&bufp->flags, CM_BUF_ERROR);
1543                         bufp->dirty_offset = 0;
1544                         bufp->dirty_length = 0;
1545                         bufp->error = code;
1546                         bufp->dataVersion = CM_BUF_VERSION_BAD;
1547                         bufp->dirtyCounter++;
1548                         reportErrorToRedir = 1;
1549                         break;
1550                     case CM_ERROR_TIMEDOUT:
1551                     case CM_ERROR_ALLDOWN:
1552                     case CM_ERROR_ALLBUSY:
1553                     case CM_ERROR_ALLOFFLINE:
1554                     case CM_ERROR_CLOCKSKEW:
1555                     default:
1556                         /* do not mark the buffer in error state but do
1557                         * not attempt to complete the rest either.
1558                         */
1559                         break;
1560                     }
1561                 } else {
1562                     _InterlockedAnd(&bufp->flags, ~(CM_BUF_WRITING | CM_BUF_DIRTY));
1563                     bufp->dirty_offset = bufp->dirty_length = 0;
1564                 }
1565             }
1566
1567             if (!scp_locked)
1568                 lock_ReleaseWrite(&scp->rw);
1569             lock_ReleaseMutex(&bufp->mx);
1570             buf_Release(bufp);
1571             bufp = NULL;
1572         }
1573
1574         if (RDR_Initialized && reportErrorToRedir) {
1575             DWORD status;
1576             smb_MapNTError(cm_MapRPCError(code, biop->reqp), &status, TRUE);
1577             RDR_SetFileStatus( &scp->fid, &biop->userp->authgroup, status);
1578         }
1579     } else {
1580         if (!scp_locked)
1581             lock_ObtainWrite(&scp->rw);
1582         cm_SyncOpDone(scp, NULL, flags);
1583         if (!scp_locked)
1584             lock_ReleaseWrite(&scp->rw);
1585     }
1586
1587     /* clean things out */
1588     biop->bufListp = NULL;
1589     biop->bufListEndp = NULL;
1590 }
1591
1592 static int
1593 cm_CloneStatus(cm_scache_t *scp, cm_user_t *userp, int scp_locked,
1594                AFSFetchStatus *afsStatusp, AFSVolSync *volSyncp)
1595 {
1596     // setup the status based upon the scp data
1597     afsStatusp->InterfaceVersion = 0x1;
1598     switch (scp->fileType) {
1599     case CM_SCACHETYPE_FILE:
1600         afsStatusp->FileType = File;
1601         break;
1602     case CM_SCACHETYPE_DIRECTORY:
1603         afsStatusp->FileType = Directory;
1604         break;
1605     case CM_SCACHETYPE_MOUNTPOINT:
1606         afsStatusp->FileType = SymbolicLink;
1607         break;
1608     case CM_SCACHETYPE_SYMLINK:
1609     case CM_SCACHETYPE_DFSLINK:
1610         afsStatusp->FileType = SymbolicLink;
1611         break;
1612     default:
1613         afsStatusp->FileType = -1;    /* an invalid value */
1614     }
1615     afsStatusp->LinkCount = scp->linkCount;
1616     afsStatusp->Length = scp->length.LowPart;
1617     afsStatusp->DataVersion = (afs_uint32)(scp->dataVersion & MAX_AFS_UINT32);
1618     afsStatusp->Author = 0x1;
1619     afsStatusp->Owner = scp->owner;
1620     if (!scp_locked) {
1621         lock_ObtainWrite(&scp->rw);
1622         scp_locked = 1;
1623     }
1624     if (cm_FindACLCache(scp, userp, &afsStatusp->CallerAccess))
1625         afsStatusp->CallerAccess = scp->anyAccess;
1626     afsStatusp->AnonymousAccess = scp->anyAccess;
1627     afsStatusp->UnixModeBits = scp->unixModeBits;
1628     afsStatusp->ParentVnode = scp->parentVnode;
1629     afsStatusp->ParentUnique = scp->parentUnique;
1630     afsStatusp->ResidencyMask = 0;
1631     afsStatusp->ClientModTime = scp->clientModTime;
1632     afsStatusp->ServerModTime = scp->serverModTime;
1633     afsStatusp->Group = scp->group;
1634     afsStatusp->SyncCounter = 0;
1635     afsStatusp->dataVersionHigh = (afs_uint32)(scp->dataVersion >> 32);
1636     afsStatusp->lockCount = 0;
1637     afsStatusp->Length_hi = scp->length.HighPart;
1638     afsStatusp->errorCode = 0;
1639
1640     volSyncp->spare1 = scp->volumeCreationDate;
1641
1642     return scp_locked;
1643 }
1644
1645 /* Fetch a buffer.  Called with scp locked.
1646  * The scp is locked on return.
1647  */
1648 long cm_GetBuffer(cm_scache_t *scp, cm_buf_t *bufp, int *cpffp, cm_user_t *userp,
1649                   cm_req_t *reqp)
1650 {
1651     long code=0, code1=0;
1652     afs_uint32 nbytes;                  /* bytes in transfer */
1653     afs_uint32 nbytes_hi = 0;            /* high-order 32 bits of bytes in transfer */
1654     afs_uint64 length_found = 0;
1655     long rbytes;                        /* bytes in rx_Read call */
1656     long temp;
1657     AFSFetchStatus afsStatus;
1658     AFSCallBack callback;
1659     AFSVolSync volSync;
1660     char *bufferp;
1661     afs_uint32 buffer_offset;
1662     cm_buf_t *tbufp;                    /* buf we're filling */
1663     osi_queueData_t *qdp;               /* q element we're scanning */
1664     AFSFid tfid;
1665     struct rx_call *rxcallp;
1666     struct rx_connection *rxconnp;
1667     cm_bulkIO_t biod;           /* bulk IO descriptor */
1668     cm_conn_t *connp;
1669     int getroot;
1670     afs_int32 t1,t2;
1671     int require_64bit_ops = 0;
1672     int call_was_64bit = 0;
1673     int fs_fetchdata_offset_bug = 0;
1674     int first_read = 1;
1675     int scp_locked = 1;
1676
1677     memset(&afsStatus, 0, sizeof(afsStatus));
1678     memset(&callback, 0, sizeof(callback));
1679     memset(&volSync, 0, sizeof(volSync));
1680
1681     /* now, the buffer may or may not be filled with good data (buf_GetNewLocked
1682      * drops lots of locks, and may indeed return a properly initialized
1683      * buffer, although more likely it will just return a new, empty, buffer.
1684      */
1685
1686 #ifdef AFS_FREELANCE_CLIENT
1687
1688     // yj: if they're trying to get the /afs directory, we need to
1689     // handle it differently, since it's local rather than on any
1690     // server
1691
1692     getroot = (scp==cm_data.rootSCachep);
1693     if (getroot)
1694         osi_Log1(afsd_logp,"GetBuffer returns cm_data.rootSCachep=%x",cm_data.rootSCachep);
1695 #endif
1696
1697     if (cm_HaveCallback(scp) && bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow) {
1698         /* We already have this buffer don't do extra work */
1699         return 0;
1700     }
1701
1702     cm_AFSFidFromFid(&tfid, &scp->fid);
1703
1704     code = cm_SetupFetchBIOD(scp, &bufp->offset, &biod, userp, reqp);
1705     if (code) {
1706         /* couldn't even get the first page setup properly */
1707         osi_Log1(afsd_logp, "cm_GetBuffer: SetupFetchBIOD failure code %d", code);
1708         return code;
1709     }
1710
1711     /* once we get here, we have the callback in place, we know that no one
1712      * is fetching the data now.  Check one last time that we still have
1713      * the wrong data, and then fetch it if we're still wrong.
1714      *
1715      * We can lose a race condition and end up with biod.length zero, in
1716      * which case we just retry.
1717      */
1718
1719     if (bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow) {
1720         /* We obtained the buffer while we were waiting */
1721         goto release_biod;
1722     }
1723
1724     if (biod.length == 0) {
1725         osi_Log2(afsd_logp, "cm_GetBuffer BIOD length 0 scp 0x%p bufp 0x%p",
1726                  scp, bufp);
1727         goto release_biod;
1728     }
1729
1730     /* Check for buffers we can fill locally */
1731     for (qdp = biod.bufListEndp;
1732           qdp;
1733           qdp = (osi_queueData_t *) osi_QPrev(&qdp->q)) {
1734         tbufp = osi_GetQData(qdp);
1735
1736         if ( tbufp->dataVersion == CM_BUF_VERSION_BAD ||
1737              tbufp->dataVersion < scp->bufDataVersionLow ||
1738              tbufp->dataVersion > scp->dataVersion) {
1739
1740             osi_Log4(afsd_logp, "cm_GetBuffer bufp 0x%p DVs 0x%x != (0x%x -> 0x%x)",
1741                      tbufp, tbufp->dataVersion, scp->bufDataVersionLow, scp->dataVersion);
1742
1743             if (LargeIntegerGreaterThanOrEqualTo(tbufp->offset, scp->length))
1744             {
1745                 if (tbufp->dataVersion == CM_BUF_VERSION_BAD)
1746                     memset(tbufp->datap, 0, cm_data.buf_blockSize);
1747                 tbufp->dataVersion = scp->dataVersion;
1748             }
1749
1750             if ((scp->mask & CM_SCACHEMASK_TRUNCPOS) &&
1751                  LargeIntegerGreaterThanOrEqualTo(tbufp->offset, scp->truncPos)) {
1752                 memset(tbufp->datap, 0, cm_data.buf_blockSize);
1753                 tbufp->dataVersion = scp->dataVersion;
1754             }
1755         }
1756     }
1757
1758     if (bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow) {
1759         /* We locally populated the buffer we wanted */
1760         goto release_biod;
1761     }
1762
1763     InterlockedIncrement(&scp->activeRPCs);
1764     lock_ReleaseWrite(&scp->rw);
1765     scp_locked = 0;
1766
1767     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
1768                                                 ConvertLongToLargeInteger(biod.length)),
1769                                 ConvertLongToLargeInteger(LONG_MAX))) {
1770         require_64bit_ops = 1;
1771     }
1772
1773     osi_Log2(afsd_logp, "cm_GetBuffer: fetching data scp %p bufp %p", scp, bufp);
1774     osi_Log3(afsd_logp, "cm_GetBuffer: fetching data scpDV 0x%x scpDVLow 0x%x bufDV 0x%x",
1775              scp->dataVersion, scp->bufDataVersionLow, bufp->dataVersion);
1776
1777 #ifdef AFS_FREELANCE_CLIENT
1778
1779     // yj code
1780     // if getroot then we don't need to make any calls
1781     // just return fake data
1782
1783     if (cm_freelanceEnabled && getroot) {
1784         // setup the fake status
1785         afsStatus.InterfaceVersion = 0x1;
1786         afsStatus.FileType = 0x2;
1787         afsStatus.LinkCount = scp->linkCount;
1788         afsStatus.Length = cm_fakeDirSize;
1789         afsStatus.DataVersion = (afs_uint32)(cm_data.fakeDirVersion & 0xFFFFFFFF);
1790         afsStatus.Author = 0x1;
1791         afsStatus.Owner = 0x0;
1792         afsStatus.CallerAccess = 0x9;
1793         afsStatus.AnonymousAccess = 0x9;
1794         afsStatus.UnixModeBits = 0x1ff;
1795         afsStatus.ParentVnode = 0x1;
1796         afsStatus.ParentUnique = 0x1;
1797         afsStatus.ResidencyMask = 0;
1798         afsStatus.ClientModTime = (afs_uint32)FakeFreelanceModTime;
1799         afsStatus.ServerModTime = (afs_uint32)FakeFreelanceModTime;
1800         afsStatus.Group = 0;
1801         afsStatus.SyncCounter = 0;
1802         afsStatus.dataVersionHigh = (afs_uint32)(cm_data.fakeDirVersion >> 32);
1803         afsStatus.lockCount = 0;
1804         afsStatus.Length_hi = 0;
1805         afsStatus.errorCode = 0;
1806         memset(&volSync, 0, sizeof(volSync));
1807
1808         // once we're done setting up the status info,
1809         // we just fill the buffer pages with fakedata
1810         // from cm_FakeRootDir. Extra pages are set to
1811         // 0.
1812
1813         lock_ObtainMutex(&cm_Freelance_Lock);
1814         t1 = bufp->offset.LowPart;
1815         qdp = biod.bufListEndp;
1816         while (qdp) {
1817             tbufp = osi_GetQData(qdp);
1818             bufferp=tbufp->datap;
1819             memset(bufferp, 0, cm_data.buf_blockSize);
1820             t2 = cm_fakeDirSize - t1;
1821             if (t2> (afs_int32)cm_data.buf_blockSize)
1822                 t2=cm_data.buf_blockSize;
1823             if (t2 > 0) {
1824                 memcpy(bufferp, cm_FakeRootDir+t1, t2);
1825             } else {
1826                 t2 = 0;
1827             }
1828             t1+=t2;
1829             qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1830
1831         }
1832         lock_ReleaseMutex(&cm_Freelance_Lock);
1833
1834         // once we're done, we skip over the part of the
1835         // code that does the ACTUAL fetching of data for
1836         // real files
1837
1838         goto fetchingcompleted;
1839     }
1840
1841 #endif /* AFS_FREELANCE_CLIENT */
1842
1843     /*
1844      * if the requested offset is greater than the file length,
1845      * the file server will return zero bytes of data and the
1846      * current status for the file which we already have since
1847      * we have just obtained a callback.  Instead, we can avoid
1848      * the network round trip by allocating zeroed buffers and
1849      * faking the status info.
1850      */
1851     if (biod.offset.QuadPart >= scp->serverLength.QuadPart ||
1852         ((scp->mask & CM_SCACHEMASK_TRUNCPOS) && biod.offset.QuadPart > scp->truncPos.QuadPart)) {
1853         osi_Log5(afsd_logp, "SKIP FetchData64 scp 0x%p, off 0x%x:%08x > length 0x%x:%08x",
1854                  scp, biod.offset.HighPart, biod.offset.LowPart,
1855                  scp->length.HighPart, scp->length.LowPart);
1856
1857         /* Clone the current status info */
1858         scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
1859
1860         /* status info complete, fill pages with zeros */
1861         for (qdp = biod.bufListEndp;
1862              qdp;
1863              qdp = (osi_queueData_t *) osi_QPrev(&qdp->q)) {
1864             tbufp = osi_GetQData(qdp);
1865             bufferp=tbufp->datap;
1866             memset(bufferp, 0, cm_data.buf_blockSize);
1867         }
1868
1869         /* no need to contact the file server */
1870         goto fetchingcompleted;
1871     }
1872
1873     if (scp_locked) {
1874         lock_ReleaseWrite(&scp->rw);
1875         scp_locked = 0;
1876     }
1877
1878     /* now make the call */
1879     do {
1880         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
1881         if (code)
1882             continue;
1883
1884         rxconnp = cm_GetRxConn(connp);
1885         rxcallp = rx_NewCall(rxconnp);
1886         rx_PutConnection(rxconnp);
1887
1888         nbytes = nbytes_hi = 0;
1889
1890         if (SERVERHAS64BIT(connp)) {
1891             call_was_64bit = 1;
1892
1893             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
1894                      scp, biod.offset.HighPart, biod.offset.LowPart, biod.length);
1895
1896             code = StartRXAFS_FetchData64(rxcallp, &tfid, biod.offset.QuadPart, biod.length);
1897
1898             if (code == 0) {
1899                 temp = rx_Read32(rxcallp, &nbytes_hi);
1900                 if (temp == sizeof(afs_int32)) {
1901                     nbytes_hi = ntohl(nbytes_hi);
1902                 } else {
1903                     nbytes_hi = 0;
1904                     code = rx_Error(rxcallp);
1905                     code1 = rx_EndCall(rxcallp, code);
1906                     rxcallp = NULL;
1907                 }
1908             }
1909         } else {
1910             call_was_64bit = 0;
1911         }
1912
1913         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
1914             if (require_64bit_ops) {
1915                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
1916                 code = CM_ERROR_TOOBIG;
1917             } else {
1918                 if (!rxcallp) {
1919                     rxconnp = cm_GetRxConn(connp);
1920                     rxcallp = rx_NewCall(rxconnp);
1921                     rx_PutConnection(rxconnp);
1922                 }
1923
1924                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
1925                          scp, biod.offset.LowPart, biod.length);
1926
1927                 code = StartRXAFS_FetchData(rxcallp, &tfid, biod.offset.LowPart,
1928                                             biod.length);
1929
1930                 SET_SERVERHASNO64BIT(connp);
1931             }
1932         }
1933
1934         if (code == 0) {
1935             temp  = rx_Read32(rxcallp, &nbytes);
1936             if (temp == sizeof(afs_int32)) {
1937                 nbytes = ntohl(nbytes);
1938                 FillInt64(length_found, nbytes_hi, nbytes);
1939                 if (length_found > biod.length) {
1940                     /*
1941                      * prior to 1.4.12 and 1.5.65 the file server would return
1942                      * (filesize - offset) if the requested offset was greater than
1943                      * the filesize.  The correct return value would have been zero.
1944                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
1945                      * is a race between two RPCs issues by this cache manager, the
1946                      * correct thing will happen the second time.
1947                      */
1948                     osi_Log0(afsd_logp, "cm_GetBuffer length_found > biod.length");
1949                     fs_fetchdata_offset_bug = 1;
1950                 }
1951             } else {
1952                 osi_Log1(afsd_logp, "cm_GetBuffer rx_Read32 returns %d != 4", temp);
1953                 code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
1954             }
1955         }
1956         /* for the moment, nbytes_hi will always be 0 if code == 0
1957            because biod.length is a 32-bit quantity. */
1958
1959         if (code == 0) {
1960             qdp = biod.bufListEndp;
1961             if (qdp) {
1962                 tbufp = osi_GetQData(qdp);
1963                 bufferp = tbufp->datap;
1964                 buffer_offset = 0;
1965             }
1966             else
1967                 bufferp = NULL;
1968
1969             /* fill length_found of data from the pipe into the pages.
1970              * When we stop, qdp will point at the last page we're
1971              * dealing with, and bufferp will tell us where we
1972              * stopped.  We'll need this info below when we clear
1973              * the remainder of the last page out (and potentially
1974              * clear later pages out, if we fetch past EOF).
1975              */
1976             while (length_found > 0) {
1977 #ifdef USE_RX_IOVEC
1978                 struct iovec tiov[RX_MAXIOVECS];
1979                 afs_int32 tnio, iov, iov_offset;
1980
1981                 temp = rx_Readv(rxcallp, tiov, &tnio, RX_MAXIOVECS, length_found);
1982                 osi_Log1(afsd_logp, "cm_GetBuffer rx_Readv returns %d", temp);
1983                 if (temp != length_found && temp < cm_data.buf_blockSize) {
1984                     /*
1985                      * If the file server returned (filesize - offset),
1986                      * then the first rx_Read will return zero octets of data.
1987                      * If it does, do not treat it as an error.  Correct the
1988                      * length_found and continue as if the file server said
1989                      * it was sending us zero octets of data.
1990                      */
1991                     if (fs_fetchdata_offset_bug && first_read) {
1992                         length_found = 0;
1993                         break;
1994                     } else if (temp <= 0) {
1995                         code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
1996                         break;
1997                     }
1998                 }
1999
2000                 iov = 0;
2001                 iov_offset = 0;
2002                 rbytes = temp;
2003
2004                 while (rbytes > 0) {
2005                     afs_int32 len;
2006
2007                     osi_assertx(bufferp != NULL, "null cm_buf_t");
2008
2009                     len = min(tiov[iov].iov_len - iov_offset, cm_data.buf_blockSize - buffer_offset);
2010                     memcpy(bufferp + buffer_offset, tiov[iov].iov_base + iov_offset, len);
2011                     iov_offset += len;
2012                     buffer_offset += len;
2013                     rbytes -= len;
2014
2015                     if (iov_offset == tiov[iov].iov_len) {
2016                         iov++;
2017                         iov_offset = 0;
2018                     }
2019
2020                     if (buffer_offset == cm_data.buf_blockSize) {
2021                         /* allow read-while-fetching.
2022                         * if this is the last buffer, clear the
2023                         * PREFETCHING flag, so the reader waiting for
2024                         * this buffer will start a prefetch.
2025                         */
2026                         _InterlockedOr(&tbufp->cmFlags, CM_BUF_CMFULLYFETCHED);
2027                         lock_ObtainWrite(&scp->rw);
2028                         if (!osi_QIsEmpty(&scp->waitQueueH)) {
2029                             osi_Log1(afsd_logp, "CM GetBuffer Waking scp 0x%p", scp);
2030                             osi_Wakeup((LONG_PTR) &scp->flags);
2031                         }
2032                         if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
2033                             osi_hyper_t tlength = ConvertLongToLargeInteger(biod.length);
2034                             *cpffp = 1;
2035                             cm_ClearPrefetchFlag(0, scp, &biod.offset, &tlength);
2036                         }
2037                         lock_ReleaseWrite(&scp->rw);
2038
2039                         /* Advance the buffer */
2040                         qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2041                         if (qdp) {
2042                             tbufp = osi_GetQData(qdp);
2043                             bufferp = tbufp->datap;
2044                             buffer_offset = 0;
2045                         }
2046                         else
2047                             bufferp = NULL;
2048                     }
2049                 }
2050
2051                 length_found -= temp;
2052 #else /* USE_RX_IOVEC */
2053                 /* assert that there are still more buffers;
2054                  * our check above for length_found being less than
2055                  * biod.length should ensure this.
2056                  */
2057                 osi_assertx(bufferp != NULL, "null cm_buf_t");
2058
2059                 /* read rbytes of data */
2060                 rbytes = (afs_uint32)(length_found > cm_data.buf_blockSize ? cm_data.buf_blockSize : length_found);
2061                 temp = rx_Read(rxcallp, bufferp, rbytes);
2062                 if (temp < rbytes) {
2063                     /*
2064                      * If the file server returned (filesize - offset),
2065                      * then the first rx_Read will return zero octets of data.
2066                      * If it does, do not treat it as an error.  Correct the
2067                      * length_found and continue as if the file server said
2068                      * it was sending us zero octets of data.
2069                      */
2070                     if (fs_fetchdata_offset_bug && first_read) {
2071                         length_found = 0;
2072                         break;
2073                     } else if (temp <= 0) {
2074                         code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2075                         break;
2076                     }
2077                 }
2078                 first_read = 0;
2079
2080                 /* allow read-while-fetching.
2081                  * if this is the last buffer, clear the
2082                  * PREFETCHING flag, so the reader waiting for
2083                  * this buffer will start a prefetch.
2084                  */
2085                 _InterlockedOr(&tbufp->cmFlags, CM_BUF_CMFULLYFETCHED);
2086                 lock_ObtainWrite(&scp->rw);
2087                 if (!osi_QIsEmpty(&scp->waitQueueH)) {
2088                     osi_Log1(afsd_logp, "CM GetBuffer Waking scp 0x%p", scp);
2089                     osi_Wakeup((LONG_PTR) &scp->flags);
2090                 }
2091                 if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
2092                     osi_hyper_t tlength = ConvertLongToLargeInteger(biod.length);
2093                     *cpffp = 1;
2094                     cm_ClearPrefetchFlag(0, scp, &biod.offset, &tlength);
2095                 }
2096                 lock_ReleaseWrite(&scp->rw);
2097
2098                 /* and adjust counters */
2099                 length_found -= temp;
2100
2101                 /* and move to the next buffer */
2102                 if (length_found != 0) {
2103                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2104                     if (qdp) {
2105                         tbufp = osi_GetQData(qdp);
2106                         bufferp = tbufp->datap;
2107                     }
2108                     else
2109                         bufferp = NULL;
2110                 } else
2111                     bufferp += temp;
2112 #endif /* USE_RX_IOVEC */
2113             }
2114
2115             /* zero out remainder of last pages, in case we are
2116              * fetching past EOF.  We were fetching an integral #
2117              * of pages, but stopped, potentially in the middle of
2118              * a page.  Zero the remainder of that page, and then
2119              * all of the rest of the pages.
2120              */
2121 #ifdef USE_RX_IOVEC
2122             rbytes = cm_data.buf_blockSize - buffer_offset;
2123             bufferp = tbufp->datap + buffer_offset;
2124 #else /* USE_RX_IOVEC */
2125             /* bytes fetched */
2126             osi_assertx((bufferp - tbufp->datap) < LONG_MAX, "data >= LONG_MAX");
2127             rbytes = (long) (bufferp - tbufp->datap);
2128
2129             /* bytes left to zero */
2130             rbytes = cm_data.buf_blockSize - rbytes;
2131 #endif /* USE_RX_IOVEC */
2132             while(qdp) {
2133                 if (rbytes != 0)
2134                     memset(bufferp, 0, rbytes);
2135                 qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2136                 if (qdp == NULL)
2137                     break;
2138                 tbufp = osi_GetQData(qdp);
2139                 bufferp = tbufp->datap;
2140                 /* bytes to clear in this page */
2141                 rbytes = cm_data.buf_blockSize;
2142             }
2143         }
2144
2145         if (code == 0) {
2146             if (call_was_64bit)
2147                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
2148             else
2149                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
2150         } else {
2151             if (call_was_64bit)
2152                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
2153             else
2154                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
2155         }
2156
2157         if (rxcallp)
2158             code1 = rx_EndCall(rxcallp, code);
2159
2160         if (code1 == RXKADUNKNOWNKEY)
2161             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
2162
2163         /* If we are avoiding a file server bug, ignore the error state */
2164         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
2165             /* Clone the current status info and clear the error state */
2166             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
2167             if (scp_locked) {
2168                 lock_ReleaseWrite(&scp->rw);
2169                 scp_locked = 0;
2170             }
2171             code = 0;
2172         /* Prefer the error value from FetchData over rx_EndCall */
2173         } else if (code == 0 && code1 != 0)
2174             code = code1;
2175         osi_Log0(afsd_logp, "CALL FetchData DONE");
2176
2177     } while (cm_Analyze(connp, userp, reqp, &scp->fid, NULL, 0, &afsStatus, &volSync, NULL, NULL, code));
2178
2179   fetchingcompleted:
2180     code = cm_MapRPCError(code, reqp);
2181
2182     if (!scp_locked)
2183         lock_ObtainWrite(&scp->rw);
2184
2185     /* we know that no one else has changed the buffer, since we still have
2186      * the fetching flag on the buffers, and we have the scp locked again.
2187      * Copy in the version # into the buffer if we got code 0 back from the
2188      * read.
2189      */
2190     if (code == 0) {
2191         for(qdp = biod.bufListp;
2192              qdp;
2193              qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
2194             tbufp = osi_GetQData(qdp);
2195             tbufp->dataVersion = afsStatus.dataVersionHigh;
2196             tbufp->dataVersion <<= 32;
2197             tbufp->dataVersion |= afsStatus.DataVersion;
2198
2199 #ifdef DISKCACHE95
2200             /* write buffer out to disk cache */
2201             diskcache_Update(tbufp->dcp, tbufp->datap, cm_data.buf_blockSize,
2202                               tbufp->dataVersion);
2203 #endif /* DISKCACHE95 */
2204         }
2205     }
2206
2207     if (code == 0)
2208         code = cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, CM_MERGEFLAG_FETCHDATA);
2209     else
2210         InterlockedDecrement(&scp->activeRPCs);
2211
2212   release_biod:
2213     /* release scatter/gather I/O structure (buffers, locks) */
2214     cm_ReleaseBIOD(&biod, 0, code, 1);
2215
2216     return code;
2217 }
2218
2219 /*
2220  * Similar to cm_GetBuffer but doesn't use an allocated cm_buf_t object.
2221  * Instead the data is read from the file server and copied directly into
2222  * a provided buffer.  Called with scp locked. The scp is locked on return.
2223  */
2224 long cm_GetData(cm_scache_t *scp, osi_hyper_t *offsetp, char *datap, int data_length,
2225                 cm_user_t *userp, cm_req_t *reqp)
2226 {
2227     long code=0, code1=0;
2228     afs_uint32 nbytes;                  /* bytes in transfer */
2229     afs_uint32 nbytes_hi = 0;           /* high-order 32 bits of bytes in transfer */
2230     afs_uint64 length_found = 0;
2231     char *bufferp = datap;
2232     afs_uint32 buffer_offset = 0;
2233     long rbytes;                        /* bytes in rx_Read call */
2234     long temp;
2235     AFSFetchStatus afsStatus;
2236     AFSCallBack callback;
2237     AFSVolSync volSync;
2238     AFSFid tfid;
2239     struct rx_call *rxcallp;
2240     struct rx_connection *rxconnp;
2241     cm_conn_t *connp;
2242     int getroot;
2243     afs_int32 t1,t2;
2244     int require_64bit_ops = 0;
2245     int call_was_64bit = 0;
2246     int fs_fetchdata_offset_bug = 0;
2247     int first_read = 1;
2248     int scp_locked = 1;
2249
2250     memset(&afsStatus, 0, sizeof(afsStatus));
2251     memset(&callback, 0, sizeof(callback));
2252     memset(&volSync, 0, sizeof(volSync));
2253
2254     /* now, the buffer may or may not be filled with good data (buf_GetNewLocked
2255      * drops lots of locks, and may indeed return a properly initialized
2256      * buffer, although more likely it will just return a new, empty, buffer.
2257      */
2258
2259 #ifdef AFS_FREELANCE_CLIENT
2260
2261     // yj: if they're trying to get the /afs directory, we need to
2262     // handle it differently, since it's local rather than on any
2263     // server
2264
2265     getroot = (scp==cm_data.rootSCachep);
2266     if (getroot)
2267         osi_Log1(afsd_logp,"GetBuffer returns cm_data.rootSCachep=%x",cm_data.rootSCachep);
2268 #endif
2269
2270     cm_AFSFidFromFid(&tfid, &scp->fid);
2271
2272     if (LargeIntegerGreaterThan(LargeIntegerAdd(*offsetp,
2273                                                 ConvertLongToLargeInteger(data_length)),
2274                                 ConvertLongToLargeInteger(LONG_MAX))) {
2275         require_64bit_ops = 1;
2276     }
2277
2278     InterlockedIncrement(&scp->activeRPCs);
2279     osi_Log2(afsd_logp, "cm_GetData: fetching data scp %p DV 0x%x", scp, scp->dataVersion);
2280
2281 #ifdef AFS_FREELANCE_CLIENT
2282
2283     // yj code
2284     // if getroot then we don't need to make any calls
2285     // just return fake data
2286
2287     if (cm_freelanceEnabled && getroot) {
2288         // setup the fake status
2289         afsStatus.InterfaceVersion = 0x1;
2290         afsStatus.FileType = 0x2;
2291         afsStatus.LinkCount = scp->linkCount;
2292         afsStatus.Length = cm_fakeDirSize;
2293         afsStatus.DataVersion = (afs_uint32)(cm_data.fakeDirVersion & 0xFFFFFFFF);
2294         afsStatus.Author = 0x1;
2295         afsStatus.Owner = 0x0;
2296         afsStatus.CallerAccess = 0x9;
2297         afsStatus.AnonymousAccess = 0x9;
2298         afsStatus.UnixModeBits = 0x1ff;
2299         afsStatus.ParentVnode = 0x1;
2300         afsStatus.ParentUnique = 0x1;
2301         afsStatus.ResidencyMask = 0;
2302         afsStatus.ClientModTime = (afs_uint32)FakeFreelanceModTime;
2303         afsStatus.ServerModTime = (afs_uint32)FakeFreelanceModTime;
2304         afsStatus.Group = 0;
2305         afsStatus.SyncCounter = 0;
2306         afsStatus.dataVersionHigh = (afs_uint32)(cm_data.fakeDirVersion >> 32);
2307         afsStatus.lockCount = 0;
2308         afsStatus.Length_hi = 0;
2309         afsStatus.errorCode = 0;
2310         memset(&volSync, 0, sizeof(volSync));
2311
2312         // once we're done setting up the status info,
2313         // we just fill the buffer pages with fakedata
2314         // from cm_FakeRootDir. Extra pages are set to
2315         // 0.
2316
2317         lock_ObtainMutex(&cm_Freelance_Lock);
2318         t1 = offsetp->LowPart;
2319         memset(datap, 0, data_length);
2320         t2 = cm_fakeDirSize - t1;
2321         if (t2 > data_length)
2322             t2 = data_length;
2323         if (t2 > 0)
2324             memcpy(datap, cm_FakeRootDir+t1, t2);
2325         lock_ReleaseMutex(&cm_Freelance_Lock);
2326
2327         // once we're done, we skip over the part of the
2328         // code that does the ACTUAL fetching of data for
2329         // real files
2330
2331         goto fetchingcompleted;
2332     }
2333
2334 #endif /* AFS_FREELANCE_CLIENT */
2335
2336     if (scp_locked) {
2337         lock_ReleaseWrite(&scp->rw);
2338         scp_locked = 0;
2339     }
2340
2341     /* now make the call */
2342     do {
2343         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2344         if (code)
2345             continue;
2346
2347         rxconnp = cm_GetRxConn(connp);
2348         rxcallp = rx_NewCall(rxconnp);
2349         rx_PutConnection(rxconnp);
2350
2351         nbytes = nbytes_hi = 0;
2352
2353         if (SERVERHAS64BIT(connp)) {
2354             call_was_64bit = 1;
2355
2356             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
2357                      scp, offsetp->HighPart, offsetp->LowPart, data_length);
2358
2359             code = StartRXAFS_FetchData64(rxcallp, &tfid, offsetp->QuadPart, data_length);
2360
2361             if (code == 0) {
2362                 temp = rx_Read32(rxcallp, &nbytes_hi);
2363                 if (temp == sizeof(afs_int32)) {
2364                     nbytes_hi = ntohl(nbytes_hi);
2365                 } else {
2366                     nbytes_hi = 0;
2367                     code = rx_Error(rxcallp);
2368                     code1 = rx_EndCall(rxcallp, code);
2369                     rxcallp = NULL;
2370                 }
2371             }
2372         } else {
2373             call_was_64bit = 0;
2374         }
2375
2376         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
2377             if (require_64bit_ops) {
2378                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
2379                 code = CM_ERROR_TOOBIG;
2380             } else {
2381                 if (!rxcallp) {
2382                     rxconnp = cm_GetRxConn(connp);
2383                     rxcallp = rx_NewCall(rxconnp);
2384                     rx_PutConnection(rxconnp);
2385                 }
2386
2387                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
2388                          scp, offsetp->LowPart, data_length);
2389
2390                 code = StartRXAFS_FetchData(rxcallp, &tfid, offsetp->LowPart, data_length);
2391
2392                 SET_SERVERHASNO64BIT(connp);
2393             }
2394         }
2395
2396         if (code == 0) {
2397             temp  = rx_Read32(rxcallp, &nbytes);
2398             if (temp == sizeof(afs_int32)) {
2399                 nbytes = ntohl(nbytes);
2400                 FillInt64(length_found, nbytes_hi, nbytes);
2401                 if (length_found > data_length) {
2402                     /*
2403                      * prior to 1.4.12 and 1.5.65 the file server would return
2404                      * (filesize - offset) if the requested offset was greater than
2405                      * the filesize.  The correct return value would have been zero.
2406                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
2407                      * is a race between two RPCs issues by this cache manager, the
2408                      * correct thing will happen the second time.
2409                      */
2410                     osi_Log0(afsd_logp, "cm_GetData length_found > data_length");
2411                     fs_fetchdata_offset_bug = 1;
2412                 }
2413             } else {
2414                 osi_Log1(afsd_logp, "cm_GetData rx_Read32 returns %d != 4", temp);
2415                 code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2416             }
2417         }
2418         /* for the moment, nbytes_hi will always be 0 if code == 0
2419            because data_length is a 32-bit quantity. */
2420
2421         if (code == 0) {
2422             /* fill length_found of data from the pipe into the pages.
2423              * When we stop, qdp will point at the last page we're
2424              * dealing with, and bufferp will tell us where we
2425              * stopped.  We'll need this info below when we clear
2426              * the remainder of the last page out (and potentially
2427              * clear later pages out, if we fetch past EOF).
2428              */
2429             while (length_found > 0) {
2430 #ifdef USE_RX_IOVEC
2431                 struct iovec tiov[RX_MAXIOVECS];
2432                 afs_int32 tnio, iov, iov_offset;
2433
2434                 temp = rx_Readv(rxcallp, tiov, &tnio, RX_MAXIOVECS, length_found);
2435                 osi_Log1(afsd_logp, "cm_GetData rx_Readv returns %d", temp);
2436                 if (temp != length_found && temp < data_length) {
2437                     /*
2438                      * If the file server returned (filesize - offset),
2439                      * then the first rx_Read will return zero octets of data.
2440                      * If it does, do not treat it as an error.  Correct the
2441                      * length_found and continue as if the file server said
2442                      * it was sending us zero octets of data.
2443                      */
2444                     if (fs_fetchdata_offset_bug && first_read) {
2445                         length_found = 0;
2446                         break;
2447                     } else if (temp <= 0) {
2448                         code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2449                         break;
2450                     }
2451                 }
2452
2453                 iov = 0;
2454                 iov_offset = 0;
2455                 rbytes = temp;
2456
2457                 while (rbytes > 0) {
2458                     afs_int32 len;
2459
2460                     osi_assertx(bufferp != NULL, "null cm_buf_t");
2461
2462                     len = min(tiov[iov].iov_len - iov_offset, data_length - buffer_offset);
2463                     memcpy(bufferp + buffer_offset, tiov[iov].iov_base + iov_offset, len);
2464                     iov_offset += len;
2465                     buffer_offset += len;
2466                     rbytes -= len;
2467
2468                     if (iov_offset == tiov[iov].iov_len) {
2469                         iov++;
2470                         iov_offset = 0;
2471                     }
2472                 }
2473
2474                 length_found -= temp;
2475 #else /* USE_RX_IOVEC */
2476                 /* assert that there are still more buffers;
2477                  * our check above for length_found being less than
2478                  * data_length should ensure this.
2479                  */
2480                 osi_assertx(bufferp != NULL, "null cm_buf_t");
2481
2482                 /* read rbytes of data */
2483                 rbytes = (afs_uint32)(length_found > data_length ? data_length : length_found);
2484                 temp = rx_Read(rxcallp, bufferp, rbytes);
2485                 if (temp < rbytes) {
2486                     /*
2487                      * If the file server returned (filesize - offset),
2488                      * then the first rx_Read will return zero octets of data.
2489                      * If it does, do not treat it as an error.  Correct the
2490                      * length_found and continue as if the file server said
2491                      * it was sending us zero octets of data.
2492                      */
2493                     if (fs_fetchdata_offset_bug && first_read) {
2494                         length_found = 0;
2495                         break;
2496                     } else if (temp <= 0) {
2497                         code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2498                         break;
2499                     }
2500                 }
2501                 first_read = 0;
2502
2503                 /* and adjust counters */
2504                 length_found -= temp;
2505 #endif /* USE_RX_IOVEC */
2506             }
2507
2508             /* zero out remainder of last pages, in case we are
2509              * fetching past EOF.  We were fetching an integral #
2510              * of pages, but stopped, potentially in the middle of
2511              * a page.  Zero the remainder of that page, and then
2512              * all of the rest of the pages.
2513              */
2514 #ifdef USE_RX_IOVEC
2515             rbytes = data_length - buffer_offset;
2516             bufferp = datap + buffer_offset;
2517 #else /* USE_RX_IOVEC */
2518             /* bytes fetched */
2519             osi_assertx((bufferp - datap) < LONG_MAX, "data >= LONG_MAX");
2520             rbytes = (long) (bufferp - datap);
2521
2522             /* bytes left to zero */
2523             rbytes = data_length - rbytes;
2524 #endif /* USE_RX_IOVEC */
2525             if (rbytes != 0)
2526                 memset(bufferp, 0, rbytes);
2527         }
2528
2529         if (code == 0) {
2530             if (call_was_64bit)
2531                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
2532             else
2533                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
2534         } else {
2535             if (call_was_64bit)
2536                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
2537             else
2538                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
2539         }
2540
2541         if (rxcallp)
2542             code1 = rx_EndCall(rxcallp, code);
2543
2544         if (code1 == RXKADUNKNOWNKEY)
2545             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
2546
2547         /* If we are avoiding a file server bug, ignore the error state */
2548         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
2549             /* Clone the current status info and clear the error state */
2550             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
2551             if (scp_locked) {
2552                 lock_ReleaseWrite(&scp->rw);
2553                 scp_locked = 0;
2554             }
2555             code = 0;
2556         /* Prefer the error value from FetchData over rx_EndCall */
2557         } else if (code == 0 && code1 != 0)
2558             code = code1;
2559         osi_Log0(afsd_logp, "CALL FetchData DONE");
2560
2561     } while (cm_Analyze(connp, userp, reqp, &scp->fid, NULL, 0, &afsStatus, &volSync, NULL, NULL, code));
2562
2563   fetchingcompleted:
2564     code = cm_MapRPCError(code, reqp);
2565
2566     if (!scp_locked)
2567         lock_ObtainWrite(&scp->rw);
2568
2569     if (code == 0)
2570         code = cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, CM_MERGEFLAG_FETCHDATA);
2571     else
2572         InterlockedDecrement(&scp->activeRPCs);
2573
2574     return code;
2575 }
2576
2577 /*
2578  * cm_VerifyStoreData.   Function passed a rw locked cm_scache_t and a store data biod.
2579  *
2580  * Return 1 if the data verifies; 0 if not.
2581  */
2582
2583 long
2584 cm_VerifyStoreData(cm_bulkIO_t *biod, cm_scache_t *savedScp)
2585 {
2586     long code=0, code1=0;
2587     afs_uint32 nbytes;                  /* bytes in transfer */
2588     afs_uint32 nbytes_hi = 0;           /* high-order 32 bits of bytes in transfer */
2589     afs_uint64 length_found = 0;
2590     long rbytes;                        /* bytes in rx_Read call */
2591     long temp;
2592     AFSFetchStatus afsStatus;
2593     AFSCallBack callback;
2594     AFSVolSync volSync;
2595     AFSFid tfid;
2596     struct rx_call *rxcallp;
2597     struct rx_connection *rxconnp;
2598     cm_conn_t *connp;
2599     int require_64bit_ops = 0;
2600     int call_was_64bit = 0;
2601     int fs_fetchdata_offset_bug = 0;
2602     int first_read = 1;
2603     int scp_locked = 1;
2604     char * bufferp = malloc(biod->length);
2605     long verified = 0;
2606     cm_scache_t *scp = biod->scp;
2607     cm_user_t *userp = biod->userp;
2608     cm_req_t *reqp = biod->reqp;
2609     afs_uint64 dataVersion = scp->dataVersion;
2610
2611     memset(&afsStatus, 0, sizeof(afsStatus));
2612     memset(&callback, 0, sizeof(callback));
2613     memset(&volSync, 0, sizeof(volSync));
2614     memset(bufferp, 0, biod->length);
2615
2616     cm_AFSFidFromFid(&tfid, &scp->fid);
2617
2618     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod->offset,
2619                                                 ConvertLongToLargeInteger(biod->length)),
2620                                 ConvertLongToLargeInteger(LONG_MAX))) {
2621         require_64bit_ops = 1;
2622     }
2623
2624     InterlockedIncrement(&scp->activeRPCs);
2625     osi_Log2(afsd_logp, "cm_VerifyStoreData: fetching data scp %p DV 0x%x", scp, scp->dataVersion);
2626
2627     if (scp_locked) {
2628         lock_ReleaseWrite(&scp->rw);
2629         scp_locked = 0;
2630     }
2631
2632     /* now make the call */
2633     do {
2634         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2635         if (code)
2636             continue;
2637
2638         rxconnp = cm_GetRxConn(connp);
2639         rxcallp = rx_NewCall(rxconnp);
2640         rx_PutConnection(rxconnp);
2641
2642         nbytes = nbytes_hi = 0;
2643
2644         if (SERVERHAS64BIT(connp)) {
2645             call_was_64bit = 1;
2646
2647             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
2648                      scp, biod->offset.HighPart, biod->offset.LowPart, biod->length);
2649
2650             code = StartRXAFS_FetchData64(rxcallp, &tfid, biod->offset.QuadPart, biod->length);
2651
2652             if (code == 0) {
2653                 temp = rx_Read32(rxcallp, &nbytes_hi);
2654                 if (temp == sizeof(afs_int32)) {
2655                     nbytes_hi = ntohl(nbytes_hi);
2656                 } else {
2657                     nbytes_hi = 0;
2658                     code = rx_Error(rxcallp);
2659                     code1 = rx_EndCall(rxcallp, code);
2660                     rxcallp = NULL;
2661                 }
2662             }
2663         } else {
2664             call_was_64bit = 0;
2665         }
2666
2667         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
2668             if (require_64bit_ops) {
2669                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
2670                 code = CM_ERROR_TOOBIG;
2671             } else {
2672                 if (!rxcallp) {
2673                     rxconnp = cm_GetRxConn(connp);
2674                     rxcallp = rx_NewCall(rxconnp);
2675                     rx_PutConnection(rxconnp);
2676                 }
2677
2678                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
2679                          scp, biod->offset.LowPart, biod->length);
2680
2681                 code = StartRXAFS_FetchData(rxcallp, &tfid, biod->offset.LowPart, biod->length);
2682
2683                 SET_SERVERHASNO64BIT(connp);
2684             }
2685         }
2686
2687         if (code == 0) {
2688             temp  = rx_Read32(rxcallp, &nbytes);
2689             if (temp == sizeof(afs_int32)) {
2690                 nbytes = ntohl(nbytes);
2691                 FillInt64(length_found, nbytes_hi, nbytes);
2692                 if (length_found > biod->length) {
2693                     /*
2694                      * prior to 1.4.12 and 1.5.65 the file server would return
2695                      * (filesize - offset) if the requested offset was greater than
2696                      * the filesize.  The correct return value would have been zero.
2697                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
2698                      * is a race between two RPCs issues by this cache manager, the
2699                      * correct thing will happen the second time.
2700                      */
2701                     osi_Log0(afsd_logp, "cm_GetData length_found > biod.length");
2702                     fs_fetchdata_offset_bug = 1;
2703                 }
2704             } else {
2705                 osi_Log1(afsd_logp, "cm_GetData rx_Read32 returns %d != 4", temp);
2706                 code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2707             }
2708         }
2709         /* for the moment, nbytes_hi will always be 0 if code == 0
2710            because data_length is a 32-bit quantity. */
2711
2712         if (code == 0) {
2713             /* fill length_found of data from the pipe into the pages.
2714              * When we stop, qdp will point at the last page we're
2715              * dealing with, and bufferp will tell us where we
2716              * stopped.  We'll need this info below when we clear
2717              * the remainder of the last page out (and potentially
2718              * clear later pages out, if we fetch past EOF).
2719              */
2720             while (length_found > 0) {
2721                 /* assert that there are still more buffers;
2722                  * our check above for length_found being less than
2723                  * data_length should ensure this.
2724                  */
2725                 osi_assertx(bufferp != NULL, "null cm_buf_t");
2726
2727                 /* read rbytes of data */
2728                 rbytes = (afs_uint32)(length_found > biod->length ? biod->length : length_found);
2729                 temp = rx_Read(rxcallp, bufferp, rbytes);
2730                 if (temp < rbytes) {
2731                     /*
2732                      * If the file server returned (filesize - offset),
2733                      * then the first rx_Read will return zero octets of data.
2734                      * If it does, do not treat it as an error.  Correct the
2735                      * length_found and continue as if the file server said
2736                      * it was sending us zero octets of data.
2737                      */
2738                     if (fs_fetchdata_offset_bug && first_read) {
2739                         length_found = 0;
2740                         break;
2741                     } else if (temp <= 0) {
2742                         code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2743                         break;
2744                     }
2745                 }
2746                 first_read = 0;
2747
2748                 /* and adjust counters */
2749                 length_found -= temp;
2750             }
2751         }
2752
2753         if (code == 0) {
2754             if (call_was_64bit)
2755                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
2756             else
2757                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
2758         } else {
2759             if (call_was_64bit)
2760                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
2761             else
2762                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
2763         }
2764
2765         if (rxcallp)
2766             code1 = rx_EndCall(rxcallp, code);
2767
2768         if (code1 == RXKADUNKNOWNKEY)
2769             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
2770
2771         /* If we are avoiding a file server bug, ignore the error state */
2772         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
2773             /* Clone the current status info and clear the error state */
2774             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
2775             if (scp_locked) {
2776                 lock_ReleaseWrite(&scp->rw);
2777                 scp_locked = 0;
2778             }
2779             code = 0;
2780         /* Prefer the error value from FetchData over rx_EndCall */
2781         } else if (code == 0 && code1 != 0)
2782             code = code1;
2783         osi_Log0(afsd_logp, "CALL FetchData DONE");
2784
2785     } while (cm_Analyze(connp, userp, reqp, &scp->fid, NULL, 0, &afsStatus, &volSync, NULL, NULL, code));
2786
2787   fetchingcompleted:
2788     code = cm_MapRPCError(code, reqp);
2789
2790     if (!scp_locked)
2791         lock_ObtainWrite(&scp->rw);
2792
2793     if (code == 0)
2794         code = cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, CM_MERGEFLAG_FETCHDATA);
2795     else
2796         InterlockedDecrement(&scp->activeRPCs);
2797
2798     if (code == 0)
2799     {
2800         if (dataVersion == scp->dataVersion)
2801         {
2802             osi_queueData_t *qdp = NULL;
2803             cm_buf_t *bufp;
2804             afs_uint32 buf_offset;
2805             afs_uint32 bytes_compared = 0;
2806             afs_uint32 cmp_length;
2807             int md5_match = 1;
2808
2809             verified = 1;
2810
2811             while ( bytes_compared < biod->length )
2812             {
2813                 if (qdp == NULL) {
2814                     qdp = biod->bufListEndp;
2815                     buf_offset = biod->offset.LowPart % cm_data.buf_blockSize;
2816                 } else {
2817                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2818                     buf_offset = 0;
2819                 }
2820                 cmp_length =  cm_data.buf_blockSize - buf_offset;
2821
2822                 osi_assertx(qdp != NULL, "null osi_queueData_t");
2823                 bufp = osi_GetQData(qdp);
2824
2825                 if (memcmp(bufferp+bytes_compared, bufp->datap+buf_offset, cmp_length) != 0)
2826                 {
2827                     verified = 0;
2828                     md5_match = buf_ValidateCheckSum(bufp);
2829
2830                     osi_Log5(afsd_logp, "cm_VerifyDataStore verification failed scp 0x%p bufp 0x%p offset 0x%x:%08x md5 %s",
2831                              scp, bufp, bufp->offset.HighPart, bufp->offset.LowPart, md5_match ? "match" : "no-match");
2832                 }
2833                 bytes_compared += cmp_length;
2834             }
2835         } else {
2836             osi_Log4(afsd_logp, "cm_VerifyStoreData unable to verify due to data version change scp 0x%p, off 0x%x:%08x, size 0x%x",
2837                      scp, biod->offset.HighPart, biod->offset.LowPart, biod->length);
2838         }
2839     }
2840
2841     if (bufferp)
2842         free(bufferp);
2843
2844     return verified;
2845 }