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