6dc23fd0c4ba4bddee2fb26131ad93e5fa639e2d
[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 /* functions called back from the buffer package when reading or writing data,
38  * or when holding or releasing a vnode pointer.
39  */
40 long cm_BufWrite(void *vscp, osi_hyper_t *offsetp, long length, long flags,
41                  cm_user_t *userp, cm_req_t *reqp)
42 {
43     /*
44      * store the data back from this buffer; the buffer is locked and held,
45      * but the vnode involved may or may not be locked depending on whether
46      * or not the CM_BUF_WRITE_SCP_LOCKED flag is set.
47      */
48     long code, code1;
49     cm_scache_t *scp = vscp;
50     afs_int32 nbytes;
51     afs_int32 save_nbytes;
52     cm_scache_t save_scache;
53     long temp;
54     AFSFetchStatus outStatus;
55     AFSStoreStatus inStatus;
56     osi_hyper_t thyper;
57     AFSVolSync volSync;
58     AFSFid tfid;
59     struct rx_call *rxcallp;
60     struct rx_connection *rxconnp;
61     osi_queueData_t *qdp;
62     cm_buf_t *bufp;
63     afs_uint32 wbytes;
64     char *bufferp;
65     cm_conn_t *connp;
66     osi_hyper_t truncPos;
67     cm_bulkIO_t biod;           /* bulk IO descriptor */
68     int require_64bit_ops = 0;
69     int call_was_64bit = 0;
70     int scp_locked = flags & CM_BUF_WRITE_SCP_LOCKED;
71     int storedata_excl = 0;
72
73     osi_assertx(userp != NULL, "null cm_user_t");
74     osi_assertx(scp != NULL, "null cm_scache_t");
75
76     memset(&volSync, 0, sizeof(volSync));
77
78     /*
79      * now, the buffer may or may not be filled with good data (buf_GetNewLocked
80      * drops lots of locks, and may indeed return a properly initialized
81      * buffer, although more likely it will just return a new, empty, buffer.
82      */
83     if (!scp_locked)
84         lock_ObtainWrite(&scp->rw);
85     if (scp->flags & CM_SCACHEFLAG_DELETED) {
86         if (!scp_locked)
87             lock_ReleaseWrite(&scp->rw);
88         return CM_ERROR_NOSUCHFILE;
89     }
90
91     cm_AFSFidFromFid(&tfid, &scp->fid);
92
93     /* Serialize StoreData RPC's; for rationale see cm_scache.c */
94     (void) cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA_EXCL);
95     storedata_excl = 1;
96
97     code = cm_SetupStoreBIOD(scp, offsetp, length, &biod, userp, reqp);
98     if (code) {
99         osi_Log1(afsd_logp, "cm_SetupStoreBIOD code %x", code);
100         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
101         if (!scp_locked)
102             lock_ReleaseWrite(&scp->rw);
103         return code;
104     }
105
106     if (biod.length == 0) {
107         osi_Log0(afsd_logp, "cm_SetupStoreBIOD length 0");
108         cm_ReleaseBIOD(&biod, 1, 0, 1); /* should be a NOOP */
109         code = 0;
110         goto exit_storedata_excl;
111     }
112
113     /* prepare the output status for the store */
114     _InterlockedOr(&scp->mask, CM_SCACHEMASK_CLIENTMODTIME);
115     cm_StatusFromAttr(&inStatus, scp, NULL);
116     truncPos = scp->length;
117     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
118          && LargeIntegerLessThan(scp->truncPos, truncPos)) {
119         truncPos = scp->truncPos;
120         _InterlockedAnd(&scp->mask, ~CM_SCACHEMASK_TRUNCPOS);
121     }
122
123     /* compute how many bytes to write from this buffer */
124     thyper = LargeIntegerSubtract(scp->length, biod.offset);
125     if (LargeIntegerLessThanZero(thyper)) {
126         /* entire buffer is past EOF */
127         nbytes = 0;
128     }
129     else {
130         /* otherwise write out part of buffer before EOF, but not
131          * more than bufferSize bytes.
132          */
133         if (LargeIntegerGreaterThan(thyper,
134                                     ConvertLongToLargeInteger(biod.length))) {
135             nbytes = biod.length;
136         } else {
137             /* if thyper is less than or equal to biod.length, then we
138                can safely assume that the value fits in a long. */
139             nbytes = thyper.LowPart;
140         }
141     }
142
143     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
144                                                  ConvertLongToLargeInteger(nbytes)),
145                                  ConvertLongToLargeInteger(LONG_MAX)) ||
146          LargeIntegerGreaterThan(truncPos,
147                                  ConvertLongToLargeInteger(LONG_MAX))) {
148         require_64bit_ops = 1;
149     }
150
151     /* now we're ready to do the store operation */
152   retry_rpc:
153     InterlockedIncrement(&scp->activeRPCs);
154     lock_ReleaseWrite(&scp->rw);
155
156     save_nbytes = nbytes;
157     save_scache = *scp;
158
159     do {
160         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
161         if (code)
162             continue;
163
164     retry:
165         rxconnp = cm_GetRxConn(connp);
166         rxcallp = rx_NewCall(rxconnp);
167         rx_PutConnection(rxconnp);
168
169         if (SERVERHAS64BIT(connp)) {
170             call_was_64bit = 1;
171
172             osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData64 scp 0x%p, offset 0x%x:%08x, length 0x%x",
173                      scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
174             osi_Log2(afsd_logp, "... truncPos 0x%x:%08x",  truncPos.HighPart, truncPos.LowPart);
175
176             code = StartRXAFS_StoreData64(rxcallp, &tfid, &inStatus,
177                                           biod.offset.QuadPart,
178                                           nbytes,
179                                           truncPos.QuadPart);
180             if (code)
181                 osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData64 FAILURE, code 0x%x", code);
182             else
183                 osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData64 SUCCESS");
184         } else {
185             call_was_64bit = 0;
186
187             if (require_64bit_ops) {
188                 osi_Log0(afsd_logp, "Skipping StartRXAFS_StoreData.  The operation requires large file support in the server.");
189                 code = CM_ERROR_TOOBIG;
190             } else {
191                 osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData scp 0x%p, offset 0x%x:%08x, length 0x%x",
192                          scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
193
194                 code = StartRXAFS_StoreData(rxcallp, &tfid, &inStatus,
195                                             biod.offset.LowPart, nbytes, truncPos.LowPart);
196                 if (code)
197                     osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData FAILURE, code 0x%x", code);
198                 else
199                     osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData SUCCESS");
200             }
201         }
202
203         if (code == 0) {
204             afs_uint32 buf_offset = 0, bytes_copied = 0;
205
206             /* write the data from the the list of buffers */
207             qdp = NULL;
208             while(nbytes > 0) {
209 #ifdef USE_RX_IOVEC
210                 struct iovec tiov[RX_MAXIOVECS];
211                 afs_int32 tnio, vlen, vbytes, iov, voffset;
212                 afs_uint32 vleft;
213
214                 vbytes = rx_WritevAlloc(rxcallp, tiov, &tnio, RX_MAXIOVECS, nbytes);
215                 if (vbytes <= 0) {
216                     code = RX_PROTOCOL_ERROR;
217                     break;
218                 }
219
220                 for ( iov = voffset = vlen = 0;
221                       vlen < vbytes && iov < tnio; vlen += wbytes) {
222                     if (qdp == NULL) {
223                         qdp = biod.bufListEndp;
224                         buf_offset = offsetp->LowPart % cm_data.buf_blockSize;
225                     } else if (buf_offset == cm_data.buf_blockSize) {
226                         qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
227                         buf_offset = 0;
228                     }
229
230                     osi_assertx(qdp != NULL, "null osi_queueData_t");
231                     bufp = osi_GetQData(qdp);
232                     bufferp = bufp->datap + buf_offset;
233                     wbytes = vbytes - vlen;
234                     if (wbytes > cm_data.buf_blockSize - buf_offset)
235                         wbytes = cm_data.buf_blockSize - buf_offset;
236
237                     vleft = tiov[iov].iov_len - voffset;
238                     while (wbytes > vleft && iov < tnio) {
239                         memcpy(tiov[iov].iov_base + voffset, bufferp, vleft);
240                         bytes_copied += vleft;
241                         vlen += vleft;
242                         wbytes -= vleft;
243                         bufferp += vleft;
244                         buf_offset += vleft;
245
246                         iov++;
247                         voffset = 0;
248                         vleft = tiov[iov].iov_len;
249                     }
250
251                     if (iov < tnio) {
252                         memcpy(tiov[iov].iov_base + voffset, bufferp, wbytes);
253                         bytes_copied += wbytes;
254                         if (tiov[iov].iov_len == voffset + wbytes) {
255                             iov++;
256                             voffset = 0;
257                             vleft = (iov < tnio) ? tiov[iov].iov_len : 0;
258                         } else {
259                             voffset += wbytes;
260                             vleft -= wbytes;
261                         }
262                         bufferp += wbytes;
263                         buf_offset += wbytes;
264                     } else {
265                         voffset = vleft = 0;
266                     }
267                 }
268
269                 osi_assertx(iov == tnio, "incorrect iov count");
270                 osi_assertx(vlen == vbytes, "bytes_copied != vbytes");
271                 osi_assertx(bufp->offset.QuadPart + buf_offset == biod.offset.QuadPart + bytes_copied,
272                             "begin and end offsets don't match");
273
274                 temp = rx_Writev(rxcallp, tiov, tnio, vbytes);
275                 if (temp != vbytes) {
276                     osi_Log3(afsd_logp, "rx_Writev failed bp 0x%p, %d != %d", bufp, temp, vbytes);
277                     code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
278                     break;
279                 }
280
281                 osi_Log2(afsd_logp, "rx_Writev succeeded iov offset 0x%x, wrote 0x%x",
282                          (unsigned long)(bufp->offset.QuadPart + buf_offset - vbytes), vbytes);
283                 nbytes -= vbytes;
284 #else /* USE_RX_IOVEC */
285                 if (qdp == NULL) {
286                     qdp = biod.bufListEndp;
287                     buf_offset = offsetp->LowPart % cm_data.buf_blockSize;
288                 } else {
289                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
290                     buf_offset = 0;
291                 }
292
293                 osi_assertx(qdp != NULL, "null osi_queueData_t");
294                 bufp = osi_GetQData(qdp);
295                 bufferp = bufp->datap + buf_offset;
296                 wbytes = nbytes;
297                 if (wbytes > cm_data.buf_blockSize - buf_offset)
298                     wbytes = cm_data.buf_blockSize - buf_offset;
299
300                 /* write out wbytes of data from bufferp */
301                 temp = rx_Write(rxcallp, bufferp, wbytes);
302                 if (temp != wbytes) {
303                     osi_Log3(afsd_logp, "rx_Write failed bp 0x%p, %d != %d", bufp, temp, wbytes);
304                     code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
305                     break;
306                 } else {
307                     osi_Log2(afsd_logp, "rx_Write succeeded bp 0x%p written %d", bufp, temp);
308                 }
309                 nbytes -= wbytes;
310 #endif /* USE_RX_IOVEC */
311
312                 /*
313                  * Rx supports an out of band signalling mechanism that permits
314                  * RPC specific status information to be communicated in the
315                  * reverse direction of the channel.  For RXAFS_StoreData, the
316                  * 0-bit is set once all of the permission checks have completed
317                  * and the volume/vnode locks have been obtained by the file
318                  * server.  The signal is intended to notify the Unix afs client
319                  * that is performing store-on-close that it is safe to permit
320                  * the close operation to complete while the store continues
321                  * in the background.  All of the callbacks have been broken
322                  * and the locks will not be dropped until the RPC completes
323                  * which prevents any other operation from being initiated on
324                  * the vnode until the store is finished.
325                  *
326                  * The Windows client does not perform store-on-close.  Instead
327                  * it uses the CM_SCACHESYNC_STOREDATA_EXCL request flag and
328                  * CM_SCACHEFLAG_DATASTORING scache state to ensure that store
329                  * operations are serialized.  The 0-bit signal permits the
330                  * CM_SCACHEFLAG_DATASTORING state to the dropped which in
331                  * turn permits another thread to prep its own BIOD in parallel.
332                  * This is safe because it is impossible for that second store
333                  * RPC to complete before this one does.
334                  */
335                 if ( storedata_excl && (rx_GetRemoteStatus(rxcallp) & 1)) {
336                     lock_ObtainWrite(&scp->rw);
337                     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
338                     lock_ReleaseWrite(&scp->rw);
339                     storedata_excl = 0;
340                 }
341             }   /* while more bytes to write */
342         }       /* if RPC started successfully */
343
344         if (code == 0) {
345             if (call_was_64bit) {
346                 code = EndRXAFS_StoreData64(rxcallp, &outStatus, &volSync);
347                 if (code)
348                     osi_Log2(afsd_logp, "EndRXAFS_StoreData64 FAILURE scp 0x%p code %lX", scp, code);
349                 else
350                     osi_Log0(afsd_logp, "EndRXAFS_StoreData64 SUCCESS");
351             } else {
352                 code = EndRXAFS_StoreData(rxcallp, &outStatus, &volSync);
353                 if (code)
354                     osi_Log2(afsd_logp, "EndRXAFS_StoreData FAILURE scp 0x%p code %lX",scp,code);
355                 else
356                     osi_Log0(afsd_logp, "EndRXAFS_StoreData SUCCESS");
357             }
358         }
359
360         code1 = rx_EndCall(rxcallp, code);
361
362         if ((code == RXGEN_OPCODE || code1 == RXGEN_OPCODE) && SERVERHAS64BIT(connp)) {
363             SET_SERVERHASNO64BIT(connp);
364             qdp = NULL;
365             nbytes = save_nbytes;
366             goto retry;
367         }
368         /* Prefer rx_EndCall error over StoreData error */
369         if (code1 != 0) {
370             osi_Log2(afsd_logp, "rx_EndCall converted 0x%x to 0x%x", code, code1);
371             code = code1;
372         }
373     } while (cm_Analyze(connp, userp, reqp, &scp->fid, NULL, 1, &outStatus, &volSync, NULL, NULL, code));
374
375     code = cm_MapRPCError(code, reqp);
376
377     if (code)
378         osi_Log2(afsd_logp, "CALL StoreData FAILURE scp 0x%p, code 0x%x", scp, code);
379     else
380         osi_Log1(afsd_logp, "CALL StoreData SUCCESS scp 0x%p", scp);
381
382     /* now, clean up our state */
383     lock_ObtainWrite(&scp->rw);
384
385     if (code == 0) {
386         osi_hyper_t t;
387         /* now, here's something a little tricky: in AFS 3, a dirty
388          * length can't be directly stored, instead, a dirty chunk is
389          * stored that sets the file's size (by writing and by using
390          * the truncate-first option in the store call).
391          *
392          * At this point, we've just finished a store, and so the trunc
393          * pos field is clean.  If the file's size at the server is at
394          * least as big as we think it should be, then we turn off the
395          * length dirty bit, since all the other dirty buffers must
396          * precede this one in the file.
397          *
398          * The file's desired size shouldn't be smaller than what's
399          * stored at the server now, since we just did the trunc pos
400          * store.
401          *
402          * We have to turn off the length dirty bit as soon as we can,
403          * so that we see updates made by other machines.
404          */
405
406         if (call_was_64bit) {
407             t.LowPart = outStatus.Length;
408             t.HighPart = outStatus.Length_hi;
409         } else {
410             t = ConvertLongToLargeInteger(outStatus.Length);
411         }
412
413         if (LargeIntegerGreaterThanOrEqualTo(t, scp->length))
414             _InterlockedAnd(&scp->mask, ~CM_SCACHEMASK_LENGTH);
415
416         code = cm_MergeStatus(NULL, scp, &outStatus, &volSync, userp, reqp, CM_MERGEFLAG_STOREDATA);
417     } else {
418         InterlockedDecrement(&scp->activeRPCs);
419         if (code == CM_ERROR_SPACE)
420             _InterlockedOr(&scp->flags, CM_SCACHEFLAG_OUTOFSPACE);
421         else if (code == CM_ERROR_QUOTA)
422             _InterlockedOr(&scp->flags, CM_SCACHEFLAG_OVERQUOTA);
423     }
424
425     if ( cm_verifyData )
426     {
427         if (!cm_VerifyStoreData(&biod, &save_scache)) {
428             /* file server content doesn't match what we sent. */
429             nbytes = save_nbytes;
430             goto retry_rpc;
431         }
432     }
433
434     cm_ReleaseBIOD(&biod, 1, code, 1);
435
436   exit_storedata_excl:
437     if (storedata_excl)
438         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
439
440     if (!scp_locked)
441         lock_ReleaseWrite(&scp->rw);
442
443     return code;
444 }
445
446 /*
447  * Truncate the file, by sending a StoreData RPC with zero length.
448  *
449  * Called with scp locked.  Releases and re-obtains the lock.
450  */
451 long cm_StoreMini(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
452 {
453     AFSFetchStatus outStatus;
454     AFSStoreStatus inStatus;
455     AFSVolSync volSync;
456     AFSFid tfid;
457     long code, code1;
458     osi_hyper_t truncPos;
459     cm_conn_t *connp;
460     struct rx_call *rxcallp;
461     struct rx_connection *rxconnp;
462     int require_64bit_ops = 0;
463     int call_was_64bit = 0;
464
465     memset(&volSync, 0, sizeof(volSync));
466
467     osi_Log2(afsd_logp, "cm_StoreMini scp 0x%p userp 0x%p", scp, userp);
468
469     /* Serialize StoreData RPC's; for rationale see cm_scache.c */
470     (void) cm_SyncOp(scp, NULL, userp, reqp, 0,
471                      CM_SCACHESYNC_STOREDATA_EXCL);
472
473     /* prepare the output status for the store */
474     inStatus.Mask = AFS_SETMODTIME;
475     inStatus.ClientModTime = scp->clientModTime;
476     _InterlockedAnd(&scp->mask, ~CM_SCACHEMASK_CLIENTMODTIME);
477
478     /* calculate truncation position */
479     truncPos = scp->length;
480     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
481         && LargeIntegerLessThan(scp->truncPos, truncPos))
482         truncPos = scp->truncPos;
483     _InterlockedAnd(&scp->mask, ~CM_SCACHEMASK_TRUNCPOS);
484
485     if (LargeIntegerGreaterThan(truncPos,
486                                 ConvertLongToLargeInteger(LONG_MAX))) {
487
488         require_64bit_ops = 1;
489     }
490
491     InterlockedIncrement(&scp->activeRPCs);
492     lock_ReleaseWrite(&scp->rw);
493
494     cm_AFSFidFromFid(&tfid, &scp->fid);
495
496     /* now we're ready to do the store operation */
497     do {
498         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
499         if (code)
500             continue;
501
502     retry:
503         rxconnp = cm_GetRxConn(connp);
504         rxcallp = rx_NewCall(rxconnp);
505         rx_PutConnection(rxconnp);
506
507         if (SERVERHAS64BIT(connp)) {
508             call_was_64bit = 1;
509
510             osi_Log3(afsd_logp, "CALL StartRXAFS_StoreData64 scp 0x%p, truncPos 0x%x:%08x",
511                       scp, truncPos.HighPart, truncPos.LowPart);
512
513             code = StartRXAFS_StoreData64(rxcallp, &tfid, &inStatus,
514                                           0, 0, truncPos.QuadPart);
515             if (code)
516                 osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData64 FAILURE, code 0x%x", code);
517             else
518                 osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData64 SUCCESS");
519         } else {
520             call_was_64bit = 0;
521
522             if (require_64bit_ops) {
523                 code = CM_ERROR_TOOBIG;
524             } else {
525                 osi_Log3(afsd_logp, "CALL StartRXAFS_StoreData scp 0x%p, truncPos 0x%x:%08x",
526                           scp, truncPos.HighPart, truncPos.LowPart);
527
528                 code = StartRXAFS_StoreData(rxcallp, &tfid, &inStatus,
529                                             0, 0, truncPos.LowPart);
530                 if (code)
531                     osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData FAILURE, code 0x%x", code);
532                 else
533                     osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData SUCCESS");
534             }
535         }
536
537         if (code == 0) {
538             if (call_was_64bit) {
539                 code = EndRXAFS_StoreData64(rxcallp, &outStatus, &volSync);
540                 if (code)
541                     osi_Log2(afsd_logp, "EndRXAFS_StoreData64 FAILURE scp 0x%p code %lX", scp, code);
542                 else
543                     osi_Log0(afsd_logp, "EndRXAFS_StoreData64 SUCCESS");
544             } else {
545                 code = EndRXAFS_StoreData(rxcallp, &outStatus, &volSync);
546                 if (code)
547                     osi_Log2(afsd_logp, "EndRXAFS_StoreData FAILURE scp 0x%p code %lX", scp, code);
548                 else
549                     osi_Log0(afsd_logp, "EndRXAFS_StoreData SUCCESS");
550             }
551         }
552         code1 = rx_EndCall(rxcallp, code);
553
554         if ((code == RXGEN_OPCODE || code1 == RXGEN_OPCODE) && SERVERHAS64BIT(connp)) {
555             SET_SERVERHASNO64BIT(connp);
556             goto retry;
557         }
558
559         /* prefer StoreData error over rx_EndCall error */
560         if (code == 0 && code1 != 0)
561             code = code1;
562     } while (cm_Analyze(connp, userp, reqp, &scp->fid, NULL, 1, &outStatus, &volSync, NULL, NULL, code));
563     code = cm_MapRPCError(code, reqp);
564
565     /* now, clean up our state */
566     lock_ObtainWrite(&scp->rw);
567
568     if (code == 0) {
569         osi_hyper_t t;
570         /*
571          * For explanation of handling of CM_SCACHEMASK_LENGTH,
572          * see cm_BufWrite().
573          */
574         if (call_was_64bit) {
575             t.HighPart = outStatus.Length_hi;
576             t.LowPart = outStatus.Length;
577         } else {
578             t = ConvertLongToLargeInteger(outStatus.Length);
579         }
580
581         if (LargeIntegerGreaterThanOrEqualTo(t, scp->length))
582             _InterlockedAnd(&scp->mask, ~CM_SCACHEMASK_LENGTH);
583         code = cm_MergeStatus(NULL, scp, &outStatus, &volSync, userp, reqp, CM_MERGEFLAG_STOREDATA);
584     } else {
585         InterlockedDecrement(&scp->activeRPCs);
586     }
587     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
588
589     return code;
590 }
591
592 long cm_BufRead(cm_buf_t *bufp, long nbytes, long *bytesReadp, cm_user_t *userp)
593 {
594     *bytesReadp = 0;
595
596     /* now return a code that means that I/O is done */
597     return 0;
598 }
599
600 /*
601  * stabilize scache entry with CM_SCACHESYNC_SETSIZE.  This prevents any new
602  * data buffers to be allocated, new data to be fetched from the file server,
603  * and writes to be accepted from the application but permits dirty buffers
604  * to be written to the file server.
605  *
606  * Stabilize uses cm_SyncOp to maintain the cm_scache_t in this stable state
607  * instead of holding the rwlock exclusively.  This permits background stores
608  * to be performed in parallel and in particular allow FlushFile to be
609  * implemented without violating the locking hierarchy.
610  */
611 long cm_BufStabilize(void *vscp, cm_user_t *userp, cm_req_t *reqp)
612 {
613     cm_scache_t *scp = vscp;
614     long code;
615
616     lock_ObtainWrite(&scp->rw);
617     code = cm_SyncOp(scp, NULL, userp, reqp, 0,
618                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
619     lock_ReleaseWrite(&scp->rw);
620
621     return code;
622 }
623
624 /* undoes the work that cm_BufStabilize does: releases lock so things can change again */
625 long cm_BufUnstabilize(void *vscp, cm_user_t *userp)
626 {
627     cm_scache_t *scp = vscp;
628
629     lock_ObtainWrite(&scp->rw);
630     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
631
632     lock_ReleaseWrite(&scp->rw);
633
634     /* always succeeds */
635     return 0;
636 }
637
638 cm_buf_ops_t cm_bufOps = {
639     cm_BufWrite,
640     cm_BufRead,
641     cm_BufStabilize,
642     cm_BufUnstabilize
643 };
644
645 long cm_ValidateDCache(void)
646 {
647     return buf_ValidateBuffers();
648 }
649
650 long cm_ShutdownDCache(void)
651 {
652     return 0;
653 }
654
655 int cm_InitDCache(int newFile, long chunkSize, afs_uint64 nbuffers)
656 {
657     return buf_Init(newFile, &cm_bufOps, nbuffers);
658 }
659
660 /* check to see if we have an up-to-date buffer.  The buffer must have
661  * previously been obtained by calling buf_Get.
662  *
663  * Make sure we have a callback, and that the dataversion matches.
664  *
665  * Scp must be locked.
666  *
667  * Bufp *may* be locked.
668  */
669 int cm_HaveBuffer(cm_scache_t *scp, cm_buf_t *bufp, int isBufLocked)
670 {
671     int code;
672     if (!cm_HaveCallback(scp))
673         return 0;
674     if ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED))
675         return 1;
676     if (bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow)
677         return 1;
678     if (bufp->offset.QuadPart >= scp->serverLength.QuadPart)
679         return 1;
680     if (!isBufLocked) {
681         code = lock_TryMutex(&bufp->mx);
682         if (code == 0) {
683             /* don't have the lock, and can't lock it, then
684              * return failure.
685              */
686             return 0;
687         }
688     }
689
690     /* remember dirty flag for later */
691     code = bufp->flags & CM_BUF_DIRTY;
692
693     /* release lock if we obtained it here */
694     if (!isBufLocked)
695         lock_ReleaseMutex(&bufp->mx);
696
697     /* if buffer was dirty, buffer is acceptable for use */
698     if (code)
699         return 1;
700     else
701         return 0;
702 }
703
704 /*
705  * used when deciding whether to do a background fetch or not.
706  * call with scp->rw write-locked.
707  */
708 afs_int32
709 cm_CheckFetchRange(cm_scache_t *scp, osi_hyper_t *startBasep, osi_hyper_t *length,
710                         cm_user_t *userp, cm_req_t *reqp, osi_hyper_t *realBasep)
711 {
712     osi_hyper_t tbase;
713     osi_hyper_t tlength;
714     osi_hyper_t tblocksize;
715     long code;
716     cm_buf_t *bp;
717     int stop;
718
719     /* now scan all buffers in the range, looking for any that look like
720      * they need work.
721      */
722     tbase = *startBasep;
723     tlength = *length;
724     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
725     stop = 0;
726     while (LargeIntegerGreaterThanZero(tlength)) {
727         /* get callback so we can do a meaningful dataVersion comparison */
728         code = cm_SyncOp(scp, NULL, userp, reqp, 0,
729                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
730         if (code)
731             return code;
732
733         if (LargeIntegerGreaterThanOrEqualTo(tbase, scp->length)) {
734             /* we're past the end of file */
735             break;
736         }
737
738         bp = buf_Find(&scp->fid, &tbase);
739         /* We cheat slightly by not locking the bp mutex. */
740         if (bp) {
741             if ((bp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING)) == 0
742                  && (bp->dataVersion < scp->bufDataVersionLow || bp->dataVersion > scp->dataVersion))
743                 stop = 1;
744             buf_Release(bp);
745             bp = NULL;
746         }
747         else
748             stop = 1;
749
750         /* if this buffer is essentially guaranteed to require a fetch,
751          * break out here and return this position.
752          */
753         if (stop)
754             break;
755
756         tbase = LargeIntegerAdd(tbase, tblocksize);
757         tlength = LargeIntegerSubtract(tlength,  tblocksize);
758     }
759
760     /* if we get here, either everything is fine or 'stop' stopped us at a
761      * particular buffer in the range that definitely needs to be fetched.
762      */
763     if (stop == 0) {
764         /* return non-zero code since realBasep won't be valid */
765         code = -1;
766     }
767     else {
768         /* successfully found a page that will need fetching */
769         *realBasep = tbase;
770         code = 0;
771     }
772     return code;
773 }
774
775 afs_int32
776 cm_BkgStore(cm_scache_t *scp, void *rockp, cm_user_t *userp, cm_req_t *reqp)
777 {
778     osi_hyper_t toffset;
779     afs_uint32 length;
780     long code = 0;
781     afs_uint32 req_flags = reqp->flags;
782
783     toffset = ((rock_BkgStore_t *)rockp)->offset;
784     length = ((rock_BkgStore_t *)rockp)->length;
785
786     if (scp->flags & CM_SCACHEFLAG_DELETED) {
787         osi_Log4(afsd_logp, "Skipping BKG store - Deleted scp 0x%p, offset 0x%x:%08x, length 0x%x",
788                  scp, toffset.HighPart, toffset.LowPart, length);
789     } else {
790         /* Retries will be performed by the BkgDaemon thread if appropriate */
791         reqp->flags |= CM_REQ_NORETRY;
792
793         osi_Log4(afsd_logp, "Starting BKG store scp 0x%p, offset 0x%x:%08x, length 0x%x",
794                  scp, toffset.HighPart, toffset.LowPart, length);
795
796         code = cm_BufWrite(scp, &toffset, length, /* flags */ 0, userp, reqp);
797
798         osi_Log5(afsd_logp, "Finished BKG store scp 0x%p, offset 0x%x:%08x, length 0x%x, code 0x%x",
799                  scp, toffset.HighPart, toffset.LowPart, length, code);
800
801         reqp->flags = req_flags;
802     }
803
804     /*
805      * Keep the following list synchronized with the
806      * error code list in cm_BkgDaemon
807      */
808     switch ( code ) {
809     case CM_ERROR_TIMEDOUT: /* or server restarting */
810     case CM_ERROR_RETRY:
811     case CM_ERROR_WOULDBLOCK:
812     case CM_ERROR_ALLBUSY:
813     case CM_ERROR_ALLDOWN:
814     case CM_ERROR_ALLOFFLINE:
815     case CM_ERROR_PARTIALWRITE:
816         break;  /* cm_BkgDaemon will re-insert the request in the queue */
817     case 0:
818     default:
819         lock_ObtainWrite(&scp->rw);
820         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_ASYNCSTORE);
821         lock_ReleaseWrite(&scp->rw);
822     }
823
824     return code;
825 }
826
827 /* Called with scp locked */
828 void cm_ClearPrefetchFlag(long code, cm_scache_t *scp, osi_hyper_t *base, osi_hyper_t *length)
829 {
830     osi_hyper_t end;
831
832     if (code == 0) {
833         end =  LargeIntegerAdd(*base, *length);
834         if (LargeIntegerGreaterThan(*base, scp->prefetch.base))
835             scp->prefetch.base = *base;
836         if (LargeIntegerGreaterThan(end, scp->prefetch.end))
837             scp->prefetch.end = end;
838     }
839     _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_PREFETCHING);
840 }
841
842 /* do the prefetch.  if the prefetch fails, return 0 (success)
843  * because there is no harm done.  */
844 afs_int32
845 cm_BkgPrefetch(cm_scache_t *scp, void *rockp, cm_user_t *userp, cm_req_t *reqp)
846 {
847     osi_hyper_t length;
848     osi_hyper_t base;
849     osi_hyper_t offset;
850     osi_hyper_t end;
851     osi_hyper_t fetched;
852     osi_hyper_t tblocksize;
853     afs_int32 code;
854     int rxheld = 0;
855     cm_buf_t *bp = NULL;
856     afs_uint32 req_flags;
857
858     /* Retries will be performed by the BkgDaemon thread if appropriate */
859     req_flags = reqp->flags;
860     reqp->flags |= CM_REQ_NORETRY;
861
862     fetched.LowPart = 0;
863     fetched.HighPart = 0;
864     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
865     base = ((rock_BkgFetch_t *)rockp)->base;
866     length = ((rock_BkgFetch_t *)rockp)->length;
867
868     end = LargeIntegerAdd(base, length);
869
870     osi_Log5(afsd_logp, "Starting BKG prefetch scp 0x%p offset 0x%x:%x length 0x%x:%x",
871              scp, base.HighPart, base.LowPart, length.HighPart, length.LowPart);
872
873     for ( code = 0, offset = base;
874           code == 0 && LargeIntegerLessThan(offset, end);
875           offset = LargeIntegerAdd(offset, tblocksize) )
876     {
877         if (rxheld) {
878             lock_ReleaseWrite(&scp->rw);
879             rxheld = 0;
880         }
881
882         code = buf_Get(scp, &offset, reqp, 0, &bp);
883         if (code)
884             break;
885
886         if (bp->cmFlags & CM_BUF_CMFETCHING) {
887             /* skip this buffer as another thread is already fetching it */
888             if (!rxheld) {
889                 lock_ObtainWrite(&scp->rw);
890                 rxheld = 1;
891             }
892             buf_Release(bp);
893             bp = NULL;
894             continue;
895         }
896
897         if (!rxheld) {
898             lock_ObtainWrite(&scp->rw);
899             rxheld = 1;
900         }
901
902         code = cm_GetBuffer(scp, bp, NULL, userp, reqp);
903         if (code == 0)
904             fetched = LargeIntegerAdd(fetched, tblocksize);
905         buf_Release(bp);
906     }
907
908     if (!rxheld) {
909         lock_ObtainWrite(&scp->rw);
910         rxheld = 1;
911     }
912
913     cm_ClearPrefetchFlag(LargeIntegerGreaterThanZero(fetched) ? 0 : code,
914                          scp, &base, &fetched);
915
916     /* wakeup anyone who is waiting */
917     if (!osi_QIsEmpty(&scp->waitQueueH)) {
918         osi_Log1(afsd_logp, "CM BkgPrefetch Waking scp 0x%p", scp);
919         osi_Wakeup((LONG_PTR) &scp->flags);
920     }
921     lock_ReleaseWrite(&scp->rw);
922
923     osi_Log4(afsd_logp, "Ending BKG prefetch scp 0x%p code 0x%x fetched 0x%x:%x",
924              scp, code, fetched.HighPart, fetched.LowPart);
925
926     reqp->flags = req_flags;
927     return code;
928 }
929
930 /* a read was issued to offsetp, and we have to determine whether we should
931  * do a prefetch of the next chunk.
932  */
933 void cm_ConsiderPrefetch(cm_scache_t *scp, osi_hyper_t *offsetp, afs_uint32 count,
934                          cm_user_t *userp, cm_req_t *reqp)
935 {
936     long code;
937     int  rwheld = 0;
938     osi_hyper_t realBase;
939     osi_hyper_t readBase;
940     osi_hyper_t readLength;
941     osi_hyper_t readEnd;
942     osi_hyper_t tblocksize;             /* a long long temp variable */
943     rock_BkgFetch_t *rockp;
944
945     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
946
947     readBase = *offsetp;
948     /* round up to chunk boundary */
949     readBase.LowPart += (cm_chunkSize-1);
950     readBase.LowPart &= (-cm_chunkSize);
951
952     readLength = ConvertLongToLargeInteger(count);
953
954     lock_ObtainWrite(&scp->rw);
955     rwheld = 1;
956     if ((scp->flags & CM_SCACHEFLAG_PREFETCHING)
957          || LargeIntegerLessThanOrEqualTo(readBase, scp->prefetch.base)) {
958         lock_ReleaseWrite(&scp->rw);
959         return;
960     }
961     _InterlockedOr(&scp->flags, CM_SCACHEFLAG_PREFETCHING);
962
963     /* start the scan at the latter of the end of this read or
964      * the end of the last fetched region.
965      */
966     if (LargeIntegerGreaterThan(scp->prefetch.end, readBase))
967         readBase = scp->prefetch.end;
968
969     code = cm_CheckFetchRange(scp, &readBase, &readLength, userp, reqp,
970                               &realBase);
971     if (code) {
972         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_PREFETCHING);
973         lock_ReleaseWrite(&scp->rw);
974         return; /* can't find something to prefetch */
975     }
976
977     readEnd = LargeIntegerAdd(realBase, readLength);
978
979     if (rwheld)
980         lock_ReleaseWrite(&scp->rw);
981
982     osi_Log2(afsd_logp, "BKG Prefetch request scp 0x%p, base 0x%x",
983              scp, realBase.LowPart);
984
985     rockp = malloc(sizeof(*rockp));
986     if (rockp == NULL) {
987         return; /* can't proceed without a rock */
988     }
989
990     rockp->base = realBase;
991     rockp->length = readLength;
992
993     /* cm_BkgDaemon frees the rock */
994     cm_QueueBKGRequest(scp, cm_BkgPrefetch, rockp, 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     biop->reserved = (cm_chunkSize / cm_data.buf_blockSize);
1035     buf_ReserveBuffers(biop->reserved);
1036     lock_ObtainWrite(&scp->rw);
1037
1038     bufp = NULL;
1039     for (temp = 0; temp < inSize; temp += cm_data.buf_blockSize) {
1040         thyper = ConvertLongToLargeInteger(temp);
1041         tbase = LargeIntegerAdd(*inOffsetp, thyper);
1042
1043         bufp = buf_Find(&scp->fid, &tbase);
1044         if (bufp) {
1045             /* get buffer mutex and scp mutex safely */
1046             lock_ReleaseWrite(&scp->rw);
1047             lock_ObtainMutex(&bufp->mx);
1048
1049             /*
1050              * if the buffer is actively involved in I/O
1051              * we wait for the I/O to complete.
1052              */
1053             if (bufp->flags & (CM_BUF_WRITING|CM_BUF_READING))
1054                 buf_WaitIO(scp, bufp);
1055
1056             lock_ObtainWrite(&scp->rw);
1057             flags = CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_STOREDATA | CM_SCACHESYNC_BUFLOCKED;
1058             code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1059             if (code) {
1060                 lock_ReleaseMutex(&bufp->mx);
1061                 buf_Release(bufp);
1062                 bufp = NULL;
1063                 buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1064                 return code;
1065             }
1066
1067             /* if the buffer is dirty, we're done */
1068             if (bufp->flags & CM_BUF_DIRTY) {
1069                 osi_assertx(!(bufp->flags & CM_BUF_WRITING),
1070                             "WRITING w/o CMSTORING in SetupStoreBIOD");
1071                 _InterlockedOr(&bufp->flags, CM_BUF_WRITING);
1072                 break;
1073             }
1074
1075             /* this buffer is clean, so there's no reason to process it */
1076             cm_SyncOpDone(scp, bufp, flags);
1077             lock_ReleaseMutex(&bufp->mx);
1078             buf_Release(bufp);
1079             bufp = NULL;
1080         }
1081     }
1082
1083     /* if we get here, if bufp is null, we didn't find any dirty buffers
1084      * that weren't already being stored back, so we just quit now.
1085      */
1086     if (!bufp) {
1087         return 0;
1088     }
1089
1090     /* don't need buffer mutex any more */
1091     lock_ReleaseMutex(&bufp->mx);
1092
1093     /* put this element in the list */
1094     qdp = osi_QDAlloc();
1095     osi_SetQData(qdp, bufp);
1096
1097     if ( cm_verifyData )
1098         buf_ComputeCheckSum(bufp);
1099
1100     /* don't have to hold bufp, since held by buf_Find above */
1101     osi_QAddH((osi_queue_t **) &biop->bufListp,
1102               (osi_queue_t **) &biop->bufListEndp,
1103               &qdp->q);
1104     biop->length = cm_data.buf_blockSize;
1105     firstModOffset = bufp->offset;
1106     biop->offset = firstModOffset;
1107     bufp = NULL;        /* this buffer and reference added to the queue */
1108
1109     /* compute the window surrounding firstModOffset of size cm_chunkSize */
1110     scanStart = firstModOffset;
1111     scanStart.LowPart &= (-cm_chunkSize);
1112     thyper = ConvertLongToLargeInteger(cm_chunkSize);
1113     scanEnd = LargeIntegerAdd(scanStart, thyper);
1114
1115     flags = CM_SCACHESYNC_GETSTATUS
1116         | CM_SCACHESYNC_STOREDATA
1117         | CM_SCACHESYNC_BUFLOCKED;
1118
1119     /* start by looking backwards until scanStart */
1120     /* hyper version of cm_data.buf_blockSize */
1121     thyper = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1122     tbase = LargeIntegerSubtract(firstModOffset, thyper);
1123     while(LargeIntegerGreaterThanOrEqualTo(tbase, scanStart)) {
1124         /* see if we can find the buffer */
1125         bufp = buf_Find(&scp->fid, &tbase);
1126         if (!bufp)
1127             break;
1128
1129         /* try to lock it, and quit if we can't (simplifies locking) */
1130         lock_ReleaseWrite(&scp->rw);
1131         code = lock_TryMutex(&bufp->mx);
1132         lock_ObtainWrite(&scp->rw);
1133         if (code == 0) {
1134             buf_Release(bufp);
1135             bufp = NULL;
1136             break;
1137         }
1138
1139         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1140         if (code) {
1141             lock_ReleaseMutex(&bufp->mx);
1142             buf_Release(bufp);
1143             bufp = NULL;
1144             break;
1145         }
1146
1147         if (!(bufp->flags & CM_BUF_DIRTY)) {
1148             /* buffer is clean, so we shouldn't add it */
1149             cm_SyncOpDone(scp, bufp, flags);
1150             lock_ReleaseMutex(&bufp->mx);
1151             buf_Release(bufp);
1152             bufp = NULL;
1153             break;
1154         }
1155
1156         /* don't need buffer mutex any more */
1157         lock_ReleaseMutex(&bufp->mx);
1158
1159         /* we have a dirty buffer ready for storing.  Add it to the tail
1160          * of the list, since it immediately precedes all of the disk
1161          * addresses we've already collected.
1162          */
1163         qdp = osi_QDAlloc();
1164         osi_SetQData(qdp, bufp);
1165
1166         if ( cm_verifyData )
1167             buf_ComputeCheckSum(bufp);
1168
1169         /* no buf_hold necessary, since we have it held from buf_Find */
1170         osi_QAddT((osi_queue_t **) &biop->bufListp,
1171                   (osi_queue_t **) &biop->bufListEndp,
1172                   &qdp->q);
1173         bufp = NULL;            /* added to the queue */
1174
1175         /* update biod info describing the transfer */
1176         biop->offset = LargeIntegerSubtract(biop->offset, thyper);
1177         biop->length += cm_data.buf_blockSize;
1178
1179         /* update loop pointer */
1180         tbase = LargeIntegerSubtract(tbase, thyper);
1181     }   /* while loop looking for pages preceding the one we found */
1182
1183     /* now, find later dirty, contiguous pages, and add them to the list */
1184     /* hyper version of cm_data.buf_blockSize */
1185     thyper = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1186     tbase = LargeIntegerAdd(firstModOffset, thyper);
1187     while(LargeIntegerLessThan(tbase, scanEnd)) {
1188         /* see if we can find the buffer */
1189         bufp = buf_Find(&scp->fid, &tbase);
1190         if (!bufp)
1191             break;
1192
1193         /* try to lock it, and quit if we can't (simplifies locking) */
1194         lock_ReleaseWrite(&scp->rw);
1195         code = lock_TryMutex(&bufp->mx);
1196         lock_ObtainWrite(&scp->rw);
1197         if (code == 0) {
1198             buf_Release(bufp);
1199             bufp = NULL;
1200             break;
1201         }
1202
1203         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1204         if (code) {
1205             lock_ReleaseMutex(&bufp->mx);
1206             buf_Release(bufp);
1207             bufp = NULL;
1208             break;
1209         }
1210
1211         if (!(bufp->flags & CM_BUF_DIRTY)) {
1212             /* buffer is clean, so we shouldn't add it */
1213             cm_SyncOpDone(scp, bufp, flags);
1214             lock_ReleaseMutex(&bufp->mx);
1215             buf_Release(bufp);
1216             bufp = NULL;
1217             break;
1218         }
1219
1220         /* don't need buffer mutex any more */
1221         lock_ReleaseMutex(&bufp->mx);
1222
1223         /* we have a dirty buffer ready for storing.  Add it to the head
1224          * of the list, since it immediately follows all of the disk
1225          * addresses we've already collected.
1226          */
1227         qdp = osi_QDAlloc();
1228         osi_SetQData(qdp, bufp);
1229
1230         if ( cm_verifyData )
1231             buf_ComputeCheckSum(bufp);
1232
1233         /* no buf_hold necessary, since we have it held from buf_Find */
1234         osi_QAddH((osi_queue_t **) &biop->bufListp,
1235                   (osi_queue_t **) &biop->bufListEndp,
1236                   &qdp->q);
1237         bufp = NULL;
1238
1239         /* update biod info describing the transfer */
1240         biop->length += cm_data.buf_blockSize;
1241
1242         /* update loop pointer */
1243         tbase = LargeIntegerAdd(tbase, thyper);
1244     }   /* while loop looking for pages following the first page we found */
1245
1246     /* finally, we're done */
1247     return 0;
1248 }
1249
1250 /* scp must be locked; temporarily unlocked during processing.
1251  * If returns 0, returns buffers held in biop, and with
1252  * CM_BUF_CMFETCHING flags set.
1253  * If an error is returned, we don't return any buffers.
1254  */
1255 long cm_SetupFetchBIOD(cm_scache_t *scp, osi_hyper_t *offsetp,
1256                         cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
1257 {
1258     long code;
1259     cm_buf_t *tbp;
1260     osi_hyper_t tblocksize;             /* a long long temp variable */
1261     osi_hyper_t pageBase;               /* base offset we're looking at */
1262     osi_queueData_t *qdp;               /* one temp queue structure */
1263     osi_queueData_t *tqdp;              /* another temp queue structure */
1264     long collected;                     /* how many bytes have been collected */
1265     int isFirst;
1266     long flags;
1267     osi_hyper_t fileSize;               /* the # of bytes in the file */
1268     osi_queueData_t *heldBufListp;      /* we hold all buffers in this list */
1269     osi_queueData_t *heldBufListEndp;   /* first one */
1270     afs_uint64 reserving;
1271
1272     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1273
1274     biop->scp = scp;                    /* do not hold; held by caller */
1275     biop->userp = userp;                /* do not hold; held by caller */
1276     biop->reqp = reqp;
1277     biop->offset = *offsetp;
1278     /* null out the list of buffers */
1279     biop->bufListp = biop->bufListEndp = NULL;
1280     biop->reserved = 0;
1281
1282     /* first lookup the file's length, so we know when to stop */
1283     code = cm_SyncOp(scp, NULL, userp, reqp, 0,
1284                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1285     if (code)
1286         return code;
1287
1288     /* copy out size, since it may change */
1289     fileSize = scp->serverLength;
1290
1291     lock_ReleaseWrite(&scp->rw);
1292
1293     pageBase = *offsetp;
1294     collected = pageBase.LowPart & (cm_chunkSize - 1);
1295     heldBufListp = NULL;
1296     heldBufListEndp = NULL;
1297
1298     /*
1299      * Obtaining buffers can cause dirty buffers to be recycled, which
1300      * can cause a storeback, so cannot be done while we have buffers
1301      * reserved.
1302      *
1303      * To get around this, we get buffers twice.  Before reserving buffers,
1304      * we obtain and release each one individually.  After reserving
1305      * buffers, we try to obtain them again, but only by lookup, not by
1306      * recycling.  If a buffer has gone away while we were waiting for
1307      * the others, we just use whatever buffers we already have.
1308      *
1309      * On entry to this function, we are already holding a buffer, so we
1310      * can't wait for reservation.  So we call buf_TryReserveBuffers()
1311      * instead.  Not only that, we can't really even call buf_Get(), for
1312      * the same reason.  We can't avoid that, though.  To avoid deadlock
1313      * we allow only one thread to be executing the buf_Get()-buf_Release()
1314      * sequence at a time.
1315      */
1316
1317     /* first hold all buffers, since we can't hold any locks in buf_Get */
1318     while (1) {
1319         /* stop at chunk boundary */
1320         if (collected >= cm_chunkSize)
1321             break;
1322
1323         /* see if the next page would be past EOF */
1324         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize))
1325             break;
1326
1327         code = buf_Get(scp, &pageBase, reqp, 0, &tbp);
1328         if (code) {
1329             lock_ObtainWrite(&scp->rw);
1330             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1331             return code;
1332         }
1333
1334         buf_Release(tbp);
1335         tbp = NULL;
1336
1337         pageBase = LargeIntegerAdd(tblocksize, pageBase);
1338         collected += cm_data.buf_blockSize;
1339     }
1340
1341     /* reserve a chunk's worth of buffers if possible */
1342     reserving = buf_TryReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1343
1344     pageBase = *offsetp;
1345     collected = pageBase.LowPart & (cm_chunkSize - 1);
1346
1347     /* now hold all buffers, if they are still there */
1348     while (1) {
1349         /* stop at chunk boundary */
1350         if (collected >= cm_chunkSize)
1351             break;
1352
1353         /* see if the next page would be past EOF */
1354         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize))
1355             break;
1356
1357         tbp = buf_Find(&scp->fid, &pageBase);
1358         if (!tbp)
1359             break;
1360
1361         /* add the buffer to the list */
1362         qdp = osi_QDAlloc();
1363         osi_SetQData(qdp, tbp);
1364         osi_QAddH((osi_queue_t **)&heldBufListp,
1365                   (osi_queue_t **)&heldBufListEndp,
1366                   &qdp->q);
1367         /* leave tbp held (from buf_Get) */
1368
1369         if (!reserving)
1370             break;
1371
1372         collected += cm_data.buf_blockSize;
1373         pageBase = LargeIntegerAdd(tblocksize, pageBase);
1374     }
1375
1376     /* look at each buffer, adding it into the list if it looks idle and
1377      * filled with old data.  One special case: wait for idle if it is the
1378      * first buffer since we really need that one for our caller to make
1379      * any progress.
1380      */
1381     isFirst = 1;
1382     collected = 0;              /* now count how many we'll really use */
1383     for (tqdp = heldBufListEndp;
1384         tqdp;
1385           tqdp = (osi_queueData_t *) osi_QPrev(&tqdp->q)) {
1386         /* get a ptr to the held buffer */
1387         tbp = osi_GetQData(tqdp);
1388         pageBase = tbp->offset;
1389
1390         /* now lock the buffer lock */
1391         lock_ObtainMutex(&tbp->mx);
1392         lock_ObtainWrite(&scp->rw);
1393
1394         /* don't bother fetching over data that is already current */
1395         if (tbp->dataVersion <= scp->dataVersion && tbp->dataVersion >= scp->bufDataVersionLow) {
1396             /* we don't need this buffer, since it is current */
1397             lock_ReleaseWrite(&scp->rw);
1398             lock_ReleaseMutex(&tbp->mx);
1399             break;
1400         }
1401
1402         flags = CM_SCACHESYNC_FETCHDATA | CM_SCACHESYNC_BUFLOCKED;
1403         if (!isFirst)
1404             flags |= CM_SCACHESYNC_NOWAIT;
1405
1406         /* wait for the buffer to serialize, if required.  Doesn't
1407          * release the scp or buffer lock(s) if NOWAIT is specified.
1408          */
1409         code = cm_SyncOp(scp, tbp, userp, reqp, 0, flags);
1410         if (code) {
1411             lock_ReleaseWrite(&scp->rw);
1412             lock_ReleaseMutex(&tbp->mx);
1413             break;
1414         }
1415
1416         /* don't fetch over dirty buffers */
1417         if (tbp->flags & CM_BUF_DIRTY) {
1418             cm_SyncOpDone(scp, tbp, flags);
1419             lock_ReleaseWrite(&scp->rw);
1420             lock_ReleaseMutex(&tbp->mx);
1421             break;
1422         }
1423
1424         /* Release locks */
1425         lock_ReleaseWrite(&scp->rw);
1426         lock_ReleaseMutex(&tbp->mx);
1427
1428         /* add the buffer to the list */
1429         qdp = osi_QDAlloc();
1430         osi_SetQData(qdp, tbp);
1431         osi_QAddH((osi_queue_t **)&biop->bufListp,
1432                   (osi_queue_t **)&biop->bufListEndp,
1433                   &qdp->q);
1434         buf_Hold(tbp);
1435
1436         /* from now on, a failure just stops our collection process, but
1437          * we still do the I/O to whatever we've already managed to collect.
1438          */
1439         isFirst = 0;
1440         collected += cm_data.buf_blockSize;
1441     }
1442
1443     /* now, we've held in biop->bufListp all the buffer's we're really
1444      * interested in.  We also have holds left from heldBufListp, and we
1445      * now release those holds on the buffers.
1446      */
1447     for (qdp = heldBufListp; qdp; qdp = tqdp) {
1448         tqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1449         tbp = osi_GetQData(qdp);
1450         osi_QRemoveHT((osi_queue_t **) &heldBufListp,
1451                       (osi_queue_t **) &heldBufListEndp,
1452                       &qdp->q);
1453         osi_QDFree(qdp);
1454         buf_Release(tbp);
1455         tbp = NULL;
1456     }
1457
1458     /* Caller expects this */
1459     lock_ObtainWrite(&scp->rw);
1460
1461     /* if we got a failure setting up the first buffer, then we don't have
1462      * any side effects yet, and we also have failed an operation that the
1463      * caller requires to make any progress.  Give up now.
1464      */
1465     if (code && isFirst) {
1466         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1467         return code;
1468     }
1469
1470     /* otherwise, we're still OK, and should just return the I/O setup we've
1471      * got.
1472      */
1473     biop->length = collected;
1474     biop->reserved = reserving;
1475     return 0;
1476 }
1477
1478 /* release a bulk I/O structure that was setup by cm_SetupFetchBIOD or by
1479  * cm_SetupStoreBIOD
1480  */
1481 void cm_ReleaseBIOD(cm_bulkIO_t *biop, int isStore, long code, int scp_locked)
1482 {
1483     cm_scache_t *scp;           /* do not release; not held in biop */
1484     cm_buf_t *bufp;
1485     osi_queueData_t *qdp;
1486     osi_queueData_t *nqdp;
1487     int flags;
1488     int reportErrorToRedir = 0;
1489
1490     /* Give back reserved buffers */
1491     if (biop->reserved)
1492         buf_UnreserveBuffers(biop->reserved);
1493
1494     if (isStore)
1495         flags = CM_SCACHESYNC_STOREDATA;
1496     else
1497         flags = CM_SCACHESYNC_FETCHDATA;
1498
1499     scp = biop->scp;
1500     if (biop->bufListp) {
1501         for(qdp = biop->bufListp; qdp; qdp = nqdp) {
1502             /* lookup next guy first, since we're going to free this one */
1503             nqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1504
1505             /* extract buffer and free queue data */
1506             bufp = osi_GetQData(qdp);
1507             osi_QRemoveHT((osi_queue_t **) &biop->bufListp,
1508                            (osi_queue_t **) &biop->bufListEndp,
1509                            &qdp->q);
1510             osi_QDFree(qdp);
1511
1512             /* now, mark I/O as done, unlock the buffer and release it */
1513             if (scp_locked)
1514                 lock_ReleaseWrite(&scp->rw);
1515             lock_ObtainMutex(&bufp->mx);
1516             lock_ObtainWrite(&scp->rw);
1517             cm_SyncOpDone(scp, bufp, flags);
1518
1519             /* turn off writing and wakeup users */
1520             if (isStore) {
1521                 if (bufp->flags & CM_BUF_WAITING) {
1522                     osi_Log2(afsd_logp, "cm_ReleaseBIOD Waking [scp 0x%p] bp 0x%p", scp, bufp);
1523                     osi_Wakeup((LONG_PTR) bufp);
1524                 }
1525                 if (code) {
1526                     _InterlockedAnd(&bufp->flags, ~CM_BUF_WRITING);
1527                     switch (code) {
1528                     case CM_ERROR_NOSUCHFILE:
1529                     case CM_ERROR_BADFD:
1530                     case CM_ERROR_NOACCESS:
1531                     case CM_ERROR_QUOTA:
1532                     case CM_ERROR_SPACE:
1533                     case CM_ERROR_TOOBIG:
1534                     case CM_ERROR_READONLY:
1535                     case CM_ERROR_NOSUCHPATH:
1536                     case EIO:
1537                     case CM_ERROR_INVAL_NET_RESP:
1538                     case CM_ERROR_UNKNOWN:
1539                         /*
1540                          * Apply the fatal error to this buffer.
1541                          */
1542                         _InterlockedAnd(&bufp->flags, ~CM_BUF_DIRTY);
1543                         _InterlockedOr(&bufp->flags, CM_BUF_ERROR);
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 rxbytes;                       /* 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                 rxbytes = temp;
2003
2004                 while (rxbytes > 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                     rxbytes -= 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 rxbytes of data */
2060                 rxbytes = (afs_uint32)(length_found > cm_data.buf_blockSize ? cm_data.buf_blockSize : length_found);
2061                 temp = rx_Read(rxcallp, bufferp, rxbytes);
2062                 if (temp < rxbytes) {
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             rxbytes = 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             rxbytes = (long) (bufferp - tbufp->datap);
2128
2129             /* bytes left to zero */
2130             rxbytes = cm_data.buf_blockSize - rxbytes;
2131 #endif /* USE_RX_IOVEC */
2132             while(qdp) {
2133                 if (rxbytes != 0)
2134                     memset(bufferp, 0, rxbytes);
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                 rxbytes = 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                 int * bytes_readp, 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 rxbytes;                       /* 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     if (bytes_readp)
2251         *bytes_readp = 0;
2252
2253     memset(&afsStatus, 0, sizeof(afsStatus));
2254     memset(&callback, 0, sizeof(callback));
2255     memset(&volSync, 0, sizeof(volSync));
2256
2257     /* now, the buffer may or may not be filled with good data (buf_GetNewLocked
2258      * drops lots of locks, and may indeed return a properly initialized
2259      * buffer, although more likely it will just return a new, empty, buffer.
2260      */
2261
2262 #ifdef AFS_FREELANCE_CLIENT
2263
2264     // yj: if they're trying to get the /afs directory, we need to
2265     // handle it differently, since it's local rather than on any
2266     // server
2267
2268     getroot = (scp==cm_data.rootSCachep);
2269     if (getroot)
2270         osi_Log1(afsd_logp,"GetBuffer returns cm_data.rootSCachep=%x",cm_data.rootSCachep);
2271 #endif
2272
2273     cm_AFSFidFromFid(&tfid, &scp->fid);
2274
2275     if (LargeIntegerGreaterThan(LargeIntegerAdd(*offsetp,
2276                                                 ConvertLongToLargeInteger(data_length)),
2277                                 ConvertLongToLargeInteger(LONG_MAX))) {
2278         require_64bit_ops = 1;
2279     }
2280
2281     InterlockedIncrement(&scp->activeRPCs);
2282     osi_Log2(afsd_logp, "cm_GetData: fetching data scp %p DV 0x%x", scp, scp->dataVersion);
2283
2284 #ifdef AFS_FREELANCE_CLIENT
2285
2286     // yj code
2287     // if getroot then we don't need to make any calls
2288     // just return fake data
2289
2290     if (cm_freelanceEnabled && getroot) {
2291         // setup the fake status
2292         afsStatus.InterfaceVersion = 0x1;
2293         afsStatus.FileType = 0x2;
2294         afsStatus.LinkCount = scp->linkCount;
2295         afsStatus.Length = cm_fakeDirSize;
2296         afsStatus.DataVersion = (afs_uint32)(cm_data.fakeDirVersion & 0xFFFFFFFF);
2297         afsStatus.Author = 0x1;
2298         afsStatus.Owner = 0x0;
2299         afsStatus.CallerAccess = 0x9;
2300         afsStatus.AnonymousAccess = 0x9;
2301         afsStatus.UnixModeBits = 0x1ff;
2302         afsStatus.ParentVnode = 0x1;
2303         afsStatus.ParentUnique = 0x1;
2304         afsStatus.ResidencyMask = 0;
2305         afsStatus.ClientModTime = (afs_uint32)FakeFreelanceModTime;
2306         afsStatus.ServerModTime = (afs_uint32)FakeFreelanceModTime;
2307         afsStatus.Group = 0;
2308         afsStatus.SyncCounter = 0;
2309         afsStatus.dataVersionHigh = (afs_uint32)(cm_data.fakeDirVersion >> 32);
2310         afsStatus.lockCount = 0;
2311         afsStatus.Length_hi = 0;
2312         afsStatus.errorCode = 0;
2313         memset(&volSync, 0, sizeof(volSync));
2314
2315         // once we're done setting up the status info,
2316         // we just fill the buffer pages with fakedata
2317         // from cm_FakeRootDir. Extra pages are set to
2318         // 0.
2319
2320         lock_ObtainMutex(&cm_Freelance_Lock);
2321         t1 = offsetp->LowPart;
2322         memset(datap, 0, data_length);
2323         t2 = cm_fakeDirSize - t1;
2324         if (t2 > data_length)
2325             t2 = data_length;
2326         if (t2 > 0)
2327             memcpy(datap, cm_FakeRootDir+t1, t2);
2328         lock_ReleaseMutex(&cm_Freelance_Lock);
2329
2330         // once we're done, we skip over the part of the
2331         // code that does the ACTUAL fetching of data for
2332         // real files
2333
2334         goto fetchingcompleted;
2335     }
2336
2337 #endif /* AFS_FREELANCE_CLIENT */
2338
2339     if (scp_locked) {
2340         lock_ReleaseWrite(&scp->rw);
2341         scp_locked = 0;
2342     }
2343
2344     /* now make the call */
2345     do {
2346         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2347         if (code)
2348             continue;
2349
2350         rxconnp = cm_GetRxConn(connp);
2351         rxcallp = rx_NewCall(rxconnp);
2352         rx_PutConnection(rxconnp);
2353
2354         nbytes = nbytes_hi = 0;
2355
2356         if (SERVERHAS64BIT(connp)) {
2357             call_was_64bit = 1;
2358
2359             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
2360                      scp, offsetp->HighPart, offsetp->LowPart, data_length);
2361
2362             code = StartRXAFS_FetchData64(rxcallp, &tfid, offsetp->QuadPart, data_length);
2363
2364             if (code == 0) {
2365                 temp = rx_Read32(rxcallp, &nbytes_hi);
2366                 if (temp == sizeof(afs_int32)) {
2367                     nbytes_hi = ntohl(nbytes_hi);
2368                 } else {
2369                     nbytes_hi = 0;
2370                     code = rx_Error(rxcallp);
2371                     code1 = rx_EndCall(rxcallp, code);
2372                     rxcallp = NULL;
2373                 }
2374             }
2375         } else {
2376             call_was_64bit = 0;
2377         }
2378
2379         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
2380             if (require_64bit_ops) {
2381                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
2382                 code = CM_ERROR_TOOBIG;
2383             } else {
2384                 if (!rxcallp) {
2385                     rxconnp = cm_GetRxConn(connp);
2386                     rxcallp = rx_NewCall(rxconnp);
2387                     rx_PutConnection(rxconnp);
2388                 }
2389
2390                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
2391                          scp, offsetp->LowPart, data_length);
2392
2393                 code = StartRXAFS_FetchData(rxcallp, &tfid, offsetp->LowPart, data_length);
2394
2395                 SET_SERVERHASNO64BIT(connp);
2396             }
2397         }
2398
2399         if (code == 0) {
2400             temp  = rx_Read32(rxcallp, &nbytes);
2401             if (temp == sizeof(afs_int32)) {
2402                 nbytes = ntohl(nbytes);
2403                 FillInt64(length_found, nbytes_hi, nbytes);
2404                 if (length_found > data_length) {
2405                     /*
2406                      * prior to 1.4.12 and 1.5.65 the file server would return
2407                      * (filesize - offset) if the requested offset was greater than
2408                      * the filesize.  The correct return value would have been zero.
2409                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
2410                      * is a race between two RPCs issues by this cache manager, the
2411                      * correct thing will happen the second time.
2412                      */
2413                     osi_Log0(afsd_logp, "cm_GetData length_found > data_length");
2414                     fs_fetchdata_offset_bug = 1;
2415                 }
2416             } else {
2417                 osi_Log1(afsd_logp, "cm_GetData rx_Read32 returns %d != 4", temp);
2418                 code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2419             }
2420         }
2421         /* for the moment, nbytes_hi will always be 0 if code == 0
2422            because data_length is a 32-bit quantity. */
2423
2424         if (code == 0) {
2425             /* fill length_found of data from the pipe into the pages.
2426              * When we stop, qdp will point at the last page we're
2427              * dealing with, and bufferp will tell us where we
2428              * stopped.  We'll need this info below when we clear
2429              * the remainder of the last page out (and potentially
2430              * clear later pages out, if we fetch past EOF).
2431              */
2432             while (length_found > 0) {
2433 #ifdef USE_RX_IOVEC
2434                 struct iovec tiov[RX_MAXIOVECS];
2435                 afs_int32 tnio, iov, iov_offset;
2436
2437                 temp = rx_Readv(rxcallp, tiov, &tnio, RX_MAXIOVECS, length_found);
2438                 osi_Log1(afsd_logp, "cm_GetData rx_Readv returns %d", temp);
2439                 if (temp != length_found && temp < data_length) {
2440                     /*
2441                      * If the file server returned (filesize - offset),
2442                      * then the first rx_Read will return zero octets of data.
2443                      * If it does, do not treat it as an error.  Correct the
2444                      * length_found and continue as if the file server said
2445                      * it was sending us zero octets of data.
2446                      */
2447                     if (fs_fetchdata_offset_bug && first_read) {
2448                         length_found = 0;
2449                         break;
2450                     } else if (temp <= 0) {
2451                         code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2452                         break;
2453                     }
2454                 }
2455
2456                 iov = 0;
2457                 iov_offset = 0;
2458                 rxbytes = temp;
2459
2460                 while (rxbytes > 0) {
2461                     afs_int32 len;
2462
2463                     osi_assertx(bufferp != NULL, "null cm_buf_t");
2464
2465                     len = min(tiov[iov].iov_len - iov_offset, data_length - buffer_offset);
2466                     memcpy(bufferp + buffer_offset, tiov[iov].iov_base + iov_offset, len);
2467                     iov_offset += len;
2468                     buffer_offset += len;
2469                     rxbytes -= len;
2470
2471                     if (iov_offset == tiov[iov].iov_len) {
2472                         iov++;
2473                         iov_offset = 0;
2474                     }
2475                 }
2476
2477                 length_found -= temp;
2478 #else /* USE_RX_IOVEC */
2479                 /* assert that there are still more buffers;
2480                  * our check above for length_found being less than
2481                  * data_length should ensure this.
2482                  */
2483                 osi_assertx(bufferp != NULL, "null cm_buf_t");
2484
2485                 /* read rxbytes of data */
2486                 rxbytes = (afs_uint32)(length_found > data_length ? data_length : length_found);
2487                 temp = rx_Read(rxcallp, bufferp, rxbytes);
2488                 if (temp < rxbytes) {
2489                     /*
2490                      * If the file server returned (filesize - offset),
2491                      * then the first rx_Read will return zero octets of data.
2492                      * If it does, do not treat it as an error.  Correct the
2493                      * length_found and continue as if the file server said
2494                      * it was sending us zero octets of data.
2495                      */
2496                     if (fs_fetchdata_offset_bug && first_read) {
2497                         length_found = 0;
2498                         break;
2499                     } else if (temp <= 0) {
2500                         code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2501                         break;
2502                     }
2503                 }
2504                 first_read = 0;
2505
2506                 /* and adjust counters */
2507                 length_found -= temp;
2508 #endif /* USE_RX_IOVEC */
2509             }
2510
2511             /* zero out remainder of last pages, in case we are
2512              * fetching past EOF.  We were fetching an integral #
2513              * of pages, but stopped, potentially in the middle of
2514              * a page.  Zero the remainder of that page, and then
2515              * all of the rest of the pages.
2516              */
2517 #ifdef USE_RX_IOVEC
2518             rxbytes = data_length - buffer_offset;
2519             bufferp = datap + buffer_offset;
2520 #else /* USE_RX_IOVEC */
2521             /* bytes fetched */
2522             osi_assertx((bufferp - datap) < LONG_MAX, "data >= LONG_MAX");
2523             rxbytes = (long) (bufferp - datap);
2524
2525             /* bytes left to zero */
2526             rxbytes = data_length - rxbytes;
2527 #endif /* USE_RX_IOVEC */
2528             if (rxbytes != 0)
2529                 memset(bufferp, 0, rxbytes);
2530         }
2531
2532         if (code == 0) {
2533             if (call_was_64bit)
2534                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
2535             else
2536                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
2537         } else {
2538             if (call_was_64bit)
2539                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
2540             else
2541                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
2542         }
2543
2544         if (rxcallp)
2545             code1 = rx_EndCall(rxcallp, code);
2546
2547         if (code1 == RXKADUNKNOWNKEY)
2548             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
2549
2550         /* If we are avoiding a file server bug, ignore the error state */
2551         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
2552             /* Clone the current status info and clear the error state */
2553             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
2554             if (scp_locked) {
2555                 lock_ReleaseWrite(&scp->rw);
2556                 scp_locked = 0;
2557             }
2558             code = 0;
2559         /* Prefer the error value from FetchData over rx_EndCall */
2560         } else if (code == 0 && code1 != 0)
2561             code = code1;
2562         osi_Log0(afsd_logp, "CALL FetchData DONE");
2563
2564     } while (cm_Analyze(connp, userp, reqp, &scp->fid, NULL, 0, &afsStatus, &volSync, NULL, NULL, code));
2565
2566   fetchingcompleted:
2567     code = cm_MapRPCError(code, reqp);
2568
2569     if (!scp_locked)
2570         lock_ObtainWrite(&scp->rw);
2571
2572     if (code == 0)
2573         code = cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, CM_MERGEFLAG_FETCHDATA);
2574     else
2575         InterlockedDecrement(&scp->activeRPCs);
2576
2577     *bytes_readp = (long) (bufferp - datap);
2578
2579     return code;
2580 }
2581
2582 /*
2583  * cm_VerifyStoreData.   Function passed a rw locked cm_scache_t and a store data biod.
2584  *
2585  * Return 1 if the data verifies; 0 if not.
2586  */
2587
2588 long
2589 cm_VerifyStoreData(cm_bulkIO_t *biod, cm_scache_t *savedScp)
2590 {
2591     long code=0, code1=0;
2592     afs_uint32 nbytes;                  /* bytes in transfer */
2593     afs_uint32 nbytes_hi = 0;           /* high-order 32 bits of bytes in transfer */
2594     afs_uint64 length_found = 0;
2595     long rxbytes;                       /* bytes in rx_Read call */
2596     long temp;
2597     AFSFetchStatus afsStatus;
2598     AFSCallBack callback;
2599     AFSVolSync volSync;
2600     AFSFid tfid;
2601     struct rx_call *rxcallp;
2602     struct rx_connection *rxconnp;
2603     cm_conn_t *connp;
2604     int require_64bit_ops = 0;
2605     int call_was_64bit = 0;
2606     int fs_fetchdata_offset_bug = 0;
2607     int first_read = 1;
2608     int scp_locked = 1;
2609     char * bufferp = malloc(biod->length);
2610     long verified = 0;
2611     cm_scache_t *scp = biod->scp;
2612     cm_user_t *userp = biod->userp;
2613     cm_req_t *reqp = biod->reqp;
2614     afs_uint64 dataVersion = scp->dataVersion;
2615
2616     memset(&afsStatus, 0, sizeof(afsStatus));
2617     memset(&callback, 0, sizeof(callback));
2618     memset(&volSync, 0, sizeof(volSync));
2619     memset(bufferp, 0, biod->length);
2620
2621     cm_AFSFidFromFid(&tfid, &scp->fid);
2622
2623     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod->offset,
2624                                                 ConvertLongToLargeInteger(biod->length)),
2625                                 ConvertLongToLargeInteger(LONG_MAX))) {
2626         require_64bit_ops = 1;
2627     }
2628
2629     InterlockedIncrement(&scp->activeRPCs);
2630     osi_Log2(afsd_logp, "cm_VerifyStoreData: fetching data scp %p DV 0x%x", scp, scp->dataVersion);
2631
2632     if (scp_locked) {
2633         lock_ReleaseWrite(&scp->rw);
2634         scp_locked = 0;
2635     }
2636
2637     /* now make the call */
2638     do {
2639         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2640         if (code)
2641             continue;
2642
2643         rxconnp = cm_GetRxConn(connp);
2644         rxcallp = rx_NewCall(rxconnp);
2645         rx_PutConnection(rxconnp);
2646
2647         nbytes = nbytes_hi = 0;
2648
2649         if (SERVERHAS64BIT(connp)) {
2650             call_was_64bit = 1;
2651
2652             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
2653                      scp, biod->offset.HighPart, biod->offset.LowPart, biod->length);
2654
2655             code = StartRXAFS_FetchData64(rxcallp, &tfid, biod->offset.QuadPart, biod->length);
2656
2657             if (code == 0) {
2658                 temp = rx_Read32(rxcallp, &nbytes_hi);
2659                 if (temp == sizeof(afs_int32)) {
2660                     nbytes_hi = ntohl(nbytes_hi);
2661                 } else {
2662                     nbytes_hi = 0;
2663                     code = rx_Error(rxcallp);
2664                     code1 = rx_EndCall(rxcallp, code);
2665                     rxcallp = NULL;
2666                 }
2667             }
2668         } else {
2669             call_was_64bit = 0;
2670         }
2671
2672         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
2673             if (require_64bit_ops) {
2674                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
2675                 code = CM_ERROR_TOOBIG;
2676             } else {
2677                 if (!rxcallp) {
2678                     rxconnp = cm_GetRxConn(connp);
2679                     rxcallp = rx_NewCall(rxconnp);
2680                     rx_PutConnection(rxconnp);
2681                 }
2682
2683                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
2684                          scp, biod->offset.LowPart, biod->length);
2685
2686                 code = StartRXAFS_FetchData(rxcallp, &tfid, biod->offset.LowPart, biod->length);
2687
2688                 SET_SERVERHASNO64BIT(connp);
2689             }
2690         }
2691
2692         if (code == 0) {
2693             temp  = rx_Read32(rxcallp, &nbytes);
2694             if (temp == sizeof(afs_int32)) {
2695                 nbytes = ntohl(nbytes);
2696                 FillInt64(length_found, nbytes_hi, nbytes);
2697                 if (length_found > biod->length) {
2698                     /*
2699                      * prior to 1.4.12 and 1.5.65 the file server would return
2700                      * (filesize - offset) if the requested offset was greater than
2701                      * the filesize.  The correct return value would have been zero.
2702                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
2703                      * is a race between two RPCs issues by this cache manager, the
2704                      * correct thing will happen the second time.
2705                      */
2706                     osi_Log0(afsd_logp, "cm_GetData length_found > biod.length");
2707                     fs_fetchdata_offset_bug = 1;
2708                 }
2709             } else {
2710                 osi_Log1(afsd_logp, "cm_GetData rx_Read32 returns %d != 4", temp);
2711                 code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2712             }
2713         }
2714         /* for the moment, nbytes_hi will always be 0 if code == 0
2715            because data_length is a 32-bit quantity. */
2716
2717         if (code == 0) {
2718             /* fill length_found of data from the pipe into the pages.
2719              * When we stop, qdp will point at the last page we're
2720              * dealing with, and bufferp will tell us where we
2721              * stopped.  We'll need this info below when we clear
2722              * the remainder of the last page out (and potentially
2723              * clear later pages out, if we fetch past EOF).
2724              */
2725             while (length_found > 0) {
2726                 /* assert that there are still more buffers;
2727                  * our check above for length_found being less than
2728                  * data_length should ensure this.
2729                  */
2730                 osi_assertx(bufferp != NULL, "null cm_buf_t");
2731
2732                 /* read rxbytes of data */
2733                 rxbytes = (afs_uint32)(length_found > biod->length ? biod->length : length_found);
2734                 temp = rx_Read(rxcallp, bufferp, rxbytes);
2735                 if (temp < rxbytes) {
2736                     /*
2737                      * If the file server returned (filesize - offset),
2738                      * then the first rx_Read will return zero octets of data.
2739                      * If it does, do not treat it as an error.  Correct the
2740                      * length_found and continue as if the file server said
2741                      * it was sending us zero octets of data.
2742                      */
2743                     if (fs_fetchdata_offset_bug && first_read) {
2744                         length_found = 0;
2745                         break;
2746                     } else if (temp <= 0) {
2747                         code = (rx_Error(rxcallp) < 0) ? rx_Error(rxcallp) : RX_PROTOCOL_ERROR;
2748                         break;
2749                     }
2750                 }
2751                 first_read = 0;
2752
2753                 /* and adjust counters */
2754                 length_found -= temp;
2755             }
2756         }
2757
2758         if (code == 0) {
2759             if (call_was_64bit)
2760                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
2761             else
2762                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
2763         } else {
2764             if (call_was_64bit)
2765                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
2766             else
2767                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
2768         }
2769
2770         if (rxcallp)
2771             code1 = rx_EndCall(rxcallp, code);
2772
2773         if (code1 == RXKADUNKNOWNKEY)
2774             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
2775
2776         /* If we are avoiding a file server bug, ignore the error state */
2777         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
2778             /* Clone the current status info and clear the error state */
2779             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
2780             if (scp_locked) {
2781                 lock_ReleaseWrite(&scp->rw);
2782                 scp_locked = 0;
2783             }
2784             code = 0;
2785         /* Prefer the error value from FetchData over rx_EndCall */
2786         } else if (code == 0 && code1 != 0)
2787             code = code1;
2788         osi_Log0(afsd_logp, "CALL FetchData DONE");
2789
2790     } while (cm_Analyze(connp, userp, reqp, &scp->fid, NULL, 0, &afsStatus, &volSync, NULL, NULL, code));
2791
2792   fetchingcompleted:
2793     code = cm_MapRPCError(code, reqp);
2794
2795     if (!scp_locked)
2796         lock_ObtainWrite(&scp->rw);
2797
2798     if (code == 0)
2799         code = cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, CM_MERGEFLAG_FETCHDATA);
2800     else
2801         InterlockedDecrement(&scp->activeRPCs);
2802
2803     if (code == 0)
2804     {
2805         if (dataVersion == scp->dataVersion)
2806         {
2807             osi_queueData_t *qdp = NULL;
2808             cm_buf_t *bufp;
2809             afs_uint32 buf_offset;
2810             afs_uint32 bytes_compared = 0;
2811             afs_uint32 cmp_length;
2812             int md5_match = 1;
2813
2814             verified = 1;
2815
2816             while ( bytes_compared < biod->length )
2817             {
2818                 if (qdp == NULL) {
2819                     qdp = biod->bufListEndp;
2820                     buf_offset = biod->offset.LowPart % cm_data.buf_blockSize;
2821                 } else {
2822                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2823                     buf_offset = 0;
2824                 }
2825                 cmp_length =  cm_data.buf_blockSize - buf_offset;
2826                 if (cmp_length > biod->length - bytes_compared)
2827                     cmp_length = biod->length - bytes_compared;
2828
2829                 osi_assertx(qdp != NULL, "null osi_queueData_t");
2830                 bufp = osi_GetQData(qdp);
2831
2832                 if (memcmp(bufferp+bytes_compared, bufp->datap+buf_offset, cmp_length) != 0)
2833                 {
2834                     verified = 0;
2835                     md5_match = buf_ValidateCheckSum(bufp);
2836
2837                     osi_Log5(afsd_logp, "cm_VerifyDataStore verification failed scp 0x%p bufp 0x%p offset 0x%x:%08x md5 %s",
2838                              scp, bufp, bufp->offset.HighPart, bufp->offset.LowPart, md5_match ? "match" : "no-match");
2839                 }
2840                 bytes_compared += cmp_length;
2841             }
2842         } else {
2843             osi_Log4(afsd_logp, "cm_VerifyStoreData unable to verify due to data version change scp 0x%p, off 0x%x:%08x, size 0x%x",
2844                      scp, biod->offset.HighPart, biod->offset.LowPart, biod->length);
2845         }
2846     }
2847
2848     if (bufferp)
2849         free(bufferp);
2850
2851     return verified;
2852 }