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