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