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