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