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