windows-volume-status-tracking-20070610
[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 #include <afs/param.h>
11 #include <afs/stds.h>
12
13 #include <windows.h>
14 #include <winsock2.h>
15 #include <nb30.h>
16 #ifdef COMMENT
17 #include <malloc.h>
18 #endif
19 #include <string.h>
20 #include <stdlib.h>
21 #include <osi.h>
22
23 #include "afsd.h"
24
25 #ifdef DEBUG
26 extern void afsi_log(char *pattern, ...);
27 #endif
28
29 osi_mutex_t cm_bufGetMutex;
30 #ifdef AFS_FREELANCE_CLIENT
31 extern osi_mutex_t cm_Freelance_Lock;
32 #endif
33
34 #ifdef AFS_LARGEFILES
35 /* we can access connp->serverp without holding a lock because that
36    never changes since the connection is made. */
37 #define SERVERHAS64BIT(connp) (!((connp)->serverp->flags & CM_SERVERFLAG_NO64BIT))
38 #define SET_SERVERHASNO64BIT(connp) (cm_SetServerNo64Bit((connp)->serverp, TRUE))
39 #else
40 #define SERVERHAS64BIT(connp) (FALSE)
41 #define SET_SERVERHASNO64BIT(connp) (FALSE)
42 #endif
43
44 /* functions called back from the buffer package when reading or writing data,
45  * or when holding or releasing a vnode pointer.
46  */
47 long cm_BufWrite(void *vscp, osi_hyper_t *offsetp, long length, long flags,
48                  cm_user_t *userp, cm_req_t *reqp)
49 {
50     /* store the data back from this buffer; the buffer is locked and held,
51      * but the vnode involved isn't locked, yet.  It is held by its
52      * reference from the buffer, which won't change until the buffer is
53      * released by our caller.  Thus, we don't have to worry about holding
54      * bufp->scp.
55      */
56     long code;
57     cm_scache_t *scp = vscp;
58     long nbytes;
59     long temp;
60     AFSFetchStatus outStatus;
61     AFSStoreStatus inStatus;
62     osi_hyper_t thyper;
63     AFSVolSync volSync;
64     AFSFid tfid;
65     struct rx_call *callp;
66     struct rx_connection *rxconnp;
67     osi_queueData_t *qdp;
68     cm_buf_t *bufp;
69     long wbytes;
70     char *bufferp;
71     cm_conn_t *connp;
72     osi_hyper_t truncPos;
73     cm_bulkIO_t biod;           /* bulk IO descriptor */
74     int require_64bit_ops = 0;
75
76     osi_assert(userp != NULL);
77     osi_assert(scp != NULL);
78
79     /* now, the buffer may or may not be filled with good data (buf_GetNew
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
84     lock_ObtainMutex(&scp->mx);
85     cm_AFSFidFromFid(&tfid, &scp->fid);
86
87     if (scp->flags & CM_SCACHEFLAG_DELETED) {
88         lock_ReleaseMutex(&scp->mx);
89         return CM_ERROR_NOSUCHFILE;
90     }
91
92     code = cm_SetupStoreBIOD(scp, offsetp, length, &biod, userp, reqp);
93     if (code) {
94         osi_Log1(afsd_logp, "cm_SetupStoreBIOD code %x", code);
95         lock_ReleaseMutex(&scp->mx);
96         return code;
97     }
98
99     if (biod.length == 0) {
100         osi_Log0(afsd_logp, "cm_SetupStoreBIOD length 0");
101         lock_ReleaseMutex(&scp->mx);
102         cm_ReleaseBIOD(&biod, 1, 0);    /* should be a NOOP */
103         return 0;
104     }
105
106     /* Serialize StoreData RPC's; for rationale see cm_scache.c */
107     (void) cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA_EXCL);
108
109     /* prepare the output status for the store */
110     scp->mask |= CM_SCACHEMASK_CLIENTMODTIME;
111     cm_StatusFromAttr(&inStatus, scp, NULL);
112     truncPos = scp->length;
113     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
114         && LargeIntegerLessThan(scp->truncPos, truncPos))
115         truncPos = scp->truncPos;
116         scp->mask &= ~CM_SCACHEMASK_TRUNCPOS;
117                 
118     /* compute how many bytes to write from this buffer */
119     thyper = LargeIntegerSubtract(scp->length, biod.offset);
120     if (LargeIntegerLessThanZero(thyper)) {
121         /* entire buffer is past EOF */
122         nbytes = 0;
123     }
124     else {
125         /* otherwise write out part of buffer before EOF, but not
126          * more than bufferSize bytes.
127          */
128         if (LargeIntegerGreaterThan(thyper,
129                                     ConvertLongToLargeInteger(biod.length))) {
130             nbytes = biod.length;
131         } else {
132             /* if thyper is less than or equal to biod.length, then we
133                can safely assume that the value fits in a long. */
134             nbytes = thyper.LowPart;
135         }
136     }
137
138     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
139                                                  ConvertLongToLargeInteger(nbytes)),
140                                  ConvertLongToLargeInteger(LONG_MAX)) ||
141          LargeIntegerGreaterThan(truncPos,
142                                  ConvertLongToLargeInteger(LONG_MAX))) {
143         require_64bit_ops = 1;
144     }
145         
146     lock_ReleaseMutex(&scp->mx);
147
148     /* now we're ready to do the store operation */
149     do {
150         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
151         if (code) 
152             continue;
153
154     retry:
155         rxconnp = cm_GetRxConn(connp);
156         callp = rx_NewCall(rxconnp);
157         rx_PutConnection(rxconnp);
158
159 #ifdef AFS_LARGEFILES
160         if (SERVERHAS64BIT(connp)) {
161             osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData64 scp 0x%p, offset 0x%x:%08x, length 0x%x",
162                      scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
163
164             code = StartRXAFS_StoreData64(callp, &tfid, &inStatus,
165                                           biod.offset.QuadPart,
166                                           nbytes,
167                                           truncPos.QuadPart);
168             if (code)
169                 osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData64 FAILURE, code 0x%x", code);
170             else
171                 osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData64 SUCCESS");
172         } else {
173             if (require_64bit_ops) {
174                 osi_Log0(afsd_logp, "Skipping StartRXAFS_StoreData.  The operation requires large file support in the server.");
175                 code = CM_ERROR_TOOBIG;
176             } else {
177                 osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData scp 0x%p, offset 0x%x:%08x, length 0x%x",
178                          scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
179
180                 code = StartRXAFS_StoreData(callp, &tfid, &inStatus,
181                                             biod.offset.LowPart, nbytes, truncPos.LowPart);
182                 if (code)
183                     osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData FAILURE, code 0x%x", code);
184                 else
185                     osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData SUCCESS");
186             }
187         }
188 #else
189         osi_Log4(afsd_logp, "CALL StartRXAFS_StoreData scp 0x%p, offset 0x%x:%08x, length 0x%x",
190                  scp, biod.offset.HighPart, biod.offset.LowPart, nbytes);
191
192         code = StartRXAFS_StoreData(callp, &tfid, &inStatus,
193                                     biod.offset.LowPart, nbytes, truncPos.LowPart);
194         if (code)
195             osi_Log1(afsd_logp, "CALL StartRXAFS_StoreData FAILURE, code 0x%x", code);
196         else
197             osi_Log0(afsd_logp, "CALL StartRXAFS_StoreData SUCCESS");
198 #endif
199
200         if (code == 0) {
201             /* write the data from the the list of buffers */
202             qdp = NULL;
203             while(nbytes > 0) {
204                 if (qdp == NULL)
205                     qdp = biod.bufListEndp;
206                 else
207                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
208                 osi_assert(qdp != NULL);
209                 bufp = osi_GetQData(qdp);
210                 bufferp = bufp->datap;
211                 wbytes = nbytes;
212                 if (wbytes > cm_data.buf_blockSize) 
213                     wbytes = cm_data.buf_blockSize;
214
215                 /* write out wbytes of data from bufferp */
216                 temp = rx_Write(callp, bufferp, wbytes);
217                 if (temp != wbytes) {
218                     osi_Log3(afsd_logp, "rx_Write failed bp 0x%p, %d != %d",bufp,temp,wbytes);
219                     code = -1;
220                     break;
221                 } else {
222                     osi_Log2(afsd_logp, "rx_Write succeeded bp 0x%p, %d",bufp,temp);
223                 }       
224                 nbytes -= wbytes;
225             }   /* while more bytes to write */
226         }       /* if RPC started successfully */
227
228         if (code == 0) {
229             if (SERVERHAS64BIT(connp)) {
230                 code = EndRXAFS_StoreData64(callp, &outStatus, &volSync);
231                 if (code)
232                     osi_Log2(afsd_logp, "EndRXAFS_StoreData64 FAILURE scp 0x%p code %lX", scp, code);
233                 else
234                     osi_Log0(afsd_logp, "EndRXAFS_StoreData64 SUCCESS");
235             } else {
236                 code = EndRXAFS_StoreData(callp, &outStatus, &volSync);
237                 if (code)
238                     osi_Log2(afsd_logp, "EndRXAFS_StoreData FAILURE scp 0x%p code %lX",scp,code);
239                 else
240                     osi_Log0(afsd_logp, "EndRXAFS_StoreData SUCCESS");
241             }
242         }
243
244         code = rx_EndCall(callp, code);
245
246 #ifdef AFS_LARGEFILES
247         if (code == RXGEN_OPCODE && SERVERHAS64BIT(connp)) {
248             SET_SERVERHASNO64BIT(connp);
249             goto retry;
250         }
251 #endif
252                 
253     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
254
255     code = cm_MapRPCError(code, reqp);
256
257     if (code)
258         osi_Log2(afsd_logp, "CALL StoreData FAILURE scp 0x%p, code 0x%x", scp, code);
259     else
260         osi_Log1(afsd_logp, "CALL StoreData SUCCESS scp 0x%p", scp);
261
262     /* now, clean up our state */
263     lock_ObtainMutex(&scp->mx);
264
265     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
266
267     if (code == 0) {
268         osi_hyper_t t;
269         /* now, here's something a little tricky: in AFS 3, a dirty
270          * length can't be directly stored, instead, a dirty chunk is
271          * stored that sets the file's size (by writing and by using
272          * the truncate-first option in the store call).
273          *
274          * At this point, we've just finished a store, and so the trunc
275          * pos field is clean.  If the file's size at the server is at
276          * least as big as we think it should be, then we turn off the
277          * length dirty bit, since all the other dirty buffers must
278          * precede this one in the file.
279          *
280          * The file's desired size shouldn't be smaller than what's
281          * stored at the server now, since we just did the trunc pos
282          * store.
283          *
284          * We have to turn off the length dirty bit as soon as we can,
285          * so that we see updates made by other machines.
286          */
287
288         if (SERVERHAS64BIT(connp)) {
289             t.LowPart = outStatus.Length;
290             t.HighPart = outStatus.Length_hi;
291         } else {
292             t = ConvertLongToLargeInteger(outStatus.Length);
293         }
294
295         if (LargeIntegerGreaterThanOrEqualTo(t, scp->length))
296             scp->mask &= ~CM_SCACHEMASK_LENGTH;
297
298         cm_MergeStatus(NULL, scp, &outStatus, &volSync, userp, CM_MERGEFLAG_STOREDATA);
299     } else {
300         if (code == CM_ERROR_SPACE)
301             scp->flags |= CM_SCACHEFLAG_OUTOFSPACE;
302         else if (code == CM_ERROR_QUOTA)
303             scp->flags |= CM_SCACHEFLAG_OVERQUOTA;
304     }
305     lock_ReleaseMutex(&scp->mx);
306     cm_ReleaseBIOD(&biod, 1, code);
307
308     return code;
309 }
310
311 /*
312  * Truncate the file, by sending a StoreData RPC with zero length.
313  *
314  * Called with scp locked.  Releases and re-obtains the lock.
315  */
316 long cm_StoreMini(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
317 {
318     AFSFetchStatus outStatus;
319     AFSStoreStatus inStatus;
320     AFSVolSync volSync;
321     AFSFid tfid;
322     long code;
323     osi_hyper_t truncPos;
324     cm_conn_t *connp;
325     struct rx_call *callp;
326     struct rx_connection *rxconnp;
327     int require_64bit_ops = 0;
328
329     /* Serialize StoreData RPC's; for rationale see cm_scache.c */
330     (void) cm_SyncOp(scp, NULL, userp, reqp, 0,
331                      CM_SCACHESYNC_STOREDATA_EXCL);
332
333     /* prepare the output status for the store */
334     inStatus.Mask = AFS_SETMODTIME;
335     inStatus.ClientModTime = scp->clientModTime;
336     scp->mask &= ~CM_SCACHEMASK_CLIENTMODTIME;
337
338     /* calculate truncation position */
339     truncPos = scp->length;
340     if ((scp->mask & CM_SCACHEMASK_TRUNCPOS)
341         && LargeIntegerLessThan(scp->truncPos, truncPos))
342         truncPos = scp->truncPos;
343     scp->mask &= ~CM_SCACHEMASK_TRUNCPOS;
344
345     if (LargeIntegerGreaterThan(truncPos,
346                                 ConvertLongToLargeInteger(LONG_MAX))) {
347
348         require_64bit_ops = 1;
349     }
350
351     lock_ReleaseMutex(&scp->mx);
352
353     cm_AFSFidFromFid(&tfid, &scp->fid);
354
355     /* now we're ready to do the store operation */
356     do {
357         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
358         if (code) 
359             continue;
360
361     retry:      
362         rxconnp = cm_GetRxConn(connp);
363         callp = rx_NewCall(rxconnp);
364         rx_PutConnection(rxconnp);
365
366 #ifdef AFS_LARGEFILES
367         if (SERVERHAS64BIT(connp)) {
368             code = StartRXAFS_StoreData64(callp, &tfid, &inStatus,
369                                           0, 0, truncPos.QuadPart);
370         } else {
371             if (require_64bit_ops) {
372                 code = CM_ERROR_TOOBIG;
373             } else {
374                 code = StartRXAFS_StoreData(callp, &tfid, &inStatus,
375                                             0, 0, truncPos.LowPart);
376             }
377         }
378 #else
379         code = StartRXAFS_StoreData(callp, &tfid, &inStatus,
380                                     0, 0, truncPos.LowPart);
381 #endif
382
383         if (code == 0) {
384             if (SERVERHAS64BIT(connp))
385                 code = EndRXAFS_StoreData64(callp, &outStatus, &volSync);
386             else
387                 code = EndRXAFS_StoreData(callp, &outStatus, &volSync);
388         }
389         code = rx_EndCall(callp, code);
390
391 #ifdef AFS_LARGEFILES
392         if (code == RXGEN_OPCODE && SERVERHAS64BIT(connp)) {
393             SET_SERVERHASNO64BIT(connp);
394             goto retry;
395         }
396 #endif
397
398     } while (cm_Analyze(connp, userp, reqp, &scp->fid, &volSync, NULL, NULL, code));
399     code = cm_MapRPCError(code, reqp);
400         
401     /* now, clean up our state */
402     lock_ObtainMutex(&scp->mx);
403
404     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STOREDATA_EXCL);
405
406     if (code == 0) {
407         osi_hyper_t t;
408         /*
409          * For explanation of handling of CM_SCACHEMASK_LENGTH,
410          * see cm_BufWrite().
411          */
412         if (SERVERHAS64BIT(connp)) {
413             t.HighPart = outStatus.Length_hi;
414             t.LowPart = outStatus.Length;
415         } else {
416             t = ConvertLongToLargeInteger(outStatus.Length);
417         }
418
419         if (LargeIntegerGreaterThanOrEqualTo(t, scp->length))
420             scp->mask &= ~CM_SCACHEMASK_LENGTH;
421         cm_MergeStatus(NULL, scp, &outStatus, &volSync, userp, CM_MERGEFLAG_STOREDATA);
422     }
423
424     return code;
425 }
426
427 long cm_BufRead(cm_buf_t *bufp, long nbytes, long *bytesReadp, cm_user_t *userp)
428 {
429     *bytesReadp = cm_data.buf_blockSize;
430
431     /* now return a code that means that I/O is done */
432     return 0;
433 }
434
435 /* stabilize scache entry, and return with it locked so 
436  * it stays stable.
437  */
438 long cm_BufStabilize(void *vscp, cm_user_t *userp, cm_req_t *reqp)
439 {
440     cm_scache_t *scp = vscp;
441     long code;
442
443     lock_ObtainMutex(&scp->mx);
444     code = cm_SyncOp(scp, NULL, userp, reqp, 0, 
445                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
446     if (code) {
447         lock_ReleaseMutex(&scp->mx);
448         return code;
449     }
450         
451     return 0;
452 }
453
454 /* undoes the work that cm_BufStabilize does: releases lock so things can change again */
455 long cm_BufUnstabilize(void *vscp, cm_user_t *userp)
456 {
457     cm_scache_t *scp = vscp;
458         
459     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_SETSIZE);
460
461     lock_ReleaseMutex(&scp->mx);
462         
463     /* always succeeds */
464     return 0;
465 }
466
467 cm_buf_ops_t cm_bufOps = {
468     cm_BufWrite,
469     cm_BufRead,
470     cm_BufStabilize,
471     cm_BufUnstabilize
472 };
473
474 long cm_ValidateDCache(void)
475 {
476     return buf_ValidateBuffers();
477 }
478
479 long cm_ShutdownDCache(void)
480 {
481     return 0;
482 }
483
484 int cm_InitDCache(int newFile, long chunkSize, afs_uint64 nbuffers)
485 {
486     lock_InitializeMutex(&cm_bufGetMutex, "buf_Get mutex");
487     return buf_Init(newFile, &cm_bufOps, nbuffers);
488 }
489
490 /* check to see if we have an up-to-date buffer.  The buffer must have
491  * previously been obtained by calling buf_Get.
492  *
493  * Make sure we have a callback, and that the dataversion matches.
494  *
495  * Scp must be locked.
496  *
497  * Bufp *may* be locked.
498  */
499 int cm_HaveBuffer(cm_scache_t *scp, cm_buf_t *bufp, int isBufLocked)
500 {
501     int code;
502     if (!cm_HaveCallback(scp))
503         return 0;
504     if ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED))
505         return 1;
506     if (bufp->dataVersion == scp->dataVersion)
507         return 1;
508     if (!isBufLocked) {
509         code = lock_TryMutex(&bufp->mx);
510         if (code == 0) {
511             /* don't have the lock, and can't lock it, then
512              * return failure.
513              */
514             return 0;
515         }
516     }
517
518     /* remember dirty flag for later */
519     code = bufp->flags & CM_BUF_DIRTY;
520
521     /* release lock if we obtained it here */
522     if (!isBufLocked) 
523         lock_ReleaseMutex(&bufp->mx);
524
525     /* if buffer was dirty, buffer is acceptable for use */
526     if (code) 
527         return 1;
528     else 
529         return 0;
530 }
531
532 /* used when deciding whether to do a prefetch or not */
533 long cm_CheckFetchRange(cm_scache_t *scp, osi_hyper_t *startBasep, long length,
534                         cm_user_t *up, cm_req_t *reqp, osi_hyper_t *realBasep)
535 {
536     osi_hyper_t toffset;
537     osi_hyper_t tbase;
538     long code;
539     cm_buf_t *bp;
540     int stop;
541         
542     /* now scan all buffers in the range, looking for any that look like
543      * they need work.
544      */
545     tbase = *startBasep;
546     stop = 0;
547     lock_ObtainMutex(&scp->mx);
548     while(length > 0) {
549         /* get callback so we can do a meaningful dataVersion comparison */
550         code = cm_SyncOp(scp, NULL, up, reqp, 0,
551                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
552         if (code) {
553             scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
554             lock_ReleaseMutex(&scp->mx);
555             return code;
556         }
557                 
558         if (LargeIntegerGreaterThanOrEqualTo(tbase, scp->length)) {
559             /* we're past the end of file */
560             break;
561         }
562
563         bp = buf_Find(scp, &tbase);
564         /* We cheat slightly by not locking the bp mutex. */
565         if (bp) {
566             if ((bp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING)) == 0
567                  && bp->dataVersion != scp->dataVersion)
568                 stop = 1;
569             buf_Release(bp);
570             bp = NULL;
571         }
572         else 
573             stop = 1;
574
575         /* if this buffer is essentially guaranteed to require a fetch,
576          * break out here and return this position.
577          */
578         if (stop) 
579             break;
580                 
581         toffset.LowPart = cm_data.buf_blockSize;
582         toffset.HighPart = 0;
583         tbase = LargeIntegerAdd(toffset, tbase);
584         length -= cm_data.buf_blockSize;
585     }
586         
587     /* if we get here, either everything is fine or stop stopped us at a
588      * particular buffer in the range that definitely needs to be fetched.
589      */
590     if (stop == 0) {
591         /* return non-zero code since realBasep won't be valid */
592         scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
593         code = -1;
594     }   
595     else {
596         /* successfully found a page that will need fetching */
597         *realBasep = tbase;
598         code = 0;
599     }
600     lock_ReleaseMutex(&scp->mx);
601     return code;
602 }
603
604 afs_int32
605 cm_BkgStore(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
606             cm_user_t *userp)
607 {
608     osi_hyper_t toffset;
609     long length;
610     cm_req_t req;
611     long code = 0;
612
613     if (scp->flags & CM_SCACHEFLAG_DELETED) {
614         osi_Log4(afsd_logp, "Skipping BKG store - Deleted scp 0x%p, offset 0x%x:%08x, length 0x%x", scp, p2, p1, p3);
615     } else {
616         cm_InitReq(&req);
617
618         /* Retries will be performed by the BkgDaemon thread if appropriate */
619         req.flags |= CM_REQ_NORETRY;
620
621         toffset.LowPart = p1;
622         toffset.HighPart = p2;
623         length = p3;
624
625         osi_Log4(afsd_logp, "Starting BKG store scp 0x%p, offset 0x%x:%08x, length 0x%x", scp, p2, p1, p3);
626
627         code = cm_BufWrite(scp, &toffset, length, /* flags */ 0, userp, &req);
628
629         osi_Log4(afsd_logp, "Finished BKG store scp 0x%p, offset 0x%x:%08x, code 0x%x", scp, p2, p1, code);
630     }
631
632     lock_ObtainMutex(&scp->mx);
633     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_ASYNCSTORE);
634     lock_ReleaseMutex(&scp->mx);
635
636     return code;
637 }
638
639 /* Called with scp locked */
640 void cm_ClearPrefetchFlag(long code, cm_scache_t *scp, osi_hyper_t *base)
641 {
642     osi_hyper_t thyper;
643
644     if (code == 0) {
645         thyper.LowPart = cm_chunkSize;
646         thyper.HighPart = 0;
647         thyper =  LargeIntegerAdd(*base, thyper);
648         thyper.LowPart &= (-cm_chunkSize);
649         if (LargeIntegerGreaterThan(*base, scp->prefetch.base))
650             scp->prefetch.base = *base;
651         if (LargeIntegerGreaterThan(thyper, scp->prefetch.end))
652             scp->prefetch.end = thyper;
653     }
654     scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
655 }
656
657 /* do the prefetch.  if the prefetch fails, return 0 (success)
658  * because there is no harm done.  */
659 afs_int32
660 cm_BkgPrefetch(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
661                cm_user_t *userp)
662 {
663     long length;
664     osi_hyper_t base;
665     long code;
666     cm_buf_t *bp = NULL;
667     int cpff = 0;                       /* cleared prefetch flag */
668     cm_req_t req;
669
670     cm_InitReq(&req);
671
672     /* Retries will be performed by the BkgDaemon thread if appropriate */
673     req.flags |= CM_REQ_NORETRY;
674         
675     base.LowPart = p1;
676     base.HighPart = p2;
677     length = p3;
678         
679     osi_Log2(afsd_logp, "Starting BKG prefetch scp 0x%p, base 0x%x", scp, p1);
680
681     code = buf_Get(scp, &base, &bp);
682
683     lock_ObtainMutex(&scp->mx);
684
685     if (code || (bp->cmFlags & CM_BUF_CMFETCHING)) {
686         scp->flags &= ~CM_SCACHEFLAG_PREFETCHING;
687         lock_ReleaseMutex(&scp->mx);
688         if (bp)
689             buf_Release(bp);
690         return 0;
691     }
692
693     code = cm_GetBuffer(scp, bp, &cpff, userp, &req);
694     if (!cpff) 
695         cm_ClearPrefetchFlag(code, scp, &base);
696     lock_ReleaseMutex(&scp->mx);
697     buf_Release(bp);
698     return code;
699 }
700
701 /* a read was issued to offsetp, and we have to determine whether we should
702  * do a prefetch.
703  */
704 void cm_ConsiderPrefetch(cm_scache_t *scp, osi_hyper_t *offsetp,
705                          cm_user_t *userp, cm_req_t *reqp)
706 {
707     long code;
708     osi_hyper_t realBase;
709     osi_hyper_t readBase;
710         
711     readBase = *offsetp;
712     /* round up to chunk boundary */
713     readBase.LowPart += (cm_chunkSize-1);
714     readBase.LowPart &= (-cm_chunkSize);
715
716     lock_ObtainMutex(&scp->mx);
717     if ((scp->flags & CM_SCACHEFLAG_PREFETCHING)
718          || LargeIntegerLessThanOrEqualTo(readBase, scp->prefetch.base)) {
719         lock_ReleaseMutex(&scp->mx);
720         return;
721     }
722     scp->flags |= CM_SCACHEFLAG_PREFETCHING;
723
724     /* start the scan at the latter of the end of this read or
725      * the end of the last fetched region.
726      */
727     if (LargeIntegerGreaterThan(scp->prefetch.end, readBase))
728         readBase = scp->prefetch.end;
729
730     lock_ReleaseMutex(&scp->mx);
731
732     code = cm_CheckFetchRange(scp, &readBase, cm_chunkSize, userp, reqp,
733                               &realBase);
734     if (code) 
735         return; /* can't find something to prefetch */
736
737     osi_Log2(afsd_logp, "BKG Prefetch request scp 0x%p, base 0x%x",
738              scp, realBase.LowPart);
739
740     cm_QueueBKGRequest(scp, cm_BkgPrefetch, realBase.LowPart,
741                        realBase.HighPart, cm_chunkSize, 0, userp);
742 }
743
744 /* scp must be locked; temporarily unlocked during processing.
745  * If returns 0, returns buffers held in biop, and with
746  * CM_BUF_CMSTORING set.
747  *
748  * Caller *must* set CM_BUF_WRITING and reset the over.hEvent field if the
749  * buffer is ever unlocked before CM_BUF_DIRTY is cleared.  And if
750  * CM_BUF_WRITING is ever viewed by anyone, then it must be cleared, sleepers
751  * must be woken, and the event must be set when the I/O is done.  All of this
752  * is required so that buf_WaitIO synchronizes properly with the buffer as it
753  * is being written out.
754  */
755 long cm_SetupStoreBIOD(cm_scache_t *scp, osi_hyper_t *inOffsetp, long inSize,
756                        cm_bulkIO_t *biop, cm_user_t *userp, cm_req_t *reqp)
757 {
758     cm_buf_t *bufp;
759     osi_queueData_t *qdp;
760     osi_hyper_t thyper;
761     osi_hyper_t tbase;
762     osi_hyper_t scanStart;              /* where to start scan for dirty pages */
763     osi_hyper_t scanEnd;                /* where to stop scan for dirty pages */
764     osi_hyper_t firstModOffset; /* offset of first modified page in range */
765     long temp;
766     long code;
767     long flags;                 /* flags to cm_SyncOp */
768         
769     /* clear things out */
770     biop->scp = scp;                    /* do not hold; held by caller */
771     biop->offset = *inOffsetp;
772     biop->length = 0;
773     biop->bufListp = NULL;
774     biop->bufListEndp = NULL;
775     biop->reserved = 0;
776
777     /* reserve a chunk's worth of buffers */
778     lock_ReleaseMutex(&scp->mx);
779     buf_ReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
780     lock_ObtainMutex(&scp->mx);
781
782     bufp = NULL;
783     for (temp = 0; temp < inSize; temp += cm_data.buf_blockSize) {
784         thyper.HighPart = 0;
785         thyper.LowPart = temp;
786         tbase = LargeIntegerAdd(*inOffsetp, thyper);
787
788         bufp = buf_Find(scp, &tbase);
789         if (bufp) {
790             /* get buffer mutex and scp mutex safely */
791             lock_ReleaseMutex(&scp->mx);
792             lock_ObtainMutex(&bufp->mx);
793             lock_ObtainMutex(&scp->mx);
794
795             flags = CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_STOREDATA | CM_SCACHESYNC_BUFLOCKED;
796             code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags); 
797             if (code) {
798                 lock_ReleaseMutex(&bufp->mx);
799                 buf_Release(bufp);
800                 buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
801                 return code;
802             }   
803                         
804             /* if the buffer is dirty, we're done */
805             if (bufp->flags & CM_BUF_DIRTY) {
806                 osi_assertx(!(bufp->flags & CM_BUF_WRITING),
807                             "WRITING w/o CMSTORING in SetupStoreBIOD");
808                 bufp->flags |= CM_BUF_WRITING;
809                 break;
810             }
811
812             /* this buffer is clean, so there's no reason to process it */
813             cm_SyncOpDone(scp, bufp, flags);
814             lock_ReleaseMutex(&bufp->mx);
815             buf_Release(bufp);
816             bufp = NULL;
817         }       
818     }
819
820     biop->reserved = 1;
821         
822     /* if we get here, if bufp is null, we didn't find any dirty buffers
823      * that weren't already being stored back, so we just quit now.
824      */
825     if (!bufp) {
826         return 0;
827     }
828
829     /* don't need buffer mutex any more */
830     lock_ReleaseMutex(&bufp->mx);
831         
832     /* put this element in the list */
833     qdp = osi_QDAlloc();
834     osi_SetQData(qdp, bufp);
835     /* don't have to hold bufp, since held by buf_Find above */
836     osi_QAddH((osi_queue_t **) &biop->bufListp,
837               (osi_queue_t **) &biop->bufListEndp,
838               &qdp->q);
839     biop->length = cm_data.buf_blockSize;
840     firstModOffset = bufp->offset;
841     biop->offset = firstModOffset;
842     bufp = NULL;        /* this buffer and reference added to the queue */
843
844     /* compute the window surrounding *inOffsetp of size cm_chunkSize */
845     scanStart = *inOffsetp;
846     scanStart.LowPart &= (-cm_chunkSize);
847     thyper.LowPart = cm_chunkSize;
848     thyper.HighPart = 0;
849     scanEnd = LargeIntegerAdd(scanStart, thyper);
850
851     flags = CM_SCACHESYNC_GETSTATUS
852         | CM_SCACHESYNC_STOREDATA
853         | CM_SCACHESYNC_BUFLOCKED
854         | CM_SCACHESYNC_NOWAIT;
855
856     /* start by looking backwards until scanStart */
857     thyper.HighPart = 0;                /* hyper version of cm_data.buf_blockSize */
858     thyper.LowPart = cm_data.buf_blockSize;
859     tbase = LargeIntegerSubtract(firstModOffset, thyper);
860     while(LargeIntegerGreaterThanOrEqualTo(tbase, scanStart)) {
861         /* see if we can find the buffer */
862         bufp = buf_Find(scp, &tbase);
863         if (!bufp) 
864             break;
865
866         /* try to lock it, and quit if we can't (simplifies locking) */
867         lock_ReleaseMutex(&scp->mx);
868         code = lock_TryMutex(&bufp->mx);
869         lock_ObtainMutex(&scp->mx);
870         if (code == 0) {
871             buf_Release(bufp);
872             bufp = NULL;
873             break;
874         }
875                 
876         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
877         if (code) {
878             lock_ReleaseMutex(&bufp->mx);
879             buf_Release(bufp);
880             bufp = NULL;
881             break;
882         }
883                 
884         if (!(bufp->flags & CM_BUF_DIRTY)) {
885             /* buffer is clean, so we shouldn't add it */
886             cm_SyncOpDone(scp, bufp, flags);
887             lock_ReleaseMutex(&bufp->mx);
888             buf_Release(bufp);
889             bufp = NULL;
890             break;
891         }
892
893         /* don't need buffer mutex any more */
894         lock_ReleaseMutex(&bufp->mx);
895
896         /* we have a dirty buffer ready for storing.  Add it to the tail
897          * of the list, since it immediately precedes all of the disk
898          * addresses we've already collected.
899          */
900         qdp = osi_QDAlloc();
901         osi_SetQData(qdp, bufp);
902         /* no buf_hold necessary, since we have it held from buf_Find */
903         osi_QAddT((osi_queue_t **) &biop->bufListp,
904                   (osi_queue_t **) &biop->bufListEndp,
905                   &qdp->q);
906         bufp = NULL;            /* added to the queue */
907
908         /* update biod info describing the transfer */
909         biop->offset = LargeIntegerSubtract(biop->offset, thyper);
910         biop->length += cm_data.buf_blockSize;
911
912         /* update loop pointer */
913         tbase = LargeIntegerSubtract(tbase, thyper);
914     }   /* while loop looking for pages preceding the one we found */
915
916     /* now, find later dirty, contiguous pages, and add them to the list */
917     thyper.HighPart = 0;                /* hyper version of cm_data.buf_blockSize */
918     thyper.LowPart = cm_data.buf_blockSize;
919     tbase = LargeIntegerAdd(firstModOffset, thyper);
920     while(LargeIntegerLessThan(tbase, scanEnd)) {
921         /* see if we can find the buffer */
922         bufp = buf_Find(scp, &tbase);
923         if (!bufp) 
924             break;
925
926         /* try to lock it, and quit if we can't (simplifies locking) */
927         lock_ReleaseMutex(&scp->mx);
928         code = lock_TryMutex(&bufp->mx);
929         lock_ObtainMutex(&scp->mx);
930         if (code == 0) {
931             buf_Release(bufp);
932             bufp = NULL;
933             break;
934         }
935
936         code = cm_SyncOp(scp, bufp, userp, reqp, 0, flags);
937         if (code) {
938             lock_ReleaseMutex(&bufp->mx);
939             buf_Release(bufp);
940             bufp = NULL;
941             break;
942         }
943                 
944         if (!(bufp->flags & CM_BUF_DIRTY)) {
945             /* buffer is clean, so we shouldn't add it */
946             cm_SyncOpDone(scp, bufp, flags);
947             lock_ReleaseMutex(&bufp->mx);
948             buf_Release(bufp);
949             bufp = NULL;
950             break;
951         }
952
953         /* don't need buffer mutex any more */
954         lock_ReleaseMutex(&bufp->mx);
955
956         /* we have a dirty buffer ready for storing.  Add it to the head
957          * of the list, since it immediately follows all of the disk
958          * addresses we've already collected.
959          */
960         qdp = osi_QDAlloc();
961         osi_SetQData(qdp, bufp);
962         /* no buf_hold necessary, since we have it held from buf_Find */
963         osi_QAddH((osi_queue_t **) &biop->bufListp,
964                   (osi_queue_t **) &biop->bufListEndp,
965                   &qdp->q);
966         bufp = NULL;
967
968         /* update biod info describing the transfer */
969         biop->length += cm_data.buf_blockSize;
970                 
971         /* update loop pointer */
972         tbase = LargeIntegerAdd(tbase, thyper);
973     }   /* while loop looking for pages following the first page we found */
974         
975     /* finally, we're done */
976     return 0;
977 }
978
979 /* scp must be locked; temporarily unlocked during processing.
980  * If returns 0, returns buffers held in biop, and with
981  * CM_BUF_CMFETCHING flags set.
982  * If an error is returned, we don't return any buffers.
983  */
984 long cm_SetupFetchBIOD(cm_scache_t *scp, osi_hyper_t *offsetp,
985                         cm_bulkIO_t *biop, cm_user_t *up, cm_req_t *reqp)
986 {
987     long code;
988     cm_buf_t *tbp;
989     osi_hyper_t toffset;                /* a long long temp variable */
990     osi_hyper_t pageBase;               /* base offset we're looking at */
991     osi_queueData_t *qdp;               /* one temp queue structure */
992     osi_queueData_t *tqdp;              /* another temp queue structure */
993     long collected;                     /* how many bytes have been collected */
994     int isFirst;
995     long flags;
996     osi_hyper_t fileSize;               /* the # of bytes in the file */
997     osi_queueData_t *heldBufListp;      /* we hold all buffers in this list */
998     osi_queueData_t *heldBufListEndp;   /* first one */
999     int reserving;
1000
1001     biop->scp = scp;                    /* do not hold; held by caller */
1002     biop->offset = *offsetp;
1003     /* null out the list of buffers */
1004     biop->bufListp = biop->bufListEndp = NULL;
1005     biop->reserved = 0;
1006
1007     /* first lookup the file's length, so we know when to stop */
1008     code = cm_SyncOp(scp, NULL, up, reqp, 0, 
1009                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1010     if (code) 
1011         return code;
1012         
1013     /* copy out size, since it may change */
1014     fileSize = scp->serverLength;
1015         
1016     lock_ReleaseMutex(&scp->mx);
1017
1018     pageBase = *offsetp;
1019     collected = pageBase.LowPart & (cm_chunkSize - 1);
1020     heldBufListp = NULL;
1021     heldBufListEndp = NULL;
1022
1023     /*
1024      * Obtaining buffers can cause dirty buffers to be recycled, which
1025      * can cause a storeback, so cannot be done while we have buffers
1026      * reserved.
1027      *
1028      * To get around this, we get buffers twice.  Before reserving buffers,
1029      * we obtain and release each one individually.  After reserving
1030      * buffers, we try to obtain them again, but only by lookup, not by
1031      * recycling.  If a buffer has gone away while we were waiting for
1032      * the others, we just use whatever buffers we already have.
1033      *
1034      * On entry to this function, we are already holding a buffer, so we
1035      * can't wait for reservation.  So we call buf_TryReserveBuffers()
1036      * instead.  Not only that, we can't really even call buf_Get(), for
1037      * the same reason.  We can't avoid that, though.  To avoid deadlock
1038      * we allow only one thread to be executing the buf_Get()-buf_Release()
1039      * sequence at a time.
1040      */
1041
1042     // lock_ObtainMutex(&cm_bufGetMutex);
1043     /* first hold all buffers, since we can't hold any locks in buf_Get */
1044     while (1) {
1045         /* stop at chunk boundary */
1046         if (collected >= cm_chunkSize) 
1047             break;
1048                 
1049         /* see if the next page would be past EOF */
1050         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize)) 
1051             break;
1052
1053         code = buf_Get(scp, &pageBase, &tbp);
1054         if (code) {
1055             //lock_ReleaseMutex(&cm_bufGetMutex);
1056             lock_ObtainMutex(&scp->mx);
1057             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1058             return code;
1059         }
1060                 
1061         buf_Release(tbp);
1062
1063         toffset.HighPart = 0;
1064         toffset.LowPart = cm_data.buf_blockSize;
1065         pageBase = LargeIntegerAdd(toffset, pageBase);
1066         collected += cm_data.buf_blockSize;
1067     }
1068
1069     /* reserve a chunk's worth of buffers if possible */
1070     reserving = buf_TryReserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1071
1072     // lock_ReleaseMutex(&cm_bufGetMutex);
1073
1074     pageBase = *offsetp;
1075     collected = pageBase.LowPart & (cm_chunkSize - 1);
1076
1077     /* now hold all buffers, if they are still there */
1078     while (1) {
1079         /* stop at chunk boundary */
1080         if (collected >= cm_chunkSize) 
1081             break;
1082                 
1083         /* see if the next page would be past EOF */
1084         if (LargeIntegerGreaterThanOrEqualTo(pageBase, fileSize)) 
1085             break;
1086
1087         tbp = buf_Find(scp, &pageBase);
1088         if (!tbp) 
1089             break;
1090
1091         /* add the buffer to the list */
1092         qdp = osi_QDAlloc();
1093         osi_SetQData(qdp, tbp);
1094         osi_QAddH((osi_queue_t **)&heldBufListp, 
1095                   (osi_queue_t **)&heldBufListEndp, 
1096                   &qdp->q);
1097         /* leave tbp held (from buf_Get) */
1098
1099         if (!reserving) 
1100             break;
1101
1102         collected += cm_data.buf_blockSize;
1103         toffset.HighPart = 0;
1104         toffset.LowPart = cm_data.buf_blockSize;
1105         pageBase = LargeIntegerAdd(toffset, pageBase);
1106     }
1107
1108     /* look at each buffer, adding it into the list if it looks idle and
1109      * filled with old data.  One special case: wait for idle if it is the
1110      * first buffer since we really need that one for our caller to make
1111      * any progress.
1112      */
1113     isFirst = 1;
1114     collected = 0;              /* now count how many we'll really use */
1115     for (tqdp = heldBufListEndp;
1116         tqdp;
1117           tqdp = (osi_queueData_t *) osi_QPrev(&tqdp->q)) {
1118         /* get a ptr to the held buffer */
1119         tbp = osi_GetQData(tqdp);
1120         pageBase = tbp->offset;
1121
1122         /* now lock the buffer lock */
1123         lock_ObtainMutex(&tbp->mx);
1124         lock_ObtainMutex(&scp->mx);
1125
1126         /* don't bother fetching over data that is already current */
1127         if (tbp->dataVersion == scp->dataVersion) {
1128             /* we don't need this buffer, since it is current */
1129             lock_ReleaseMutex(&scp->mx);
1130             lock_ReleaseMutex(&tbp->mx);
1131             break;
1132         }
1133
1134         flags = CM_SCACHESYNC_FETCHDATA | CM_SCACHESYNC_BUFLOCKED;
1135         if (!isFirst) 
1136             flags |= CM_SCACHESYNC_NOWAIT;
1137
1138         /* wait for the buffer to serialize, if required.  Doesn't
1139          * release the scp or buffer lock(s) if NOWAIT is specified.
1140          */
1141         code = cm_SyncOp(scp, tbp, up, reqp, 0, flags);
1142         if (code) {
1143             lock_ReleaseMutex(&scp->mx);
1144             lock_ReleaseMutex(&tbp->mx);
1145             break;
1146         }
1147                 
1148         /* don't fetch over dirty buffers */
1149         if (tbp->flags & CM_BUF_DIRTY) {
1150             cm_SyncOpDone(scp, tbp, flags);
1151             lock_ReleaseMutex(&scp->mx);
1152             lock_ReleaseMutex(&tbp->mx);
1153             break;
1154         }
1155
1156         /* Release locks */
1157         lock_ReleaseMutex(&scp->mx);
1158         lock_ReleaseMutex(&tbp->mx);
1159
1160         /* add the buffer to the list */
1161         qdp = osi_QDAlloc();
1162         osi_SetQData(qdp, tbp);
1163         osi_QAddH((osi_queue_t **)&biop->bufListp, 
1164                   (osi_queue_t **)&biop->bufListEndp, 
1165                   &qdp->q);
1166         buf_Hold(tbp);
1167
1168         /* from now on, a failure just stops our collection process, but
1169          * we still do the I/O to whatever we've already managed to collect.
1170          */
1171         isFirst = 0;
1172         collected += cm_data.buf_blockSize;
1173     }
1174         
1175     /* now, we've held in biop->bufListp all the buffer's we're really
1176      * interested in.  We also have holds left from heldBufListp, and we
1177      * now release those holds on the buffers.
1178      */
1179     for (qdp = heldBufListp; qdp; qdp = tqdp) {
1180         tqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1181         tbp = osi_GetQData(qdp);
1182         osi_QRemoveHT((osi_queue_t **) &heldBufListp,
1183                       (osi_queue_t **) &heldBufListEndp,
1184                       &qdp->q);
1185         osi_QDFree(qdp);
1186         buf_Release(tbp);
1187     }
1188
1189     /* Caller expects this */
1190     lock_ObtainMutex(&scp->mx);
1191  
1192     /* if we got a failure setting up the first buffer, then we don't have
1193      * any side effects yet, and we also have failed an operation that the
1194      * caller requires to make any progress.  Give up now.
1195      */
1196     if (code && isFirst) {
1197         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1198         return code;
1199     }
1200         
1201     /* otherwise, we're still OK, and should just return the I/O setup we've
1202      * got.
1203      */
1204     biop->length = collected;
1205     biop->reserved = reserving;
1206     return 0;
1207 }
1208
1209 /* release a bulk I/O structure that was setup by cm_SetupFetchBIOD or by
1210  * cm_SetupStoreBIOD
1211  */
1212 void cm_ReleaseBIOD(cm_bulkIO_t *biop, int isStore, int failed)
1213 {
1214     cm_scache_t *scp;           /* do not release; not held in biop */
1215     cm_buf_t *bufp;
1216     osi_queueData_t *qdp;
1217     osi_queueData_t *nqdp;
1218     int flags;
1219
1220     /* Give back reserved buffers */
1221     if (biop->reserved)
1222         buf_UnreserveBuffers(cm_chunkSize / cm_data.buf_blockSize);
1223         
1224     if (isStore)
1225         flags = CM_SCACHESYNC_STOREDATA;
1226     else
1227         flags = CM_SCACHESYNC_FETCHDATA;
1228
1229     scp = biop->scp;
1230     if (biop->bufListp) {
1231         for(qdp = biop->bufListp; qdp; qdp = nqdp) {
1232             /* lookup next guy first, since we're going to free this one */
1233             nqdp = (osi_queueData_t *) osi_QNext(&qdp->q);
1234                 
1235             /* extract buffer and free queue data */
1236             bufp = osi_GetQData(qdp);
1237             osi_QRemoveHT((osi_queue_t **) &biop->bufListp,
1238                            (osi_queue_t **) &biop->bufListEndp,
1239                            &qdp->q);
1240             osi_QDFree(qdp);
1241
1242             /* now, mark I/O as done, unlock the buffer and release it */
1243             lock_ObtainMutex(&bufp->mx);
1244             lock_ObtainMutex(&scp->mx);
1245             cm_SyncOpDone(scp, bufp, flags);
1246                 
1247             /* turn off writing and wakeup users */
1248             if (isStore) {
1249                 if (bufp->flags & CM_BUF_WAITING) {
1250                     osi_Log2(afsd_logp, "cm_ReleaseBIOD Waking [scp 0x%p] bp 0x%p", scp, bufp);
1251                     osi_Wakeup((LONG_PTR) bufp);
1252                 }
1253                 if (failed)
1254                     bufp->flags &= ~CM_BUF_WRITING;
1255                 else
1256                     bufp->flags &= ~(CM_BUF_WRITING | CM_BUF_DIRTY);
1257             }
1258
1259             lock_ReleaseMutex(&scp->mx);
1260             lock_ReleaseMutex(&bufp->mx);
1261             buf_Release(bufp);
1262             bufp = NULL;
1263         }
1264     } else {
1265         lock_ObtainMutex(&scp->mx);
1266         cm_SyncOpDone(scp, NULL, flags);
1267         lock_ReleaseMutex(&scp->mx);
1268     }
1269
1270     /* clean things out */
1271     biop->bufListp = NULL;
1272     biop->bufListEndp = NULL;
1273 }   
1274
1275 /* Fetch a buffer.  Called with scp locked.
1276  * The scp is locked on return.
1277  */
1278 long cm_GetBuffer(cm_scache_t *scp, cm_buf_t *bufp, int *cpffp, cm_user_t *up,
1279                   cm_req_t *reqp)
1280 {
1281     long code;
1282     afs_int32 nbytes;                   /* bytes in transfer */
1283     afs_int32 nbytes_hi = 0;            /* high-order 32 bits of bytes in transfer */
1284     afs_int64 length_found = 0;
1285     long rbytes;                        /* bytes in rx_Read call */
1286     long temp;
1287     AFSFetchStatus afsStatus;
1288     AFSCallBack callback;
1289     AFSVolSync volSync;
1290     char *bufferp;
1291     cm_buf_t *tbufp;                    /* buf we're filling */
1292     osi_queueData_t *qdp;               /* q element we're scanning */
1293     AFSFid tfid;
1294     struct rx_call *callp;
1295     struct rx_connection *rxconnp;
1296     cm_bulkIO_t biod;           /* bulk IO descriptor */
1297     cm_conn_t *connp;
1298     int getroot;
1299     long t1, t2;
1300     int require_64bit_ops = 0;
1301
1302     /* now, the buffer may or may not be filled with good data (buf_GetNew
1303      * drops lots of locks, and may indeed return a properly initialized
1304      * buffer, although more likely it will just return a new, empty, buffer.
1305      */
1306
1307 #ifdef AFS_FREELANCE_CLIENT
1308
1309     // yj: if they're trying to get the /afs directory, we need to
1310     // handle it differently, since it's local rather than on any
1311     // server
1312
1313     getroot = (scp==cm_data.rootSCachep);
1314     if (getroot)
1315         osi_Log1(afsd_logp,"GetBuffer returns cm_data.rootSCachep=%x",cm_data.rootSCachep);
1316 #endif
1317
1318     cm_AFSFidFromFid(&tfid, &scp->fid);
1319
1320     code = cm_SetupFetchBIOD(scp, &bufp->offset, &biod, up, reqp);
1321     if (code) {
1322         /* couldn't even get the first page setup properly */
1323         osi_Log1(afsd_logp, "SetupFetchBIOD failure code %d", code);
1324         return code;
1325     }
1326
1327     /* once we get here, we have the callback in place, we know that no one
1328      * is fetching the data now.  Check one last time that we still have
1329      * the wrong data, and then fetch it if we're still wrong.
1330      *
1331      * We can lose a race condition and end up with biod.length zero, in
1332      * which case we just retry.
1333      */
1334     if (bufp->dataVersion == scp->dataVersion || biod.length == 0) {
1335         osi_Log3(afsd_logp, "Bad DVs %d, %d or length 0x%x",
1336                  bufp->dataVersion, scp->dataVersion, biod.length);
1337         if ((bufp->dataVersion == -1
1338              || bufp->dataVersion < scp->dataVersion)
1339              && LargeIntegerGreaterThanOrEqualTo(bufp->offset,
1340                                                  scp->serverLength)) {
1341             if (bufp->dataVersion == -1)
1342                 memset(bufp->datap, 0, cm_data.buf_blockSize);
1343             bufp->dataVersion = scp->dataVersion;
1344         }
1345         lock_ReleaseMutex(&scp->mx);
1346         cm_ReleaseBIOD(&biod, 0, 0);
1347         lock_ObtainMutex(&scp->mx);
1348         return 0;
1349     }
1350
1351     lock_ReleaseMutex(&scp->mx);
1352
1353     if (LargeIntegerGreaterThan(LargeIntegerAdd(biod.offset,
1354                                                 ConvertLongToLargeInteger(biod.length)),
1355                                 ConvertLongToLargeInteger(LONG_MAX))) {
1356         require_64bit_ops = 1;
1357     }
1358
1359 #ifdef DISKCACHE95
1360     DPRINTF("cm_GetBuffer: fetching data scpDV=%d bufDV=%d scp=%x bp=%x dcp=%x\n",
1361             scp->dataVersion, bufp->dataVersion, scp, bufp, bufp->dcp);
1362 #endif /* DISKCACHE95 */
1363
1364 #ifdef AFS_FREELANCE_CLIENT
1365
1366     // yj code
1367     // if getroot then we don't need to make any calls
1368     // just return fake data
1369         
1370     if (cm_freelanceEnabled && getroot) {
1371         // setup the fake status                        
1372         afsStatus.InterfaceVersion = 0x1;
1373         afsStatus.FileType = 0x2;
1374         afsStatus.LinkCount = scp->linkCount;
1375         afsStatus.Length = cm_fakeDirSize;
1376         afsStatus.DataVersion = cm_data.fakeDirVersion;
1377         afsStatus.Author = 0x1;
1378         afsStatus.Owner = 0x0;
1379         afsStatus.CallerAccess = 0x9;
1380         afsStatus.AnonymousAccess = 0x9;
1381         afsStatus.UnixModeBits = 0x1ff;
1382         afsStatus.ParentVnode = 0x1;
1383         afsStatus.ParentUnique = 0x1;
1384         afsStatus.ResidencyMask = 0;
1385         afsStatus.ClientModTime = (afs_uint32)FakeFreelanceModTime;
1386         afsStatus.ServerModTime = (afs_uint32)FakeFreelanceModTime;
1387         afsStatus.Group = 0;
1388         afsStatus.SyncCounter = 0;
1389         afsStatus.dataVersionHigh = 0;
1390         afsStatus.lockCount = 0;
1391         afsStatus.Length_hi = 0;
1392         afsStatus.errorCode = 0;
1393         
1394         // once we're done setting up the status info,
1395         // we just fill the buffer pages with fakedata
1396         // from cm_FakeRootDir. Extra pages are set to
1397         // 0. 
1398                 
1399         lock_ObtainMutex(&cm_Freelance_Lock);
1400         t1 = bufp->offset.LowPart;
1401         qdp = biod.bufListEndp;
1402         while (qdp) {
1403             tbufp = osi_GetQData(qdp);
1404             bufferp=tbufp->datap;
1405             memset(bufferp, 0, cm_data.buf_blockSize);
1406             t2 = cm_fakeDirSize - t1;
1407             if (t2>cm_data.buf_blockSize) t2=cm_data.buf_blockSize;
1408             if (t2 > 0) {
1409                 memcpy(bufferp, cm_FakeRootDir+t1, t2);
1410             } else {
1411                 t2 = 0;
1412             }
1413             t1+=t2;
1414             qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1415
1416         }
1417         lock_ReleaseMutex(&cm_Freelance_Lock);
1418         
1419         // once we're done, we skip over the part of the
1420         // code that does the ACTUAL fetching of data for
1421         // real files
1422
1423         goto fetchingcompleted;
1424     }
1425
1426 #endif /* AFS_FREELANCE_CLIENT */
1427
1428         /* now make the call */
1429     do {
1430         code = cm_ConnFromFID(&scp->fid, up, reqp, &connp);
1431         if (code) 
1432             continue;
1433
1434         rxconnp = cm_GetRxConn(connp);
1435         callp = rx_NewCall(rxconnp);
1436         rx_PutConnection(rxconnp);
1437
1438 #ifdef AFS_LARGEFILES
1439         nbytes = nbytes_hi = 0;
1440
1441         if (SERVERHAS64BIT(connp)) {
1442             osi_Log4(afsd_logp, "CALL FetchData64 scp 0x%p, off 0x%x:%08x, size 0x%x",
1443                      scp, biod.offset.HighPart, biod.offset.LowPart, biod.length);
1444
1445             code = StartRXAFS_FetchData64(callp, &tfid, biod.offset.QuadPart, biod.length);
1446
1447             if (code == 0) {
1448                 temp = rx_Read(callp, (char *) &nbytes_hi, sizeof(afs_int32));
1449                 if (temp == sizeof(afs_int32)) {
1450                     nbytes_hi = ntohl(nbytes_hi);
1451                 } else {
1452                     nbytes_hi = 0;
1453                     code = callp->error;
1454                     rx_EndCall(callp, code);
1455                     callp = NULL;
1456                 }
1457             }
1458         }
1459
1460         if (code == RXGEN_OPCODE || !SERVERHAS64BIT(connp)) {
1461             if (require_64bit_ops) {
1462                 osi_Log0(afsd_logp, "Skipping FetchData.  Operation requires FetchData64");
1463                 code = CM_ERROR_TOOBIG;
1464             } else {
1465                 if (!callp) {
1466                     rxconnp = cm_GetRxConn(connp);
1467                     callp = rx_NewCall(rxconnp);
1468                     rx_PutConnection(rxconnp);
1469                 }
1470
1471                 osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
1472                          scp, biod.offset.LowPart, biod.length);
1473
1474                 code = StartRXAFS_FetchData(callp, &tfid, biod.offset.LowPart,
1475                                             biod.length);
1476
1477                 SET_SERVERHASNO64BIT(connp);
1478             }
1479         }
1480
1481         if (code == 0) {
1482             temp  = rx_Read(callp, (char *)&nbytes, sizeof(afs_int32));
1483             if (temp == sizeof(afs_int32)) {
1484                 nbytes = ntohl(nbytes);
1485                 FillInt64(length_found, nbytes_hi, nbytes);
1486                 if (length_found > biod.length) 
1487                     code = (callp->error < 0) ? callp->error : -1;
1488             } else {
1489                 code = (callp->error < 0) ? callp->error : -1;
1490             }
1491         }
1492         /* for the moment, nbytes_hi will always be 0 if code == 0
1493            because biod.length is a 32-bit quantity. */
1494 #else
1495         osi_Log3(afsd_logp, "CALL FetchData scp 0x%p, off 0x%x, size 0x%x",
1496                  scp, biod.offset.LowPart, biod.length);
1497
1498         code = StartRXAFS_FetchData(callp, &tfid, biod.offset.LowPart,
1499                                     biod.length);
1500
1501         /* now copy the data out of the pipe and put it in the buffer */
1502         if (code == 0) {
1503             temp  = rx_Read(callp, (char *)&nbytes, sizeof(afs_int32));
1504             if (temp == sizeof(afs_int32)) {
1505                 nbytes = ntohl(nbytes);
1506                 if (nbytes > biod.length) 
1507                     code = (callp->error < 0) ? callp->error : -1;
1508             }
1509             else 
1510                 code = (callp->error < 0) ? callp->error : -1;
1511         }
1512 #endif
1513
1514         if (code == 0) {
1515             qdp = biod.bufListEndp;
1516             if (qdp) {
1517                 tbufp = osi_GetQData(qdp);
1518                 bufferp = tbufp->datap;
1519             }
1520             else 
1521                 bufferp = NULL;
1522             /* fill nbytes of data from the pipe into the pages.
1523              * When we stop, qdp will point at the last page we're
1524              * dealing with, and bufferp will tell us where we
1525              * stopped.  We'll need this info below when we clear
1526              * the remainder of the last page out (and potentially
1527              * clear later pages out, if we fetch past EOF).
1528              */
1529             while (nbytes > 0) {
1530                 /* assert that there are still more buffers;
1531                  * our check above for nbytes being less than
1532                  * biod.length should ensure this.
1533                  */
1534                 osi_assert(bufferp != NULL);
1535
1536                 /* read rbytes of data */
1537                 rbytes = (nbytes > cm_data.buf_blockSize? cm_data.buf_blockSize : nbytes);
1538                 temp = rx_Read(callp, bufferp, rbytes);
1539                 if (temp < rbytes) {
1540                     code = (callp->error < 0) ? callp->error : -1;
1541                     break;
1542                 }
1543
1544                 /* allow read-while-fetching.
1545                  * if this is the last buffer, clear the
1546                  * PREFETCHING flag, so the reader waiting for
1547                  * this buffer will start a prefetch.
1548                  */
1549                 tbufp->cmFlags |= CM_BUF_CMFULLYFETCHED;
1550                 lock_ObtainMutex(&scp->mx);
1551                 if (scp->flags & CM_SCACHEFLAG_WAITING) {
1552                     osi_Log1(afsd_logp, "CM GetBuffer Waking scp 0x%p", scp);
1553                     osi_Wakeup((LONG_PTR) &scp->flags);
1554                 }
1555                 if (cpffp && !*cpffp && !osi_QPrev(&qdp->q)) {
1556                     *cpffp = 1;
1557                     cm_ClearPrefetchFlag(0, scp, &biod.offset);
1558                 }
1559                 lock_ReleaseMutex(&scp->mx);
1560
1561                 /* and adjust counters */
1562                 nbytes -= temp;
1563
1564                 /* and move to the next buffer */
1565                 if (nbytes != 0) {
1566                     qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1567                     if (qdp) {
1568                         tbufp = osi_GetQData(qdp);
1569                         bufferp = tbufp->datap;
1570                     }
1571                     else 
1572                         bufferp = NULL;
1573                 } else 
1574                     bufferp += temp;
1575             }
1576
1577             /* zero out remainder of last pages, in case we are
1578              * fetching past EOF.  We were fetching an integral #
1579              * of pages, but stopped, potentially in the middle of
1580              * a page.  Zero the remainder of that page, and then
1581              * all of the rest of the pages.
1582              */
1583             /* bytes fetched */
1584             osi_assert((bufferp - tbufp->datap) < LONG_MAX);
1585             rbytes = (long) (bufferp - tbufp->datap);
1586
1587             /* bytes left to zero */
1588             rbytes = cm_data.buf_blockSize - rbytes;
1589             while(qdp) {
1590                 if (rbytes != 0)
1591                     memset(bufferp, 0, rbytes);
1592                 qdp = (osi_queueData_t *) osi_QPrev(&qdp->q);
1593                 if (qdp == NULL) 
1594                     break;
1595                 tbufp = osi_GetQData(qdp);
1596                 bufferp = tbufp->datap;
1597                 /* bytes to clear in this page */
1598                 rbytes = cm_data.buf_blockSize;
1599             }   
1600         }
1601
1602         if (code == 0) {
1603             if (SERVERHAS64BIT(connp))
1604                 code = EndRXAFS_FetchData64(callp, &afsStatus, &callback, &volSync);
1605             else
1606                 code = EndRXAFS_FetchData(callp, &afsStatus, &callback, &volSync);
1607         } else {
1608             if (SERVERHAS64BIT(connp))
1609                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData64 skipped due to error %d", code);
1610             else
1611                 osi_Log1(afsd_logp, "CALL EndRXAFS_FetchData skipped due to error %d", code);
1612         }
1613
1614         if (callp)
1615             code = rx_EndCall(callp, code);
1616
1617         if (code == RXKADUNKNOWNKEY)
1618             osi_Log0(afsd_logp, "CALL EndCall returns RXKADUNKNOWNKEY");
1619
1620         osi_Log0(afsd_logp, "CALL FetchData DONE");
1621
1622     } while (cm_Analyze(connp, up, reqp, &scp->fid, &volSync, NULL, NULL, code));
1623
1624   fetchingcompleted:
1625     code = cm_MapRPCError(code, reqp);
1626
1627     lock_ObtainMutex(&scp->mx);
1628     
1629     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_FETCHSTATUS);
1630
1631     /* we know that no one else has changed the buffer, since we still have
1632      * the fetching flag on the buffers, and we have the scp locked again.
1633      * Copy in the version # into the buffer if we got code 0 back from the
1634      * read.
1635      */
1636     if (code == 0) {
1637         for(qdp = biod.bufListp;
1638              qdp;
1639              qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1640             tbufp = osi_GetQData(qdp);
1641             tbufp->dataVersion = afsStatus.DataVersion;
1642
1643 #ifdef DISKCACHE95
1644             /* write buffer out to disk cache */
1645             diskcache_Update(tbufp->dcp, tbufp->datap, cm_data.buf_blockSize,
1646                               tbufp->dataVersion);
1647 #endif /* DISKCACHE95 */
1648         }
1649     }
1650
1651     /* release scatter/gather I/O structure (buffers, locks) */
1652     lock_ReleaseMutex(&scp->mx);
1653     cm_ReleaseBIOD(&biod, 0, code);
1654     lock_ObtainMutex(&scp->mx);
1655
1656     if (code == 0) 
1657         cm_MergeStatus(NULL, scp, &afsStatus, &volSync, up, 0);
1658     
1659     return code;
1660 }