244f70510c6c7ca0f75012699d9f98ceb3129071
[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
26 #ifdef DEBUG
27 extern void afsi_log(char *pattern, ...);
28 #endif
29
30 #ifdef AFS_FREELANCE_CLIENT
31 extern osi_mutex_t cm_Freelance_Lock;
32 #endif
33
34 #define USE_RX_IOVEC 1
35
36 /* we can access connp->serverp without holding a lock because that
37    never changes since the connection is made. */
38 #define SERVERHAS64BIT(connp) (!((connp)->serverp->flags & CM_SERVERFLAG_NO64BIT))
39 #define SET_SERVERHASNO64BIT(connp) (cm_SetServerNo64Bit((connp)->serverp, TRUE))
40
41 /* functions called back from the buffer package when reading or writing data,
42  * or when holding or releasing a vnode pointer.
43  */
44 long cm_BufWrite(void *vscp, osi_hyper_t *offsetp, long length, long flags,
45                  cm_user_t *userp, cm_req_t *reqp)
46 {
47     /* store the data back from this buffer; the buffer is locked and held,
48      * but the vnode involved isn't locked, yet.  It is held by its
49      * reference from the buffer, which won't change until the buffer is
50      * released by our caller.  Thus, we don't have to worry about holding
51      * bufp->scp.
52      */
53     long code, code1;
54     cm_scache_t *scp = vscp;
55     afs_int32 nbytes;
56     afs_int32 save_nbytes;
57     long temp;
58     AFSFetchStatus outStatus;
59     AFSStoreStatus inStatus;
60     osi_hyper_t thyper;
61     AFSVolSync volSync;
62     AFSFid tfid;
63     struct rx_call *rxcallp;
64     struct rx_connection *rxconnp;
65     osi_queueData_t *qdp;
66     cm_buf_t *bufp;
67     afs_uint32 wbytes;
68     char *bufferp;
69     cm_conn_t *connp;
70     osi_hyper_t truncPos;
71     cm_bulkIO_t biod;           /* bulk IO descriptor */
72     int require_64bit_ops = 0;
73     int call_was_64bit = 0;
74     int scp_locked = flags & CM_BUF_WRITE_SCP_LOCKED;
75
76     osi_assertx(userp != NULL, "null cm_user_t");
77     osi_assertx(scp != NULL, "null cm_scache_t");
78
79     memset(&volSync, 0, sizeof(volSync));
80
81     /* now, the buffer may or may not be filled with good data (buf_GetNewLocked
82      * drops lots of locks, and may indeed return a properly initialized
83      * buffer, although more likely it will just return a new, empty, buffer.
84      */
85     if (!scp_locked)
86         lock_ObtainWrite(&scp->rw);
87     if (scp->flags & CM_SCACHEFLAG_DELETED) {
88         if (!scp_locked)
89             lock_ReleaseWrite(&scp->rw);
90         return CM_ERROR_NOSUCHFILE;
91     }
92
93     cm_AFSFidFromFid(&tfid, &scp->fid);
94
95     /* Serialize StoreData RPC's; for rationale see cm_scache.c */
96     (void) cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA_EXCL);
97
98     code = cm_SetupStoreBIOD(scp, offsetp, length, &biod, userp, reqp);
99     if (code) {
100         osi_Log1(afsd_logp, "cm_SetupStoreBIOD code %x", code);
101         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
102         if (!scp_locked)
103             lock_ReleaseWrite(&scp->rw);
104         return code;
105     }
106
107     if (biod.length == 0) {
108         osi_Log0(afsd_logp, "cm_SetupStoreBIOD length 0");
109         cm_ReleaseBIOD(&biod, 1, 0, 1); /* should be a NOOP */
110         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
111         if (!scp_locked)
112             lock_ReleaseWrite(&scp->rw);
113         return 0;
114     }
115
116     /* prepare the output status for the store */
117     scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
118     cm_StatusFromAttr(&inStatus, scp, NULL);
119     truncPos = scp->length;
120     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
121         && LargeIntegerLessThan(scp->truncPos, truncPos))
122         truncPos = scp->truncPos;
123         scp->mask &= ~CM_SCACHEMASK_TRUNCPOS;
124                 
125     /* compute how many bytes to write from this buffer */
126     thyper = LargeIntegerSubtract(scp->length, biod.offset);
127     if (LargeIntegerLessThanZero(thyper)) {
128         /* entire buffer is past EOF */
129         nbytes = 0;
130     }
131     else {
132         /* otherwise write out part of buffer before EOF, but not
133          * more than bufferSize bytes.
134          */
135         if (LargeIntegerGreaterThan(thyper,
136                                     ConvertLongToLargeInteger(biod.length))) {
137             nbytes = biod.length;
138         } else {
139             /* if thyper is less than or equal to biod.length, then we
140                can safely assume that the value fits in a long. */
141             nbytes = thyper.LowPart;
142         }
143     }
144
145     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
146                                                  ConvertLongToLargeInteger(nbytes)),
147                                  ConvertLongToLargeInteger(LONG_MAX)) ||
148          LargeIntegerGreaterThan(truncPos,
149                                  ConvertLongToLargeInteger(LONG_MAX))) {
150         require_64bit_ops = 1;
151     }
152         
153     lock_ReleaseWrite(&scp->rw);
154
155     /* now we're ready to do the store operation */
156     save_nbytes = nbytes;
157     do {
158         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
159         if (code) 
160             continue;
161
162     retry:
163         rxconnp = cm_GetRxConn(connp);
164         rxcallp = rx_NewCall(rxconnp);
165         rx_PutConnection(rxconnp);
166
167         if (SERVERHAS64BIT(connp)) {
168             call_was_64bit = 1;
169
170             osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData64 scp 0x%p, offset 0x%x:%08x, length 0x%x",
171                      scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
172
173             code = StartRXAFS_StoreData64(rxcallp, &tfid, &inStatus,
174                                           biod.offset.QuadPart,
175                                           nbytes,
176                                           truncPos.QuadPart);
177             if (code)
178                 osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData64 FAILURE, code 0x%x", code);
179             else
180                 osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData64 SUCCESS");
181         } else {
182             call_was_64bit = 0;
183
184             if (require_64bit_ops) {
185                 osi_Log0(afsd_logp, "Skipping StartRXAFS_StoreData.  The operation requires large file support in the server.");
186                 code = CM_ERROR_TOOBIG;
187             } else {
188                 osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData scp 0x%p, offset 0x%x:%08x, length 0x%x",
189                          scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
190
191                 code = StartRXAFS_StoreData(rxcallp, &tfid, &inStatus,
192                                             biod.offset.LowPart, nbytes, truncPos.LowPart);
193                 if (code)
194                     osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData FAILURE, code 0x%x", code);
195                 else
196                     osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData SUCCESS");
197             }
198         }
199
200         if (code == 0) {
201             afs_uint32 buf_offset = 0, bytes_copied = 0;
202
203             /* write the data from the the list of buffers */
204             qdp = NULL;
205             while(nbytes > 0) {
206 #ifdef USE_RX_IOVEC
207                 struct iovec tiov[RX_MAXIOVECS];
208                 afs_int32 tnio, vlen, vbytes, iov, voffset;
209                 afs_uint32 vleft;
210
211                 vbytes = rx_WritevAlloc(rxcallp, tiov, &tnio, RX_MAXIOVECS, nbytes);
212                 if (vbytes <= 0) {
213                     code = RX_PROTOCOL_ERROR;
214                     break;
215                 }
216
217                 for ( iov = voffset = vlen = 0;
218                       vlen < vbytes && iov < tnio; vlen += wbytes) {
219                     if (qdp == NULL) {
220                         qdp = biod.bufListEndp;
221                         buf_offset = offsetp->LowPart % cm_data.buf_blockSize;
222                     } else if (buf_offset == cm_data.buf_blockSize) {
223                         qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
224                         buf_offset = 0;
225                     }
226
227                     osi_assertx(qdp != NULL, "null osi_queueData_t");
228                     bufp = osi_GetQData(qdp);
229                     bufferp = bufp->datap + buf_offset;
230                     wbytes = vbytes - vlen;
231                     if (wbytes > cm_data.buf_blockSize - buf_offset)
232                         wbytes = cm_data.buf_blockSize - buf_offset;
233
234                     vleft = tiov[iov].iov_len - voffset;
235                     while (wbytes > vleft && iov < tnio) {
236                         memcpy(tiov[iov].iov_base + voffset, bufferp, vleft);
237                         bytes_copied += vleft;
238                         vlen += vleft;
239                         wbytes -= vleft;
240                         bufferp += vleft;
241                         buf_offset += vleft;
242
243                         iov++;
244                         voffset = 0;
245                         vleft = tiov[iov].iov_len;
246                     }
247
248                     if (iov < tnio) {
249                         memcpy(tiov[iov].iov_base + voffset, bufferp, wbytes);
250                         bytes_copied += wbytes;
251                         if (tiov[iov].iov_len == voffset + wbytes) {
252                             iov++;
253                             voffset = 0;
254                             vleft = (iov < tnio) ? tiov[iov].iov_len : 0;
255                         } else {
256                             voffset += wbytes;
257                             vleft -= wbytes;
258                         }
259                         bufferp += wbytes;
260                         buf_offset += wbytes;
261                     } else {
262                         voffset = vleft = 0;
263                     }
264                 }
265
266                 osi_assertx(iov == tnio, "incorrect iov count");
267                 osi_assertx(vlen == vbytes, "bytes_copied != vbytes");
268                 osi_assertx(bufp->offset.QuadPart + buf_offset == biod.offset.QuadPart + bytes_copied,
269                             "begin and end offsets don't match");
270
271                 temp = rx_Writev(rxcallp, tiov, tnio, vbytes);
272                 if (temp != vbytes) {
273                     osi_Log3(afsd_logp, "rx_Writev failed bp 0x%p, %d != %d", bufp, temp, vbytes);
274                     code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
275                     break;
276                 }
277
278                 osi_Log3(afsd_logp, "rx_Writev succeeded bp 0x%p offset 0x%x, wrote %u",
279                          bufp, buf_offset, vbytes);
280                 nbytes -= vbytes;
281 #else /* USE_RX_IOVEC */
282                 if (qdp == NULL) {
283                     qdp = biod.bufListEndp;
284                     buf_offset = offsetp->LowPart % cm_data.buf_blockSize;
285                 } else {
286                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
287                     buf_offset = 0;
288                 }
289
290                 osi_assertx(qdp != NULL, "null osi_queueData_t");
291                 bufp = osi_GetQData(qdp);
292                 bufferp = bufp->datap + buf_offset;
293                 wbytes = nbytes;
294                 if (wbytes > cm_data.buf_blockSize - buf_offset)
295                     wbytes = cm_data.buf_blockSize - buf_offset;
296
297                 /* write out wbytes of data from bufferp */
298                 temp = rx_Write(rxcallp, bufferp, wbytes);
299                 if (temp != wbytes) {
300                     osi_Log3(afsd_logp, "rx_Write failed bp 0x%p, %d != %d",bufp,temp,wbytes);
301                     code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
302                     break;
303                 } else {
304                     osi_Log2(afsd_logp, "rx_Write succeeded bp 0x%p, %d",bufp,temp);
305                 }       
306                 nbytes -= wbytes;
307 #endif /* USE_RX_IOVEC */
308             }   /* while more bytes to write */
309         }       /* if RPC started successfully */
310
311         if (code == 0) {
312             if (call_was_64bit) {
313                 code = EndRXAFS_StoreData64(rxcallp, &outStatus, &volSync);
314                 if (code)
315                     osi_Log2(afsd_logp, "EndRXAFS_StoreData64 FAILURE scp 0x%p code %lX", scp, code);
316                 else
317                     osi_Log0(afsd_logp, "EndRXAFS_StoreData64 SUCCESS");
318             } else {
319                 code = EndRXAFS_StoreData(rxcallp, &outStatus, &volSync);
320                 if (code)
321                     osi_Log2(afsd_logp, "EndRXAFS_StoreData FAILURE scp 0x%p code %lX",scp,code);
322                 else
323                     osi_Log0(afsd_logp, "EndRXAFS_StoreData SUCCESS");
324             }
325         }
326
327         code1 = rx_EndCall(rxcallp, code);
328
329         if ((code == RXGEN_OPCODE || code1 == RXGEN_OPCODE) && SERVERHAS64BIT(connp)) {
330             SET_SERVERHASNO64BIT(connp);
331             qdp = NULL;
332             nbytes = save_nbytes;
333             goto retry;
334         }
335
336         /* Prefer StoreData error over rx_EndCall error */
337         if (code1 != 0)
338             code = code1;
339     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
340
341     code = cm_MapRPCError(code, reqp);
342
343     if (code)
344         osi_Log2(afsd_logp, "CALL StoreData FAILURE scp 0x%p, code 0x%x", scp, code);
345     else
346         osi_Log1(afsd_logp, "CALL StoreData SUCCESS scp 0x%p", scp);
347
348     /* now, clean up our state */
349     lock_ObtainWrite(&scp->rw);
350
351     cm_ReleaseBIOD(&biod, 1, code, 1);
352     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
353
354     if (code == 0) {
355         osi_hyper_t t;
356         /* now, here's something a little tricky: in AFS 3, a dirty
357          * length can't be directly stored, instead, a dirty chunk is
358          * stored that sets the file's size (by writing and by using
359          * the truncate-first option in the store call).
360          *
361          * At this point, we've just finished a store, and so the trunc
362          * pos field is clean.  If the file's size at the server is at
363          * least as big as we think it should be, then we turn off the
364          * length dirty bit, since all the other dirty buffers must
365          * precede this one in the file.
366          *
367          * The file's desired size shouldn't be smaller than what's
368          * stored at the server now, since we just did the trunc pos
369          * store.
370          *
371          * We have to turn off the length dirty bit as soon as we can,
372          * so that we see updates made by other machines.
373          */
374
375         if (call_was_64bit) {
376             t.LowPart = outStatus.Length;
377             t.HighPart = outStatus.Length_hi;
378         } else {
379             t = ConvertLongToLargeInteger(outStatus.Length);
380         }
381
382         if (LargeIntegerGreaterThanOrEqualTo(t, scp->length))
383             scp->mask &= ~CM_SCACHEMASK_LENGTH;
384
385         cm_MergeStatus(NULL, scp, &outStatus, &volSync, userp, reqp, CM_MERGEFLAG_STOREDATA);
386     } else {
387         if (code == CM_ERROR_SPACE)
388             scp->flags |= CM_SCACHEFLAG_OUTOFSPACE;
389         else if (code == CM_ERROR_QUOTA)
390             scp->flags |= CM_SCACHEFLAG_OVERQUOTA;
391     }
392     if (!scp_locked)
393         lock_ReleaseWrite(&scp->rw);
394
395     return code;
396 }
397
398 /*
399  * Truncate the file, by sending a StoreData RPC with zero length.
400  *
401  * Called with scp locked.  Releases and re-obtains the lock.
402  */
403 long cm_StoreMini(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
404 {
405     AFSFetchStatus outStatus;
406     AFSStoreStatus inStatus;
407     AFSVolSync volSync;
408     AFSFid tfid;
409     long code, code1;
410     osi_hyper_t truncPos;
411     cm_conn_t *connp;
412     struct rx_call *rxcallp;
413     struct rx_connection *rxconnp;
414     int require_64bit_ops = 0;
415     int call_was_64bit = 0;
416
417     memset(&volSync, 0, sizeof(volSync));
418
419     /* Serialize StoreData RPC's; for rationale see cm_scache.c */
420     (void) cm_SyncOp(scp, NULL, userp, reqp, 0,
421                      CM_SCACHESYNC_STOREDATA_EXCL);
422
423     /* prepare the output status for the store */
424     inStatus.Mask = AFS_SETMODTIME;
425     inStatus.ClientModTime = scp->clientModTime;
426     scp->mask &= ~CM_SCACHEMASK_CLIENTMODTIME;
427
428     /* calculate truncation position */
429     truncPos = scp->length;
430     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
431         && LargeIntegerLessThan(scp->truncPos, truncPos))
432         truncPos = scp->truncPos;
433     scp->mask &= ~CM_SCACHEMASK_TRUNCPOS;
434
435     if (LargeIntegerGreaterThan(truncPos,
436                                 ConvertLongToLargeInteger(LONG_MAX))) {
437
438         require_64bit_ops = 1;
439     }
440
441     lock_ReleaseWrite(&scp->rw);
442
443     cm_AFSFidFromFid(&tfid, &scp->fid);
444
445     /* now we're ready to do the store operation */
446     do {
447         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
448         if (code) 
449             continue;
450
451     retry:      
452         rxconnp = cm_GetRxConn(connp);
453         rxcallp = rx_NewCall(rxconnp);
454         rx_PutConnection(rxconnp);
455
456         if (SERVERHAS64BIT(connp)) {
457             call_was_64bit = 1;
458
459             code = StartRXAFS_StoreData64(rxcallp, &tfid, &inStatus,
460                                           0, 0, truncPos.QuadPart);
461         } else {
462             call_was_64bit = 0;
463
464             if (require_64bit_ops) {
465                 code = CM_ERROR_TOOBIG;
466             } else {
467                 code = StartRXAFS_StoreData(rxcallp, &tfid, &inStatus,
468                                             0, 0, truncPos.LowPart);
469             }
470         }
471
472         if (code == 0) {
473             if (call_was_64bit)
474                 code = EndRXAFS_StoreData64(rxcallp, &outStatus, &volSync);
475             else
476                 code = EndRXAFS_StoreData(rxcallp, &outStatus, &volSync);
477         }
478         code1 = rx_EndCall(rxcallp, code);
479
480         if ((code == RXGEN_OPCODE || code1 == RXGEN_OPCODE) && SERVERHAS64BIT(connp)) {
481             SET_SERVERHASNO64BIT(connp);
482             goto retry;
483         }
484
485         /* prefer StoreData error over rx_EndCall error */
486         if (code == 0 && code1 != 0)
487             code = code1;
488     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
489     code = cm_MapRPCError(code, reqp);
490         
491     /* now, clean up our state */
492     lock_ObtainWrite(&scp->rw);
493
494     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
495
496     if (code == 0) {
497         osi_hyper_t t;
498         /*
499          * For explanation of handling of CM_SCACHEMASK_LENGTH,
500          * see cm_BufWrite().
501          */
502         if (call_was_64bit) {
503             t.HighPart = outStatus.Length_hi;
504             t.LowPart = outStatus.Length;
505         } else {
506             t = ConvertLongToLargeInteger(outStatus.Length);
507         }
508
509         if (LargeIntegerGreaterThanOrEqualTo(t, scp->length))
510             scp->mask &= ~CM_SCACHEMASK_LENGTH;
511         cm_MergeStatus(NULL, scp, &outStatus, &volSync, userp, reqp, CM_MERGEFLAG_STOREDATA);
512     }
513
514     return code;
515 }
516
517 long cm_BufRead(cm_buf_t *bufp, long nbytes, long *bytesReadp, cm_user_t *userp)
518 {
519     *bytesReadp = 0;
520
521     /* now return a code that means that I/O is done */
522     return 0;
523 }
524
525 /*
526  * stabilize scache entry with CM_SCACHESYNC_SETSIZE.  This prevents any new
527  * data buffers to be allocated, new data to be fetched from the file server,
528  * and writes to be accepted from the application but permits dirty buffers
529  * to be written to the file server.
530  *
531  * Stabilize uses cm_SyncOp to maintain the cm_scache_t in this stable state
532  * instead of holding the rwlock exclusively.  This permits background stores
533  * to be performed in parallel and in particular allow FlushFile to be
534  * implemented without violating the locking hierarchy.
535  */
536 long cm_BufStabilize(void *vscp, cm_user_t *userp, cm_req_t *reqp)
537 {
538     cm_scache_t *scp = vscp;
539     long code;
540
541     lock_ObtainWrite(&scp->rw);
542     code = cm_SyncOp(scp, NULL, userp, reqp, 0, 
543                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
544     lock_ReleaseWrite(&scp->rw);
545
546     return code;
547 }
548
549 /* undoes the work that cm_BufStabilize does: releases lock so things can change again */
550 long cm_BufUnstabilize(void *vscp, cm_user_t *userp)
551 {
552     cm_scache_t *scp = vscp;
553         
554     lock_ObtainWrite(&scp->rw);
555     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
556
557     lock_ReleaseWrite(&scp->rw);
558         
559     /* always succeeds */
560     return 0;
561 }
562
563 cm_buf_ops_t cm_bufOps = {
564     cm_BufWrite,
565     cm_BufRead,
566     cm_BufStabilize,
567     cm_BufUnstabilize
568 };
569
570 long cm_ValidateDCache(void)
571 {
572     return buf_ValidateBuffers();
573 }
574
575 long cm_ShutdownDCache(void)
576 {
577     return 0;
578 }
579
580 int cm_InitDCache(int newFile, long chunkSize, afs_uint64 nbuffers)
581 {
582     return buf_Init(newFile, &cm_bufOps, nbuffers);
583 }
584
585 /* check to see if we have an up-to-date buffer.  The buffer must have
586  * previously been obtained by calling buf_Get.
587  *
588  * Make sure we have a callback, and that the dataversion matches.
589  *
590  * Scp must be locked.
591  *
592  * Bufp *may* be locked.
593  */
594 int cm_HaveBuffer(cm_scache_t *scp, cm_buf_t *bufp, int isBufLocked)
595 {
596     int code;
597     if (!cm_HaveCallback(scp))
598         return 0;
599     if ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED))
600         return 1;
601     if (bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow)
602         return 1;
603     if (bufp->offset.QuadPart >= scp->serverLength.QuadPart)
604         return 1;
605     if (!isBufLocked) {
606         code = lock_TryMutex(&bufp->mx);
607         if (code == 0) {
608             /* don't have the lock, and can't lock it, then
609              * return failure.
610              */
611             return 0;
612         }
613     }
614
615     /* remember dirty flag for later */
616     code = bufp->flags & CM_BUF_DIRTY;
617
618     /* release lock if we obtained it here */
619     if (!isBufLocked) 
620         lock_ReleaseMutex(&bufp->mx);
621
622     /* if buffer was dirty, buffer is acceptable for use */
623     if (code) 
624         return 1;
625     else 
626         return 0;
627 }
628
629 /*
630  * used when deciding whether to do a background fetch or not.
631  * call with scp->rw write-locked.
632  */
633 afs_int32
634 cm_CheckFetchRange(cm_scache_t *scp, osi_hyper_t *startBasep, osi_hyper_t *length,
635                         cm_user_t *userp, cm_req_t *reqp, osi_hyper_t *realBasep)
636 {
637     osi_hyper_t tbase;
638     osi_hyper_t tlength;
639     osi_hyper_t tblocksize;
640     long code;
641     cm_buf_t *bp;
642     int stop;
643         
644     /* now scan all buffers in the range, looking for any that look like
645      * they need work.
646      */
647     tbase = *startBasep;
648     tlength = *length;
649     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
650     stop = 0;
651     while (LargeIntegerGreaterThanZero(tlength)) {
652         /* get callback so we can do a meaningful dataVersion comparison */
653         code = cm_SyncOp(scp, NULL, userp, reqp, 0,
654                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
655         if (code)
656             return code;
657                 
658         if (LargeIntegerGreaterThanOrEqualTo(tbase, scp->length)) {
659             /* we're past the end of file */
660             break;
661         }
662
663         bp = buf_Find(scp, &tbase);
664         /* We cheat slightly by not locking the bp mutex. */
665         if (bp) {
666             if ((bp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING | CM_BUF_CMBKGFETCH)) == 0
667                  && (bp->dataVersion < scp->bufDataVersionLow || bp->dataVersion > scp->dataVersion))
668                 stop = 1;
669             buf_Release(bp);
670             bp = NULL;
671         }
672         else 
673             stop = 1;
674
675         /* if this buffer is essentially guaranteed to require a fetch,
676          * break out here and return this position.
677          */
678         if (stop) 
679             break;
680                 
681         tbase = LargeIntegerAdd(tbase, tblocksize);
682         tlength = LargeIntegerSubtract(tlength,  tblocksize);
683     }
684         
685     /* if we get here, either everything is fine or 'stop' stopped us at a
686      * particular buffer in the range that definitely needs to be fetched.
687      */
688     if (stop == 0) {
689         /* return non-zero code since realBasep won't be valid */
690         code = -1;
691     }   
692     else {
693         /* successfully found a page that will need fetching */
694         *realBasep = tbase;
695         code = 0;
696     }
697     return code;
698 }
699
700 afs_int32
701 cm_BkgStore(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
702             cm_user_t *userp)
703 {
704     osi_hyper_t toffset;
705     long length;
706     cm_req_t req;
707     long code = 0;
708
709     if (scp->flags & CM_SCACHEFLAG_DELETED) {
710         osi_Log4(afsd_logp, "Skipping BKG store - Deleted scp 0x%p, offset 0x%x:%08x, length 0x%x", scp, p2, p1, p3);
711     } else {
712         cm_InitReq(&req);
713
714         /* Retries will be performed by the BkgDaemon thread if appropriate */
715         req.flags |= CM_REQ_NORETRY;
716
717         toffset.LowPart = p1;
718         toffset.HighPart = p2;
719         length = p3;
720
721         osi_Log4(afsd_logp, "Starting BKG store scp 0x%p, offset 0x%x:%08x, length 0x%x", scp, p2, p1, p3);
722
723         code = cm_BufWrite(scp, &toffset, length, /* flags */ 0, userp, &req);
724
725         osi_Log4(afsd_logp, "Finished BKG store scp 0x%p, offset 0x%x:%08x, code 0x%x", scp, p2, p1, code);
726     }
727
728     /* 
729      * Keep the following list synchronized with the
730      * error code list in cm_BkgDaemon 
731      */
732     switch ( code ) {
733     case CM_ERROR_TIMEDOUT: /* or server restarting */
734     case CM_ERROR_RETRY:
735     case CM_ERROR_WOULDBLOCK:
736     case CM_ERROR_ALLBUSY:
737     case CM_ERROR_ALLDOWN:
738     case CM_ERROR_ALLOFFLINE:
739     case CM_ERROR_PARTIALWRITE:
740         break;  /* cm_BkgDaemon will re-insert the request in the queue */
741     case 0:
742     default:
743         lock_ObtainWrite(&scp->rw);
744         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_ASYNCSTORE);
745         lock_ReleaseWrite(&scp->rw);
746     }
747     return code;
748 }
749
750 /* Called with scp locked */
751 void cm_ClearPrefetchFlag(long code, cm_scache_t *scp, osi_hyper_t *base, osi_hyper_t *length)
752 {
753     osi_hyper_t end;
754
755     if (code == 0) {
756         end =  LargeIntegerAdd(*base, *length);
757         if (LargeIntegerGreaterThan(*base, scp->prefetch.base))
758             scp->prefetch.base = *base;
759         if (LargeIntegerGreaterThan(end, scp->prefetch.end))
760             scp->prefetch.end = end;
761     }
762     scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
763 }
764
765 /* do the prefetch.  if the prefetch fails, return 0 (success)
766  * because there is no harm done.  */
767 afs_int32
768 cm_BkgPrefetch(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
769                cm_user_t *userp)
770 {
771     osi_hyper_t length;
772     osi_hyper_t base;
773     osi_hyper_t offset;
774     osi_hyper_t end;
775     osi_hyper_t fetched;
776     osi_hyper_t tblocksize;
777     afs_int32 code;
778     int rxheld = 0;
779     cm_buf_t *bp = NULL;
780     cm_req_t req;
781
782     cm_InitReq(&req);
783
784     /* Retries will be performed by the BkgDaemon thread if appropriate */
785     req.flags |= CM_REQ_NORETRY;
786         
787     fetched.LowPart = 0;
788     fetched.HighPart = 0;
789     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
790     base.LowPart = p1;
791     base.HighPart = p2;
792     length.LowPart = p3;
793     length.HighPart = p4;
794
795     end = LargeIntegerAdd(base, length);
796         
797     osi_Log5(afsd_logp, "Starting BKG prefetch scp 0x%p offset 0x%x:%x length 0x%x:%x",
798              scp, p2, p1, p4, p3);
799
800     for ( code = 0, offset = base;
801           code == 0 && LargeIntegerLessThan(offset, end); 
802           offset = LargeIntegerAdd(offset, tblocksize) )
803     {
804         if (rxheld) {
805             lock_ReleaseWrite(&scp->rw);
806             rxheld = 0;
807         }
808
809         code = buf_Get(scp, &offset, &req, &bp);
810         if (code)
811             break;
812
813         if (bp->cmFlags & CM_BUF_CMFETCHING) {
814             /* skip this buffer as another thread is already fetching it */
815             if (!rxheld) {
816                 lock_ObtainWrite(&scp->rw);
817                 rxheld = 1;
818             }
819             bp->cmFlags &= ~CM_BUF_CMBKGFETCH;
820             buf_Release(bp);
821             bp = NULL;
822             continue;
823         }
824
825         if (!rxheld) {
826             lock_ObtainWrite(&scp->rw);
827             rxheld = 1;
828         }
829
830         code = cm_GetBuffer(scp, bp, NULL, userp, &req);
831         if (code == 0)
832             fetched = LargeIntegerAdd(fetched, tblocksize); 
833         buf_Release(bp);
834         bp->cmFlags &= ~CM_BUF_CMBKGFETCH;
835     }
836     
837     if (!rxheld) {
838         lock_ObtainWrite(&scp->rw);
839         rxheld = 1;
840     }
841
842     /* Clear flag from any remaining buffers */
843     for ( ;
844           LargeIntegerLessThan(offset, end);
845           offset = LargeIntegerAdd(offset, tblocksize) )
846     {
847         bp = buf_Find(scp, &offset);
848         if (bp) {
849             bp->cmFlags &= ~CM_BUF_CMBKGFETCH;
850             buf_Release(bp);
851         }
852     }
853     cm_ClearPrefetchFlag(LargeIntegerGreaterThanZero(fetched) ? 0 : code, 
854                          scp, &base, &fetched);
855
856     /* wakeup anyone who is waiting */
857     if (scp->flags & CM_SCACHEFLAG_WAITING) {
858         osi_Log1(afsd_logp, "CM BkgPrefetch Waking scp 0x%p", scp);
859         osi_Wakeup((LONG_PTR) &scp->flags);
860     }
861     lock_ReleaseWrite(&scp->rw);
862
863     osi_Log4(afsd_logp, "Ending BKG prefetch scp 0x%p code 0x%x fetched 0x%x:%x",
864              scp, code, fetched.HighPart, fetched.LowPart);
865     return code;
866 }
867
868 /* a read was issued to offsetp, and we have to determine whether we should
869  * do a prefetch of the next chunk.
870  */
871 void cm_ConsiderPrefetch(cm_scache_t *scp, osi_hyper_t *offsetp, afs_uint32 count,
872                          cm_user_t *userp, cm_req_t *reqp)
873 {
874     long code;
875     int  rwheld = 0;
876     osi_hyper_t realBase;
877     osi_hyper_t readBase;
878     osi_hyper_t readLength;
879     osi_hyper_t readEnd;
880     osi_hyper_t offset;
881     osi_hyper_t tblocksize;             /* a long long temp variable */
882     cm_buf_t    *bp;
883
884     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
885         
886     readBase = *offsetp;
887     /* round up to chunk boundary */
888     readBase.LowPart += (cm_chunkSize-1);
889     readBase.LowPart &= (-cm_chunkSize);
890
891     readLength = ConvertLongToLargeInteger(count);
892
893     lock_ObtainWrite(&scp->rw);
894     rwheld = 1;
895     if ((scp->flags & CM_SCACHEFLAG_PREFETCHING)
896          || LargeIntegerLessThanOrEqualTo(readBase, scp->prefetch.base)) {
897         lock_ReleaseWrite(&scp->rw);
898         return;
899     }
900     scp->flags |= CM_SCACHEFLAG_PREFETCHING;
901
902     /* start the scan at the latter of the end of this read or
903      * the end of the last fetched region.
904      */
905     if (LargeIntegerGreaterThan(scp->prefetch.end, readBase))
906         readBase = scp->prefetch.end;
907
908     code = cm_CheckFetchRange(scp, &readBase, &readLength, userp, reqp,
909                               &realBase);
910     if (code) {
911         scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
912         lock_ReleaseWrite(&scp->rw);
913         return; /* can't find something to prefetch */
914     }
915
916     readEnd = LargeIntegerAdd(realBase, readLength);
917
918     /*
919      * Mark each buffer in the range as queued for a
920      * background fetch
921      */
922     for ( offset = realBase;
923           LargeIntegerLessThan(offset, readEnd);
924           offset = LargeIntegerAdd(offset, tblocksize) )
925     {
926         if (rwheld) {
927             lock_ReleaseWrite(&scp->rw);
928             rwheld = 0;
929         }
930
931         bp = buf_Find(scp, &offset);
932         if (!bp)
933             continue;
934
935         if (!rwheld) {
936             lock_ObtainWrite(&scp->rw);
937             rwheld = 1;
938         }
939
940         bp->cmFlags |= CM_BUF_CMBKGFETCH;
941         buf_Release(bp);
942     }
943
944     if (rwheld)
945         lock_ReleaseWrite(&scp->rw);
946
947     osi_Log2(afsd_logp, "BKG Prefetch request scp 0x%p, base 0x%x",
948              scp, realBase.LowPart);
949
950     cm_QueueBKGRequest(scp, cm_BkgPrefetch, 
951                        realBase.LowPart, realBase.HighPart, 
952                        readLength.LowPart, readLength.HighPart, 
953                        userp);
954 }
955
956 /* scp must be locked; temporarily unlocked during processing.
957  * If returns 0, returns buffers held in biop, and with
958  * CM_BUF_CMSTORING set.
959  *
960  * Caller *must* set CM_BUF_WRITING and reset the over.hEvent field if the
961  * buffer is ever unlocked before CM_BUF_DIRTY is cleared.  And if
962  * CM_BUF_WRITING is ever viewed by anyone, then it must be cleared, sleepers
963  * must be woken, and the event must be set when the I/O is done.  All of this
964  * is required so that buf_WaitIO synchronizes properly with the buffer as it
965  * is being written out.
966  */
967 long cm_SetupStoreBIOD(cm_scache_t *scp, osi_hyper_t *inOffsetp, long inSize,
968                        cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
969 {
970     cm_buf_t *bufp;
971     osi_queueData_t *qdp;
972     osi_hyper_t thyper;
973     osi_hyper_t tbase;
974     osi_hyper_t scanStart;              /* where to start scan for dirty pages */
975     osi_hyper_t scanEnd;                /* where to stop scan for dirty pages */
976     osi_hyper_t firstModOffset; /* offset of first modified page in range */
977     long temp;
978     long code;
979     long flags;                 /* flags to cm_SyncOp */
980         
981     /* clear things out */
982     biop->scp = scp;                    /* do not hold; held by caller */
983     biop->offset = *inOffsetp;
984     biop->length = 0;
985     biop->bufListp = NULL;
986     biop->bufListEndp = NULL;
987     biop->reserved = 0;
988
989     /* reserve a chunk's worth of buffers */
990     lock_ReleaseWrite(&scp->rw);
991     buf_ReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
992     lock_ObtainWrite(&scp->rw);
993
994     bufp = NULL;
995     for (temp = 0; temp < inSize; temp += cm_data.buf_blockSize) {
996         thyper = ConvertLongToLargeInteger(temp);
997         tbase = LargeIntegerAdd(*inOffsetp, thyper);
998
999         bufp = buf_Find(scp, &tbase);
1000         if (bufp) {
1001             /* get buffer mutex and scp mutex safely */
1002             lock_ReleaseWrite(&scp->rw);
1003             lock_ObtainMutex(&bufp->mx);
1004
1005             /*
1006              * if the buffer is actively involved in I/O
1007              * we wait for the I/O to complete.
1008              */
1009             if (bufp->flags & (CM_BUF_WRITING|CM_BUF_READING))
1010                 buf_WaitIO(scp, bufp);
1011
1012             lock_ObtainWrite(&scp->rw);
1013             flags = CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_STOREDATA | CM_SCACHESYNC_BUFLOCKED;
1014             code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags); 
1015             if (code) {
1016                 lock_ReleaseMutex(&bufp->mx);
1017                 buf_Release(bufp);
1018                 bufp = NULL;
1019                 buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1020                 return code;
1021             }   
1022                         
1023             /* if the buffer is dirty, we're done */
1024             if (bufp->flags & CM_BUF_DIRTY) {
1025                 osi_assertx(!(bufp->flags & CM_BUF_WRITING),
1026                             "WRITING w/o CMSTORING in SetupStoreBIOD");
1027                 bufp->flags |= CM_BUF_WRITING;
1028                 break;
1029             }
1030
1031             /* this buffer is clean, so there's no reason to process it */
1032             cm_SyncOpDone(scp, bufp, flags);
1033             lock_ReleaseMutex(&bufp->mx);
1034             buf_Release(bufp);
1035             bufp = NULL;
1036         }       
1037     }
1038
1039     biop->reserved = 1;
1040         
1041     /* if we get here, if bufp is null, we didn't find any dirty buffers
1042      * that weren't already being stored back, so we just quit now.
1043      */
1044     if (!bufp) {
1045         return 0;
1046     }
1047
1048     /* don't need buffer mutex any more */
1049     lock_ReleaseMutex(&bufp->mx);
1050         
1051     /* put this element in the list */
1052     qdp = osi_QDAlloc();
1053     osi_SetQData(qdp, bufp);
1054     /* don't have to hold bufp, since held by buf_Find above */
1055     osi_QAddH((osi_queue_t **) &biop->bufListp,
1056               (osi_queue_t **) &biop->bufListEndp,
1057               &qdp->q);
1058     biop->length = cm_data.buf_blockSize;
1059     firstModOffset = bufp->offset;
1060     biop->offset = firstModOffset;
1061     bufp = NULL;        /* this buffer and reference added to the queue */
1062
1063     /* compute the window surrounding *inOffsetp of size cm_chunkSize */
1064     scanStart = *inOffsetp;
1065     scanStart.LowPart &= (-cm_chunkSize);
1066     thyper = ConvertLongToLargeInteger(cm_chunkSize);
1067     scanEnd = LargeIntegerAdd(scanStart, thyper);
1068
1069     flags = CM_SCACHESYNC_GETSTATUS
1070         | CM_SCACHESYNC_STOREDATA
1071         | CM_SCACHESYNC_BUFLOCKED
1072         | CM_SCACHESYNC_NOWAIT;
1073
1074     /* start by looking backwards until scanStart */
1075     /* hyper version of cm_data.buf_blockSize */
1076     thyper = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1077     tbase = LargeIntegerSubtract(firstModOffset, thyper);
1078     while(LargeIntegerGreaterThanOrEqualTo(tbase, scanStart)) {
1079         /* see if we can find the buffer */
1080         bufp = buf_Find(scp, &tbase);
1081         if (!bufp) 
1082             break;
1083
1084         /* try to lock it, and quit if we can't (simplifies locking) */
1085         lock_ReleaseWrite(&scp->rw);
1086         code = lock_TryMutex(&bufp->mx);
1087         lock_ObtainWrite(&scp->rw);
1088         if (code == 0) {
1089             buf_Release(bufp);
1090             bufp = NULL;
1091             break;
1092         }
1093                 
1094         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1095         if (code) {
1096             lock_ReleaseMutex(&bufp->mx);
1097             buf_Release(bufp);
1098             bufp = NULL;
1099             break;
1100         }
1101                 
1102         if (!(bufp->flags & CM_BUF_DIRTY)) {
1103             /* buffer is clean, so we shouldn't add it */
1104             cm_SyncOpDone(scp, bufp, flags);
1105             lock_ReleaseMutex(&bufp->mx);
1106             buf_Release(bufp);
1107             bufp = NULL;
1108             break;
1109         }
1110
1111         /* don't need buffer mutex any more */
1112         lock_ReleaseMutex(&bufp->mx);
1113
1114         /* we have a dirty buffer ready for storing.  Add it to the tail
1115          * of the list, since it immediately precedes all of the disk
1116          * addresses we've already collected.
1117          */
1118         qdp = osi_QDAlloc();
1119         osi_SetQData(qdp, bufp);
1120         /* no buf_hold necessary, since we have it held from buf_Find */
1121         osi_QAddT((osi_queue_t **) &biop->bufListp,
1122                   (osi_queue_t **) &biop->bufListEndp,
1123                   &qdp->q);
1124         bufp = NULL;            /* added to the queue */
1125
1126         /* update biod info describing the transfer */
1127         biop->offset = LargeIntegerSubtract(biop->offset, thyper);
1128         biop->length += cm_data.buf_blockSize;
1129
1130         /* update loop pointer */
1131         tbase = LargeIntegerSubtract(tbase, thyper);
1132     }   /* while loop looking for pages preceding the one we found */
1133
1134     /* now, find later dirty, contiguous pages, and add them to the list */
1135     /* hyper version of cm_data.buf_blockSize */
1136     thyper = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1137     tbase = LargeIntegerAdd(firstModOffset, thyper);
1138     while(LargeIntegerLessThan(tbase, scanEnd)) {
1139         /* see if we can find the buffer */
1140         bufp = buf_Find(scp, &tbase);
1141         if (!bufp) 
1142             break;
1143
1144         /* try to lock it, and quit if we can't (simplifies locking) */
1145         lock_ReleaseWrite(&scp->rw);
1146         code = lock_TryMutex(&bufp->mx);
1147         lock_ObtainWrite(&scp->rw);
1148         if (code == 0) {
1149             buf_Release(bufp);
1150             bufp = NULL;
1151             break;
1152         }
1153
1154         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
1155         if (code) {
1156             lock_ReleaseMutex(&bufp->mx);
1157             buf_Release(bufp);
1158             bufp = NULL;
1159             break;
1160         }
1161                 
1162         if (!(bufp->flags & CM_BUF_DIRTY)) {
1163             /* buffer is clean, so we shouldn't add it */
1164             cm_SyncOpDone(scp, bufp, flags);
1165             lock_ReleaseMutex(&bufp->mx);
1166             buf_Release(bufp);
1167             bufp = NULL;
1168             break;
1169         }
1170
1171         /* don't need buffer mutex any more */
1172         lock_ReleaseMutex(&bufp->mx);
1173
1174         /* we have a dirty buffer ready for storing.  Add it to the head
1175          * of the list, since it immediately follows all of the disk
1176          * addresses we've already collected.
1177          */
1178         qdp = osi_QDAlloc();
1179         osi_SetQData(qdp, bufp);
1180         /* no buf_hold necessary, since we have it held from buf_Find */
1181         osi_QAddH((osi_queue_t **) &biop->bufListp,
1182                   (osi_queue_t **) &biop->bufListEndp,
1183                   &qdp->q);
1184         bufp = NULL;
1185
1186         /* update biod info describing the transfer */
1187         biop->length += cm_data.buf_blockSize;
1188                 
1189         /* update loop pointer */
1190         tbase = LargeIntegerAdd(tbase, thyper);
1191     }   /* while loop looking for pages following the first page we found */
1192         
1193     /* finally, we're done */
1194     return 0;
1195 }
1196
1197 /* scp must be locked; temporarily unlocked during processing.
1198  * If returns 0, returns buffers held in biop, and with
1199  * CM_BUF_CMFETCHING flags set.
1200  * If an error is returned, we don't return any buffers.
1201  */
1202 long cm_SetupFetchBIOD(cm_scache_t *scp, osi_hyper_t *offsetp,
1203                         cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
1204 {
1205     long code;
1206     cm_buf_t *tbp;
1207     osi_hyper_t tblocksize;             /* a long long temp variable */
1208     osi_hyper_t pageBase;               /* base offset we're looking at */
1209     osi_queueData_t *qdp;               /* one temp queue structure */
1210     osi_queueData_t *tqdp;              /* another temp queue structure */
1211     long collected;                     /* how many bytes have been collected */
1212     int isFirst;
1213     long flags;
1214     osi_hyper_t fileSize;               /* the # of bytes in the file */
1215     osi_queueData_t *heldBufListp;      /* we hold all buffers in this list */
1216     osi_queueData_t *heldBufListEndp;   /* first one */
1217     int reserving;
1218
1219     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
1220
1221     biop->scp = scp;                    /* do not hold; held by caller */
1222     biop->offset = *offsetp;
1223     /* null out the list of buffers */
1224     biop->bufListp = biop->bufListEndp = NULL;
1225     biop->reserved = 0;
1226
1227     /* first lookup the file's length, so we know when to stop */
1228     code = cm_SyncOp(scp, NULL, userp, reqp, 0, 
1229                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1230     if (code) 
1231         return code;
1232         
1233     /* copy out size, since it may change */
1234     fileSize = scp->serverLength;
1235         
1236     lock_ReleaseWrite(&scp->rw);
1237
1238     pageBase = *offsetp;
1239     collected = pageBase.LowPart & (cm_chunkSize - 1);
1240     heldBufListp = NULL;
1241     heldBufListEndp = NULL;
1242
1243     /*
1244      * Obtaining buffers can cause dirty buffers to be recycled, which
1245      * can cause a storeback, so cannot be done while we have buffers
1246      * reserved.
1247      *
1248      * To get around this, we get buffers twice.  Before reserving buffers,
1249      * we obtain and release each one individually.  After reserving
1250      * buffers, we try to obtain them again, but only by lookup, not by
1251      * recycling.  If a buffer has gone away while we were waiting for
1252      * the others, we just use whatever buffers we already have.
1253      *
1254      * On entry to this function, we are already holding a buffer, so we
1255      * can't wait for reservation.  So we call buf_TryReserveBuffers()
1256      * instead.  Not only that, we can't really even call buf_Get(), for
1257      * the same reason.  We can't avoid that, though.  To avoid deadlock
1258      * we allow only one thread to be executing the buf_Get()-buf_Release()
1259      * sequence at a time.
1260      */
1261
1262     /* first hold all buffers, since we can't hold any locks in buf_Get */
1263     while (1) {
1264         /* stop at chunk boundary */
1265         if (collected >= cm_chunkSize) 
1266             break;
1267                 
1268         /* see if the next page would be past EOF */
1269         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize)) 
1270             break;
1271
1272         code = buf_Get(scp, &pageBase, reqp, &tbp);
1273         if (code) {
1274             lock_ObtainWrite(&scp->rw);
1275             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1276             return code;
1277         }
1278                 
1279         buf_Release(tbp);
1280         tbp = NULL;
1281
1282         pageBase = LargeIntegerAdd(tblocksize, pageBase);
1283         collected += cm_data.buf_blockSize;
1284     }
1285
1286     /* reserve a chunk's worth of buffers if possible */
1287     reserving = buf_TryReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1288
1289     pageBase = *offsetp;
1290     collected = pageBase.LowPart & (cm_chunkSize - 1);
1291
1292     /* now hold all buffers, if they are still there */
1293     while (1) {
1294         /* stop at chunk boundary */
1295         if (collected >= cm_chunkSize) 
1296             break;
1297                 
1298         /* see if the next page would be past EOF */
1299         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize)) 
1300             break;
1301
1302         tbp = buf_Find(scp, &pageBase);
1303         if (!tbp) 
1304             break;
1305
1306         /* add the buffer to the list */
1307         qdp = osi_QDAlloc();
1308         osi_SetQData(qdp, tbp);
1309         osi_QAddH((osi_queue_t **)&heldBufListp, 
1310                   (osi_queue_t **)&heldBufListEndp, 
1311                   &qdp->q);
1312         /* leave tbp held (from buf_Get) */
1313
1314         if (!reserving) 
1315             break;
1316
1317         collected += cm_data.buf_blockSize;
1318         pageBase = LargeIntegerAdd(tblocksize, pageBase);
1319     }
1320
1321     /* look at each buffer, adding it into the list if it looks idle and
1322      * filled with old data.  One special case: wait for idle if it is the
1323      * first buffer since we really need that one for our caller to make
1324      * any progress.
1325      */
1326     isFirst = 1;
1327     collected = 0;              /* now count how many we'll really use */
1328     for (tqdp = heldBufListEndp;
1329         tqdp;
1330           tqdp = (osi_queueData_t *) osi_QPrev(&tqdp->q)) {
1331         /* get a ptr to the held buffer */
1332         tbp = osi_GetQData(tqdp);
1333         pageBase = tbp->offset;
1334
1335         /* now lock the buffer lock */
1336         lock_ObtainMutex(&tbp->mx);
1337         lock_ObtainWrite(&scp->rw);
1338
1339         /* don't bother fetching over data that is already current */
1340         if (tbp->dataVersion <= scp->dataVersion && tbp->dataVersion >= scp->bufDataVersionLow) {
1341             /* we don't need this buffer, since it is current */
1342             lock_ReleaseWrite(&scp->rw);
1343             lock_ReleaseMutex(&tbp->mx);
1344             break;
1345         }
1346
1347         flags = CM_SCACHESYNC_FETCHDATA | CM_SCACHESYNC_BUFLOCKED;
1348         if (!isFirst) 
1349             flags |= CM_SCACHESYNC_NOWAIT;
1350
1351         /* wait for the buffer to serialize, if required.  Doesn't
1352          * release the scp or buffer lock(s) if NOWAIT is specified.
1353          */
1354         code = cm_SyncOp(scp, tbp, userp, reqp, 0, flags);
1355         if (code) {
1356             lock_ReleaseWrite(&scp->rw);
1357             lock_ReleaseMutex(&tbp->mx);
1358             break;
1359         }
1360                 
1361         /* don't fetch over dirty buffers */
1362         if (tbp->flags & CM_BUF_DIRTY) {
1363             cm_SyncOpDone(scp, tbp, flags);
1364             lock_ReleaseWrite(&scp->rw);
1365             lock_ReleaseMutex(&tbp->mx);
1366             break;
1367         }
1368
1369         /* Release locks */
1370         lock_ReleaseWrite(&scp->rw);
1371         lock_ReleaseMutex(&tbp->mx);
1372
1373         /* add the buffer to the list */
1374         qdp = osi_QDAlloc();
1375         osi_SetQData(qdp, tbp);
1376         osi_QAddH((osi_queue_t **)&biop->bufListp, 
1377                   (osi_queue_t **)&biop->bufListEndp, 
1378                   &qdp->q);
1379         buf_Hold(tbp);
1380
1381         /* from now on, a failure just stops our collection process, but
1382          * we still do the I/O to whatever we've already managed to collect.
1383          */
1384         isFirst = 0;
1385         collected += cm_data.buf_blockSize;
1386     }
1387         
1388     /* now, we've held in biop->bufListp all the buffer's we're really
1389      * interested in.  We also have holds left from heldBufListp, and we
1390      * now release those holds on the buffers.
1391      */
1392     for (qdp = heldBufListp; qdp; qdp = tqdp) {
1393         tqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1394         tbp = osi_GetQData(qdp);
1395         osi_QRemoveHT((osi_queue_t **) &heldBufListp,
1396                       (osi_queue_t **) &heldBufListEndp,
1397                       &qdp->q);
1398         osi_QDFree(qdp);
1399         buf_Release(tbp);
1400         tbp = NULL;
1401     }
1402
1403     /* Caller expects this */
1404     lock_ObtainWrite(&scp->rw);
1405  
1406     /* if we got a failure setting up the first buffer, then we don't have
1407      * any side effects yet, and we also have failed an operation that the
1408      * caller requires to make any progress.  Give up now.
1409      */
1410     if (code && isFirst) {
1411         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1412         return code;
1413     }
1414         
1415     /* otherwise, we're still OK, and should just return the I/O setup we've
1416      * got.
1417      */
1418     biop->length = collected;
1419     biop->reserved = reserving;
1420     return 0;
1421 }
1422
1423 /* release a bulk I/O structure that was setup by cm_SetupFetchBIOD or by
1424  * cm_SetupStoreBIOD
1425  */
1426 void cm_ReleaseBIOD(cm_bulkIO_t *biop, int isStore, long code, int scp_locked)
1427 {
1428     cm_scache_t *scp;           /* do not release; not held in biop */
1429     cm_buf_t *bufp;
1430     osi_queueData_t *qdp;
1431     osi_queueData_t *nqdp;
1432     int flags;
1433
1434     /* Give back reserved buffers */
1435     if (biop->reserved)
1436         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1437         
1438     if (isStore)
1439         flags = CM_SCACHESYNC_STOREDATA;
1440     else
1441         flags = CM_SCACHESYNC_FETCHDATA;
1442
1443     scp = biop->scp;
1444     if (biop->bufListp) {
1445         for(qdp = biop->bufListp; qdp; qdp = nqdp) {
1446             /* lookup next guy first, since we're going to free this one */
1447             nqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1448                 
1449             /* extract buffer and free queue data */
1450             bufp = osi_GetQData(qdp);
1451             osi_QRemoveHT((osi_queue_t **) &biop->bufListp,
1452                            (osi_queue_t **) &biop->bufListEndp,
1453                            &qdp->q);
1454             osi_QDFree(qdp);
1455
1456             /* now, mark I/O as done, unlock the buffer and release it */
1457             if (scp_locked)
1458                 lock_ReleaseWrite(&scp->rw);
1459             lock_ObtainMutex(&bufp->mx);
1460             lock_ObtainWrite(&scp->rw);
1461             cm_SyncOpDone(scp, bufp, flags);
1462                 
1463             /* turn off writing and wakeup users */
1464             if (isStore) {
1465                 if (bufp->flags & CM_BUF_WAITING) {
1466                     osi_Log2(afsd_logp, "cm_ReleaseBIOD Waking [scp 0x%p] bp 0x%p", scp, bufp);
1467                     osi_Wakeup((LONG_PTR) bufp);
1468                 }
1469                 if (code) {
1470                     bufp->flags &= ~CM_BUF_WRITING;
1471                     switch (code) {
1472                     case CM_ERROR_NOSUCHFILE:
1473                     case CM_ERROR_BADFD:
1474                     case CM_ERROR_NOACCESS:
1475                     case CM_ERROR_QUOTA:
1476                     case CM_ERROR_SPACE:
1477                     case CM_ERROR_TOOBIG:
1478                     case CM_ERROR_READONLY:
1479                     case CM_ERROR_NOSUCHPATH:
1480                         /*
1481                          * Apply the fatal error to this buffer.
1482                          */
1483                         bufp->flags &= ~CM_BUF_DIRTY;
1484                         bufp->flags |= CM_BUF_ERROR;
1485                         bufp->dirty_offset = 0;
1486                         bufp->dirty_length = 0;
1487                         bufp->error = code;
1488                         bufp->dataVersion = CM_BUF_VERSION_BAD;
1489                         bufp->dirtyCounter++;
1490                         break;
1491                     case CM_ERROR_TIMEDOUT:
1492                     case CM_ERROR_ALLDOWN:
1493                     case CM_ERROR_ALLBUSY:
1494                     case CM_ERROR_ALLOFFLINE:
1495                     case CM_ERROR_CLOCKSKEW:
1496                     default:
1497                         /* do not mark the buffer in error state but do
1498                         * not attempt to complete the rest either.
1499                         */
1500                         break;
1501                     }
1502                 } else {
1503                     bufp->flags &= ~(CM_BUF_WRITING | CM_BUF_DIRTY);
1504                     bufp->dirty_offset = bufp->dirty_length = 0;
1505                 }
1506             }
1507
1508             if (!scp_locked)
1509                 lock_ReleaseWrite(&scp->rw);
1510             lock_ReleaseMutex(&bufp->mx);
1511             buf_Release(bufp);
1512             bufp = NULL;
1513         }
1514     } else {
1515         if (!scp_locked)
1516             lock_ObtainWrite(&scp->rw);
1517         cm_SyncOpDone(scp, NULL, flags);
1518         if (!scp_locked)
1519             lock_ReleaseWrite(&scp->rw);
1520     }
1521
1522     /* clean things out */
1523     biop->bufListp = NULL;
1524     biop->bufListEndp = NULL;
1525 }   
1526
1527 static int
1528 cm_CloneStatus(cm_scache_t *scp, cm_user_t *userp, int scp_locked,
1529                AFSFetchStatus *afsStatusp, AFSVolSync *volSyncp)
1530 {
1531     // setup the status based upon the scp data
1532     afsStatusp->InterfaceVersion = 0x1;
1533     switch (scp->fileType) {
1534     case CM_SCACHETYPE_FILE:
1535         afsStatusp->FileType = File;
1536         break;
1537     case CM_SCACHETYPE_DIRECTORY:
1538         afsStatusp->FileType = Directory;
1539         break;
1540     case CM_SCACHETYPE_MOUNTPOINT:
1541         afsStatusp->FileType = SymbolicLink;
1542         break;
1543     case CM_SCACHETYPE_SYMLINK:
1544     case CM_SCACHETYPE_DFSLINK:
1545         afsStatusp->FileType = SymbolicLink;
1546         break;
1547     default:
1548         afsStatusp->FileType = -1;    /* an invalid value */
1549     }
1550     afsStatusp->LinkCount = scp->linkCount;
1551     afsStatusp->Length = scp->length.LowPart;
1552     afsStatusp->DataVersion = (afs_uint32)(scp->dataVersion & MAX_AFS_UINT32);
1553     afsStatusp->Author = 0x1;
1554     afsStatusp->Owner = scp->owner;
1555     if (!scp_locked) {
1556         lock_ObtainWrite(&scp->rw);
1557         scp_locked = 1;
1558     }
1559     if (cm_FindACLCache(scp, userp, &afsStatusp->CallerAccess))
1560         afsStatusp->CallerAccess = scp->anyAccess;
1561     afsStatusp->AnonymousAccess = scp->anyAccess;
1562     afsStatusp->UnixModeBits = scp->unixModeBits;
1563     afsStatusp->ParentVnode = scp->parentVnode;
1564     afsStatusp->ParentUnique = scp->parentUnique;
1565     afsStatusp->ResidencyMask = 0;
1566     afsStatusp->ClientModTime = scp->clientModTime;
1567     afsStatusp->ServerModTime = scp->serverModTime;
1568     afsStatusp->Group = scp->group;
1569     afsStatusp->SyncCounter = 0;
1570     afsStatusp->dataVersionHigh = (afs_uint32)(scp->dataVersion >> 32);
1571     afsStatusp->lockCount = 0;
1572     afsStatusp->Length_hi = scp->length.HighPart;
1573     afsStatusp->errorCode = 0;
1574
1575     volSyncp->spare1 = scp->volumeCreationDate;
1576
1577     return scp_locked;
1578 }
1579
1580 /* Fetch a buffer.  Called with scp locked.
1581  * The scp is locked on return.
1582  */
1583 long cm_GetBuffer(cm_scache_t *scp, cm_buf_t *bufp, int *cpffp, cm_user_t *userp,
1584                   cm_req_t *reqp)
1585 {
1586     long code=0, code1=0;
1587     afs_uint32 nbytes;                  /* bytes in transfer */
1588     afs_uint32 nbytes_hi = 0;            /* high-order 32 bits of bytes in transfer */
1589     afs_uint64 length_found = 0;
1590     long rbytes;                        /* bytes in rx_Read call */
1591     long temp;
1592     AFSFetchStatus afsStatus;
1593     AFSCallBack callback;
1594     AFSVolSync volSync;
1595     char *bufferp;
1596     afs_uint32 buffer_offset;
1597     cm_buf_t *tbufp;                    /* buf we're filling */
1598     osi_queueData_t *qdp;               /* q element we're scanning */
1599     AFSFid tfid;
1600     struct rx_call *rxcallp;
1601     struct rx_connection *rxconnp;
1602     cm_bulkIO_t biod;           /* bulk IO descriptor */
1603     cm_conn_t *connp;
1604     int getroot;
1605     afs_int32 t1,t2;
1606     int require_64bit_ops = 0;
1607     int call_was_64bit = 0;
1608     int fs_fetchdata_offset_bug = 0;
1609     int first_read = 1;
1610     int scp_locked = 1;
1611
1612     memset(&volSync, 0, sizeof(volSync));
1613
1614     /* now, the buffer may or may not be filled with good data (buf_GetNewLocked
1615      * drops lots of locks, and may indeed return a properly initialized
1616      * buffer, although more likely it will just return a new, empty, buffer.
1617      */
1618
1619 #ifdef AFS_FREELANCE_CLIENT
1620
1621     // yj: if they're trying to get the /afs directory, we need to
1622     // handle it differently, since it's local rather than on any
1623     // server
1624
1625     getroot = (scp==cm_data.rootSCachep);
1626     if (getroot)
1627         osi_Log1(afsd_logp,"GetBuffer returns cm_data.rootSCachep=%x",cm_data.rootSCachep);
1628 #endif
1629
1630     if (cm_HaveCallback(scp) && bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow) {
1631         /* We already have this buffer don't do extra work */
1632         return 0;
1633     }
1634
1635     cm_AFSFidFromFid(&tfid, &scp->fid);
1636
1637     code = cm_SetupFetchBIOD(scp, &bufp->offset, &biod, userp, reqp);
1638     if (code) {
1639         /* couldn't even get the first page setup properly */
1640         osi_Log1(afsd_logp, "GetBuffer: SetupFetchBIOD failure code %d", code);
1641         return code;
1642     }
1643
1644     /* once we get here, we have the callback in place, we know that no one
1645      * is fetching the data now.  Check one last time that we still have
1646      * the wrong data, and then fetch it if we're still wrong.
1647      *
1648      * We can lose a race condition and end up with biod.length zero, in
1649      * which case we just retry.
1650      */
1651     if (bufp->dataVersion <= scp->dataVersion && bufp->dataVersion >= scp->bufDataVersionLow || biod.length == 0) {
1652         if ((bufp->dataVersion == CM_BUF_VERSION_BAD || bufp->dataVersion < scp->bufDataVersionLow) && 
1653              LargeIntegerGreaterThanOrEqualTo(bufp->offset, scp->serverLength)) 
1654         {
1655             osi_Log4(afsd_logp, "Bad DVs 0x%x != (0x%x -> 0x%x) or length 0x%x",
1656                      bufp->dataVersion, scp->bufDataVersionLow, scp->dataVersion, biod.length);
1657
1658             if (bufp->dataVersion == CM_BUF_VERSION_BAD)
1659                 memset(bufp->datap, 0, cm_data.buf_blockSize);
1660             bufp->dataVersion = scp->dataVersion;
1661         }
1662         cm_ReleaseBIOD(&biod, 0, 0, 1);
1663         return 0;
1664     } else if ((bufp->dataVersion == CM_BUF_VERSION_BAD || bufp->dataVersion < scp->bufDataVersionLow)
1665                 && (scp->mask & CM_SCACHEMASK_TRUNCPOS) &&
1666                 LargeIntegerGreaterThanOrEqualTo(bufp->offset, scp->truncPos)) {
1667         memset(bufp->datap, 0, cm_data.buf_blockSize);
1668         bufp->dataVersion = scp->dataVersion;
1669         cm_ReleaseBIOD(&biod, 0, 0, 1);
1670         return 0;
1671     }
1672
1673     lock_ReleaseWrite(&scp->rw);
1674     scp_locked = 0;
1675
1676     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
1677                                                 ConvertLongToLargeInteger(biod.length)),
1678                                 ConvertLongToLargeInteger(LONG_MAX))) {
1679         require_64bit_ops = 1;
1680     }
1681
1682     osi_Log2(afsd_logp, "cm_GetBuffer: fetching data scp %p bufp %p", scp, bufp);
1683     osi_Log3(afsd_logp, "cm_GetBuffer: fetching data scpDV 0x%x scpDVLow 0x%x bufDV 0x%x",
1684              scp->dataVersion, scp->bufDataVersionLow, bufp->dataVersion);
1685
1686 #ifdef AFS_FREELANCE_CLIENT
1687
1688     // yj code
1689     // if getroot then we don't need to make any calls
1690     // just return fake data
1691         
1692     if (cm_freelanceEnabled && getroot) {
1693         // setup the fake status                        
1694         afsStatus.InterfaceVersion = 0x1;
1695         afsStatus.FileType = 0x2;
1696         afsStatus.LinkCount = scp->linkCount;
1697         afsStatus.Length = cm_fakeDirSize;
1698         afsStatus.DataVersion = (afs_uint32)(cm_data.fakeDirVersion & 0xFFFFFFFF);
1699         afsStatus.Author = 0x1;
1700         afsStatus.Owner = 0x0;
1701         afsStatus.CallerAccess = 0x9;
1702         afsStatus.AnonymousAccess = 0x9;
1703         afsStatus.UnixModeBits = 0x1ff;
1704         afsStatus.ParentVnode = 0x1;
1705         afsStatus.ParentUnique = 0x1;
1706         afsStatus.ResidencyMask = 0;
1707         afsStatus.ClientModTime = (afs_uint32)FakeFreelanceModTime;
1708         afsStatus.ServerModTime = (afs_uint32)FakeFreelanceModTime;
1709         afsStatus.Group = 0;
1710         afsStatus.SyncCounter = 0;
1711         afsStatus.dataVersionHigh = (afs_uint32)(cm_data.fakeDirVersion >> 32);
1712         afsStatus.lockCount = 0;
1713         afsStatus.Length_hi = 0;
1714         afsStatus.errorCode = 0;
1715         memset(&volSync, 0, sizeof(volSync));
1716
1717         // once we're done setting up the status info,
1718         // we just fill the buffer pages with fakedata
1719         // from cm_FakeRootDir. Extra pages are set to
1720         // 0. 
1721                 
1722         lock_ObtainMutex(&cm_Freelance_Lock);
1723         t1 = bufp->offset.LowPart;
1724         qdp = biod.bufListEndp;
1725         while (qdp) {
1726             tbufp = osi_GetQData(qdp);
1727             bufferp=tbufp->datap;
1728             memset(bufferp, 0, cm_data.buf_blockSize);
1729             t2 = cm_fakeDirSize - t1;
1730             if (t2> (afs_int32)cm_data.buf_blockSize) 
1731                 t2=cm_data.buf_blockSize;
1732             if (t2 > 0) {
1733                 memcpy(bufferp, cm_FakeRootDir+t1, t2);
1734             } else {
1735                 t2 = 0;
1736             }
1737             t1+=t2;
1738             qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1739
1740         }
1741         lock_ReleaseMutex(&cm_Freelance_Lock);
1742         
1743         // once we're done, we skip over the part of the
1744         // code that does the ACTUAL fetching of data for
1745         // real files
1746
1747         goto fetchingcompleted;
1748     }
1749
1750 #endif /* AFS_FREELANCE_CLIENT */
1751
1752     /*
1753      * if the requested offset is greater than the file length,
1754      * the file server will return zero bytes of data and the
1755      * current status for the file which we already have since
1756      * we have just obtained a callback.  Instead, we can avoid
1757      * the network round trip by allocating zeroed buffers and
1758      * faking the status info.
1759      */
1760     if (biod.offset.QuadPart >= scp->length.QuadPart) {
1761         osi_Log5(afsd_logp, "SKIP FetchData64 scp 0x%p, off 0x%x:%08x > length 0x%x:%08x",
1762                  scp, biod.offset.HighPart, biod.offset.LowPart,
1763                  scp->length.HighPart, scp->length.LowPart);
1764
1765         /* Clone the current status info */
1766         scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
1767
1768         /* status info complete, fill pages with zeros */
1769         for (qdp = biod.bufListEndp;
1770              qdp;
1771              qdp = (osi_queueData_t *) osi_QPrev(&qdp->q)) {
1772             tbufp = osi_GetQData(qdp);
1773             bufferp=tbufp->datap;
1774             memset(bufferp, 0, cm_data.buf_blockSize);
1775         }
1776
1777         /* no need to contact the file server */
1778         goto fetchingcompleted;
1779     }
1780
1781     if (scp_locked) {
1782         lock_ReleaseWrite(&scp->rw);
1783         scp_locked = 0;
1784     }
1785
1786     /* now make the call */
1787     do {
1788         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
1789         if (code) 
1790             continue;
1791
1792         rxconnp = cm_GetRxConn(connp);
1793         rxcallp = rx_NewCall(rxconnp);
1794         rx_PutConnection(rxconnp);
1795
1796         nbytes = nbytes_hi = 0;
1797
1798         if (SERVERHAS64BIT(connp)) {
1799             call_was_64bit = 1;
1800
1801             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
1802                      scp, biod.offset.HighPart, biod.offset.LowPart, biod.length);
1803
1804             code = StartRXAFS_FetchData64(rxcallp, &tfid, biod.offset.QuadPart, biod.length);
1805
1806             if (code == 0) {
1807                 temp = rx_Read32(rxcallp, &nbytes_hi);
1808                 if (temp == sizeof(afs_int32)) {
1809                     nbytes_hi = ntohl(nbytes_hi);
1810                 } else {
1811                     nbytes_hi = 0;
1812                     code = rxcallp->error;
1813                     code1 = rx_EndCall(rxcallp, code);
1814                     rxcallp = NULL;
1815                 }
1816             }
1817         } else {
1818             call_was_64bit = 0;
1819         }
1820
1821         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
1822             if (require_64bit_ops) {
1823                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
1824                 code = CM_ERROR_TOOBIG;
1825             } else {
1826                 if (!rxcallp) {
1827                     rxconnp = cm_GetRxConn(connp);
1828                     rxcallp = rx_NewCall(rxconnp);
1829                     rx_PutConnection(rxconnp);
1830                 }
1831
1832                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
1833                          scp, biod.offset.LowPart, biod.length);
1834
1835                 code = StartRXAFS_FetchData(rxcallp, &tfid, biod.offset.LowPart,
1836                                             biod.length);
1837
1838                 SET_SERVERHASNO64BIT(connp);
1839             }
1840         }
1841
1842         if (code == 0) {
1843             temp  = rx_Read32(rxcallp, &nbytes);
1844             if (temp == sizeof(afs_int32)) {
1845                 nbytes = ntohl(nbytes);
1846                 FillInt64(length_found, nbytes_hi, nbytes);
1847                 if (length_found > biod.length) {
1848                     /*
1849                      * prior to 1.4.12 and 1.5.65 the file server would return
1850                      * (filesize - offset) if the requested offset was greater than
1851                      * the filesize.  The correct return value would have been zero.
1852                      * Force a retry by returning an RX_PROTOCOL_ERROR.  If the cause
1853                      * is a race between two RPCs issues by this cache manager, the
1854                      * correct thing will happen the second time.
1855                      */
1856                     osi_Log0(afsd_logp, "cm_GetBuffer length_found > biod.length");
1857                     fs_fetchdata_offset_bug = 1;
1858                 }
1859             } else {
1860                 osi_Log1(afsd_logp, "cm_GetBuffer rx_Read32 returns %d != 4", temp);
1861                 code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
1862             }
1863         }
1864         /* for the moment, nbytes_hi will always be 0 if code == 0
1865            because biod.length is a 32-bit quantity. */
1866
1867         if (code == 0) {
1868             qdp = biod.bufListEndp;
1869             if (qdp) {
1870                 tbufp = osi_GetQData(qdp);
1871                 bufferp = tbufp->datap;
1872                 buffer_offset = 0;
1873             }
1874             else 
1875                 bufferp = NULL;
1876
1877             /* fill length_found of data from the pipe into the pages.
1878              * When we stop, qdp will point at the last page we're
1879              * dealing with, and bufferp will tell us where we
1880              * stopped.  We'll need this info below when we clear
1881              * the remainder of the last page out (and potentially
1882              * clear later pages out, if we fetch past EOF).
1883              */
1884             while (length_found > 0) {
1885 #ifdef USE_RX_IOVEC
1886                 struct iovec tiov[RX_MAXIOVECS];
1887                 afs_int32 tnio, iov, iov_offset;
1888
1889                 temp = rx_Readv(rxcallp, tiov, &tnio, RX_MAXIOVECS, length_found);
1890                 osi_Log1(afsd_logp, "cm_GetBuffer rx_Readv returns %d", temp);
1891                 if (temp != length_found && temp < cm_data.buf_blockSize) {
1892                     /*
1893                      * If the file server returned (filesize - offset),
1894                      * then the first rx_Read will return zero octets of data.
1895                      * If it does, do not treat it as an error.  Correct the
1896                      * length_found and continue as if the file server said
1897                      * it was sending us zero octets of data.
1898                      */
1899                     if (fs_fetchdata_offset_bug && first_read)
1900                         length_found = 0;
1901                     else
1902                         code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
1903                     break;
1904                 }
1905
1906                 iov = 0;
1907                 iov_offset = 0;
1908                 rbytes = temp;
1909
1910                 while (rbytes > 0) {
1911                     afs_int32 len;
1912
1913                     osi_assertx(bufferp != NULL, "null cm_buf_t");
1914
1915                     len = MIN(tiov[iov].iov_len - iov_offset, cm_data.buf_blockSize - buffer_offset);
1916                     memcpy(bufferp + buffer_offset, tiov[iov].iov_base + iov_offset, len);
1917                     iov_offset += len;
1918                     buffer_offset += len;
1919                     rbytes -= len;
1920
1921                     if (iov_offset == tiov[iov].iov_len) {
1922                         iov++;
1923                         iov_offset = 0;
1924                     }
1925
1926                     if (buffer_offset == cm_data.buf_blockSize) {
1927                         /* allow read-while-fetching.
1928                         * if this is the last buffer, clear the
1929                         * PREFETCHING flag, so the reader waiting for
1930                         * this buffer will start a prefetch.
1931                         */
1932                         tbufp->cmFlags |= CM_BUF_CMFULLYFETCHED;
1933                         lock_ObtainWrite(&scp->rw);
1934                         if (scp->flags & CM_SCACHEFLAG_WAITING) {
1935                             osi_Log1(afsd_logp, "CM GetBuffer Waking scp 0x%p", scp);
1936                             osi_Wakeup((LONG_PTR) &scp->flags);
1937                         }
1938                         if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
1939                             osi_hyper_t tlength = ConvertLongToLargeInteger(biod.length);
1940                             *cpffp = 1;
1941                             cm_ClearPrefetchFlag(0, scp, &biod.offset, &tlength);
1942                         }
1943                         lock_ReleaseWrite(&scp->rw);
1944
1945                         /* Advance the buffer */
1946                         qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1947                         if (qdp) {
1948                             tbufp = osi_GetQData(qdp);
1949                             bufferp = tbufp->datap;
1950                             buffer_offset = 0;
1951                         }
1952                         else
1953                             bufferp = NULL;
1954                     }
1955                 }
1956
1957                 length_found -= temp;
1958 #else /* USE_RX_IOVEC */
1959                 /* assert that there are still more buffers;
1960                  * our check above for length_found being less than
1961                  * biod.length should ensure this.
1962                  */
1963                 osi_assertx(bufferp != NULL, "null cm_buf_t");
1964
1965                 /* read rbytes of data */
1966                 rbytes = (afs_uint32)(length_found > cm_data.buf_blockSize ? cm_data.buf_blockSize : length_found);
1967                 temp = rx_Read(rxcallp, bufferp, rbytes);
1968                 if (temp < rbytes) {
1969                     /*
1970                      * If the file server returned (filesize - offset),
1971                      * then the first rx_Read will return zero octets of data.
1972                      * If it does, do not treat it as an error.  Correct the
1973                      * length_found and continue as if the file server said
1974                      * it was sending us zero octets of data.
1975                      */
1976                     if (fs_fetchdata_offset_bug && first_read)
1977                         length_found = 0;
1978                     else
1979                         code = (rxcallp->error < 0) ? rxcallp->error : RX_PROTOCOL_ERROR;
1980                     break;
1981                 }
1982                 first_read = 0;
1983
1984                 /* allow read-while-fetching.
1985                  * if this is the last buffer, clear the
1986                  * PREFETCHING flag, so the reader waiting for
1987                  * this buffer will start a prefetch.
1988                  */
1989                 tbufp->cmFlags |= CM_BUF_CMFULLYFETCHED;
1990                 lock_ObtainWrite(&scp->rw);
1991                 if (scp->flags & CM_SCACHEFLAG_WAITING) {
1992                     osi_Log1(afsd_logp, "CM GetBuffer Waking scp 0x%p", scp);
1993                     osi_Wakeup((LONG_PTR) &scp->flags);
1994                 }
1995                 if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
1996                     osi_hyper_t tlength = ConvertLongToLargeInteger(biod.length);
1997                     *cpffp = 1;
1998                     cm_ClearPrefetchFlag(0, scp, &biod.offset, &tlength);
1999                 }
2000                 lock_ReleaseWrite(&scp->rw);
2001
2002                 /* and adjust counters */
2003                 length_found -= temp;
2004
2005                 /* and move to the next buffer */
2006                 if (length_found != 0) {
2007                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2008                     if (qdp) {
2009                         tbufp = osi_GetQData(qdp);
2010                         bufferp = tbufp->datap;
2011                     }
2012                     else 
2013                         bufferp = NULL;
2014                 } else 
2015                     bufferp += temp;
2016 #endif /* USE_RX_IOVEC */
2017             }
2018
2019             /* zero out remainder of last pages, in case we are
2020              * fetching past EOF.  We were fetching an integral #
2021              * of pages, but stopped, potentially in the middle of
2022              * a page.  Zero the remainder of that page, and then
2023              * all of the rest of the pages.
2024              */
2025 #ifdef USE_RX_IOVEC
2026             rbytes = cm_data.buf_blockSize - buffer_offset;
2027             bufferp = tbufp->datap + buffer_offset;
2028 #else /* USE_RX_IOVEC */
2029             /* bytes fetched */
2030             osi_assertx((bufferp - tbufp->datap) < LONG_MAX, "data >= LONG_MAX");
2031             rbytes = (long) (bufferp - tbufp->datap);
2032
2033             /* bytes left to zero */
2034             rbytes = cm_data.buf_blockSize - rbytes;
2035 #endif /* USE_RX_IOVEC */
2036             while(qdp) {
2037                 if (rbytes != 0)
2038                     memset(bufferp, 0, rbytes);
2039                 qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
2040                 if (qdp == NULL) 
2041                     break;
2042                 tbufp = osi_GetQData(qdp);
2043                 bufferp = tbufp->datap;
2044                 /* bytes to clear in this page */
2045                 rbytes = cm_data.buf_blockSize;
2046             }   
2047         }
2048
2049         if (code == 0) {
2050             if (call_was_64bit)
2051                 code = EndRXAFS_FetchData64(rxcallp, &afsStatus, &callback, &volSync);
2052             else
2053                 code = EndRXAFS_FetchData(rxcallp, &afsStatus, &callback, &volSync);
2054         } else {
2055             if (call_was_64bit)
2056                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
2057             else
2058                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
2059         }
2060
2061         if (rxcallp)
2062             code1 = rx_EndCall(rxcallp, code);
2063
2064         if (code1 == RXKADUNKNOWNKEY)
2065             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
2066
2067         /* If we are avoiding a file server bug, ignore the error state */
2068         if (fs_fetchdata_offset_bug && first_read && length_found == 0 && code == -451) {
2069             /* Clone the current status info and clear the error state */
2070             scp_locked = cm_CloneStatus(scp, userp, scp_locked, &afsStatus, &volSync);
2071             if (scp_locked) {
2072                 lock_ReleaseWrite(&scp->rw);
2073                 scp_locked = 0;
2074             }
2075             code = 0;
2076         /* Prefer the error value from FetchData over rx_EndCall */
2077         } else if (code == 0 && code1 != 0)
2078             code = code1;
2079         osi_Log0(afsd_logp, "CALL FetchData DONE");
2080
2081     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
2082
2083   fetchingcompleted:
2084     code = cm_MapRPCError(code, reqp);
2085
2086     if (!scp_locked)
2087         lock_ObtainWrite(&scp->rw);
2088     
2089     /* we know that no one else has changed the buffer, since we still have
2090      * the fetching flag on the buffers, and we have the scp locked again.
2091      * Copy in the version # into the buffer if we got code 0 back from the
2092      * read.
2093      */
2094     if (code == 0) {
2095         for(qdp = biod.bufListp;
2096              qdp;
2097              qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
2098             tbufp = osi_GetQData(qdp);
2099             tbufp->dataVersion = afsStatus.dataVersionHigh;
2100             tbufp->dataVersion <<= 32;
2101             tbufp->dataVersion |= afsStatus.DataVersion;
2102
2103 #ifdef DISKCACHE95
2104             /* write buffer out to disk cache */
2105             diskcache_Update(tbufp->dcp, tbufp->datap, cm_data.buf_blockSize,
2106                               tbufp->dataVersion);
2107 #endif /* DISKCACHE95 */
2108         }
2109     }
2110
2111     /* release scatter/gather I/O structure (buffers, locks) */
2112     cm_ReleaseBIOD(&biod, 0, code, 1);
2113
2114     if (code == 0) 
2115         cm_MergeStatus(NULL, scp, &afsStatus, &volSync, userp, reqp, 0);
2116     
2117     return code;
2118 }