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