windows-scache-ref-leak-20061008
[openafs.git] / src / WINNT / afsd / cm_scache.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 #include <malloc.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <osi.h>
20
21 #include "afsd.h"
22
23 /*extern void afsi_log(char *pattern, ...);*/
24
25 extern osi_hyper_t hzero;
26
27 /* File locks */
28 osi_queue_t *cm_allFileLocks;
29 osi_queue_t *cm_freeFileLocks;
30 unsigned long cm_lockRefreshCycle;
31
32 /* lock for globals */
33 osi_rwlock_t cm_scacheLock;
34
35 /* Dummy scache entry for use with pioctl fids */
36 cm_scache_t cm_fakeSCache;
37
38 #ifdef AFS_FREELANCE_CLIENT
39 extern osi_mutex_t cm_Freelance_Lock;
40 #endif
41
42 /* must be called with cm_scacheLock write-locked! */
43 void cm_AdjustLRU(cm_scache_t *scp)
44 {
45     if (scp == cm_data.scacheLRULastp)
46         cm_data.scacheLRULastp = (cm_scache_t *) osi_QPrev(&scp->q);
47     osi_QRemoveHT((osi_queue_t **) &cm_data.scacheLRUFirstp, (osi_queue_t **) &cm_data.scacheLRULastp, &scp->q);
48     osi_QAdd((osi_queue_t **) &cm_data.scacheLRUFirstp, &scp->q);
49     if (!cm_data.scacheLRULastp) 
50         cm_data.scacheLRULastp = scp;
51 }
52
53 /* call with scache write-locked and mutex held */
54 void cm_RemoveSCacheFromHashTable(cm_scache_t *scp)
55 {
56     cm_scache_t **lscpp;
57     cm_scache_t *tscp;
58     int i;
59         
60     if (scp->flags & CM_SCACHEFLAG_INHASH) {
61         /* hash it out first */
62         i = CM_SCACHE_HASH(&scp->fid);
63         for (lscpp = &cm_data.hashTablep[i], tscp = cm_data.hashTablep[i];
64              tscp;
65              lscpp = &tscp->nextp, tscp = tscp->nextp) {
66             if (tscp == scp) {
67                 *lscpp = scp->nextp;
68                 scp->flags &= ~CM_SCACHEFLAG_INHASH;
69                 break;
70             }
71         }
72     }
73 }
74
75 /* called with cm_scacheLock write-locked; recycles an existing scp. 
76  *
77  * this function ignores all of the locking hierarchy.  
78  */
79 long cm_RecycleSCache(cm_scache_t *scp, afs_int32 flags)
80 {
81     if (scp->refCount != 0) {
82         return -1;
83     }
84
85     if (scp->flags & CM_SCACHEFLAG_SMB_FID) {
86         osi_Log1(afsd_logp,"cm_RecycleSCache CM_SCACHEFLAG_SMB_FID detected scp 0x%p", scp);
87 #ifdef DEBUG
88         osi_panic("cm_RecycleSCache CM_SCACHEFLAG_SMB_FID detected",__FILE__,__LINE__);
89 #endif
90         return -1;
91     }
92
93     cm_RemoveSCacheFromHashTable(scp);
94
95 #if 0
96     if (flags & CM_SCACHE_RECYCLEFLAG_DESTROY_BUFFERS) {
97         osi_queueData_t *qdp;
98         cm_buf_t *bufp;
99
100         while(qdp = scp->bufWritesp) {
101             bufp = osi_GetQData(qdp);
102             osi_QRemove((osi_queue_t **) &scp->bufWritesp, &qdp->q);
103             osi_QDFree(qdp);
104             if (bufp) {
105                 lock_ObtainMutex(&bufp->mx);
106                 bufp->cmFlags &= ~CM_BUF_CMSTORING;
107                 bufp->flags &= ~CM_BUF_DIRTY;
108                 bufp->flags |= CM_BUF_ERROR;
109                 bufp->error = VNOVNODE;
110                 bufp->dataVersion = -1; /* bad */
111                 bufp->dirtyCounter++;
112                 if (bufp->flags & CM_BUF_WAITING) {
113                     osi_Log2(afsd_logp, "CM RecycleSCache Waking [scp 0x%x] bufp 0x%x", scp, bufp);
114                     osi_Wakeup((long) &bufp);
115                 }
116                 lock_ReleaseMutex(&bufp->mx);
117                 buf_Release(bufp);
118             }
119         }
120         while(qdp = scp->bufReadsp) {
121             bufp = osi_GetQData(qdp);
122             osi_QRemove((osi_queue_t **) &scp->bufReadsp, &qdp->q);
123             osi_QDFree(qdp);
124             if (bufp) {
125                 lock_ObtainMutex(&bufp->mx);
126                 bufp->cmFlags &= ~CM_BUF_CMFETCHING;
127                 bufp->flags &= ~CM_BUF_DIRTY;
128                 bufp->flags |= CM_BUF_ERROR;
129                 bufp->error = VNOVNODE;
130                 bufp->dataVersion = -1; /* bad */
131                 bufp->dirtyCounter++;
132                 if (bufp->flags & CM_BUF_WAITING) {
133                     osi_Log2(afsd_logp, "CM RecycleSCache Waking [scp 0x%x] bufp 0x%x", scp, bufp);
134                     osi_Wakeup((long) &bufp);
135                 }
136                 lock_ReleaseMutex(&bufp->mx);
137                 buf_Release(bufp);
138             }
139         }
140         buf_CleanDirtyBuffers(scp); 
141     } else {
142         /* look for things that shouldn't still be set */
143         osi_assert(scp->bufWritesp == NULL);
144         osi_assert(scp->bufReadsp == NULL);
145     }
146 #endif
147
148     /* invalidate so next merge works fine;
149      * also initialize some flags */
150     scp->flags &= ~(CM_SCACHEFLAG_STATD
151                      | CM_SCACHEFLAG_DELETED
152                      | CM_SCACHEFLAG_RO
153                      | CM_SCACHEFLAG_PURERO
154                      | CM_SCACHEFLAG_OVERQUOTA
155                      | CM_SCACHEFLAG_OUTOFSPACE
156                      | CM_SCACHEFLAG_EACCESS);
157     scp->serverModTime = 0;
158     scp->dataVersion = 0;
159     scp->bulkStatProgress = hzero;
160     scp->waitCount = 0;
161
162     scp->fid.vnode = 0;
163     scp->fid.volume = 0;
164     scp->fid.unique = 0;
165     scp->fid.cell = 0;
166
167     /* discard callback */
168     if (scp->cbServerp) {
169         cm_PutServer(scp->cbServerp);
170         scp->cbServerp = NULL;
171     }
172     scp->cbExpires = 0;
173
174     /* remove from dnlc */
175     cm_dnlcPurgedp(scp);
176     cm_dnlcPurgevp(scp);
177
178     /* discard cached status; if non-zero, Close
179      * tried to store this to server but failed */
180     scp->mask = 0;
181
182     /* drop held volume ref */
183     if (scp->volp) {
184         cm_PutVolume(scp->volp);
185         scp->volp = NULL;
186     }
187
188     /* discard symlink info */
189     scp->mountPointStringp[0] = 0;
190     memset(&scp->mountRootFid, 0, sizeof(cm_fid_t));
191     memset(&scp->dotdotFid, 0, sizeof(cm_fid_t));
192
193     /* reset locking info */
194     scp->fileLocksH = NULL;
195     scp->fileLocksT = NULL;
196     scp->serverLock = (-1);
197     scp->exclusiveLocks = 0;
198     scp->sharedLocks = 0;
199
200     /* not locked, but there can be no references to this guy
201      * while we hold the global refcount lock.
202      */
203     cm_FreeAllACLEnts(scp);
204     return 0;
205 }
206
207
208 /* called with cm_scacheLock write-locked; find a vnode to recycle.
209  * Can allocate a new one if desperate, or if below quota (cm_data.maxSCaches).
210  */
211 cm_scache_t *cm_GetNewSCache(void)
212 {
213     cm_scache_t *scp;
214     int retry = 0;
215
216 #if 0
217     /* first pass - look for deleted objects */
218     for ( scp = cm_data.scacheLRULastp;
219           scp;
220           scp = (cm_scache_t *) osi_QPrev(&scp->q)) 
221     {
222         osi_assert(scp >= cm_data.scacheBaseAddress && scp < (cm_scache_t *)cm_data.hashTablep);
223
224         if (scp->refCount == 0) {
225             if (scp->flags & CM_SCACHEFLAG_DELETED) {
226                 osi_Log1(afsd_logp, "GetNewSCache attempting to recycle deleted scp 0x%x", scp);
227                 if (!cm_RecycleSCache(scp, CM_SCACHE_RECYCLEFLAG_DESTROY_BUFFERS)) {
228
229                     /* we found an entry, so return it */
230                     /* now remove from the LRU queue and put it back at the
231                      * head of the LRU queue.
232                      */
233                     cm_AdjustLRU(scp);
234
235                     /* and we're done */
236                     return scp;
237                 } 
238                 osi_Log1(afsd_logp, "GetNewSCache recycled failed scp 0x%x", scp);
239             } else if (!(scp->flags & CM_SCACHEFLAG_INHASH)) {
240                 /* we found an entry, so return it */
241                 /* now remove from the LRU queue and put it back at the
242                 * head of the LRU queue.
243                 */
244                 cm_AdjustLRU(scp);
245
246                 /* and we're done */
247                 return scp;
248             }
249         }       
250     }   
251     osi_Log0(afsd_logp, "GetNewSCache no deleted or recycled entries available for reuse");
252 #endif 
253
254     if (cm_data.currentSCaches >= cm_data.maxSCaches) {
255         /* There were no deleted scache objects that we could use.  Try to find
256          * one that simply hasn't been used in a while.
257          */
258             for ( scp = cm_data.scacheLRULastp;
259                   scp;
260                   scp = (cm_scache_t *) osi_QPrev(&scp->q)) 
261             {
262                 /* It is possible for the refCount to be zero and for there still
263                  * to be outstanding dirty buffers.  If there are dirty buffers,
264                  * we must not recycle the scp. */
265                 if (scp->refCount == 0 && scp->bufReadsp == NULL && scp->bufWritesp == NULL) {
266                     if (!buf_DirtyBuffersExist(&scp->fid)) {
267                         if (!cm_RecycleSCache(scp, 0)) {
268                             /* we found an entry, so return it */
269                             /* now remove from the LRU queue and put it back at the
270                              * head of the LRU queue.
271                              */
272                             cm_AdjustLRU(scp);
273
274                             /* and we're done */
275                             return scp;
276                         }
277                     } else {
278                         osi_Log1(afsd_logp,"GetNewSCache dirty buffers exist scp 0x%x", scp);
279                     }
280                 }       
281             }
282             osi_Log1(afsd_logp, "GetNewSCache all scache entries in use (retry = %d)", retry);
283             
284                 return NULL;
285     }
286         
287     /* if we get here, we should allocate a new scache entry.  We either are below
288      * quota or we have a leak and need to allocate a new one to avoid panicing.
289      */
290     scp = cm_data.scacheBaseAddress + cm_data.currentSCaches;
291     osi_assert(scp >= cm_data.scacheBaseAddress && scp < (cm_scache_t *)cm_data.hashTablep);
292     memset(scp, 0, sizeof(cm_scache_t));
293     scp->magic = CM_SCACHE_MAGIC;
294     lock_InitializeMutex(&scp->mx, "cm_scache_t mutex");
295     lock_InitializeRWLock(&scp->bufCreateLock, "cm_scache_t bufCreateLock");
296     scp->serverLock = -1;
297
298     /* and put it in the LRU queue */
299     osi_QAdd((osi_queue_t **) &cm_data.scacheLRUFirstp, &scp->q);
300     if (!cm_data.scacheLRULastp) 
301         cm_data.scacheLRULastp = scp;
302     cm_data.currentSCaches++;
303     cm_dnlcPurgedp(scp); /* make doubly sure that this is not in dnlc */
304     cm_dnlcPurgevp(scp); 
305     return scp;
306 }       
307
308 /* like strcmp, only for fids */
309 int cm_FidCmp(cm_fid_t *ap, cm_fid_t *bp)
310 {
311     if (ap->vnode != bp->vnode) 
312         return 1;
313     if (ap->volume != bp->volume) 
314         return 1;
315     if (ap->unique != bp->unique) 
316         return 1;
317     if (ap->cell != bp->cell) 
318         return 1;
319     return 0;
320 }
321
322 void cm_fakeSCacheInit(int newFile)
323 {
324     if ( newFile ) {
325         memset(&cm_data.fakeSCache, 0, sizeof(cm_scache_t));
326         cm_data.fakeSCache.cbServerp = (struct cm_server *)(-1);
327         /* can leave clientModTime at 0 */
328         cm_data.fakeSCache.fileType = CM_SCACHETYPE_FILE;
329         cm_data.fakeSCache.unixModeBits = 0777;
330         cm_data.fakeSCache.length.LowPart = 1000;
331         cm_data.fakeSCache.linkCount = 1;
332         cm_data.fakeSCache.refCount = 1;
333     }
334     lock_InitializeMutex(&cm_data.fakeSCache.mx, "cm_scache_t mutex");
335 }
336
337 long
338 cm_ValidateSCache(void)
339 {
340     cm_scache_t * scp, *lscp;
341     long i;
342
343     if ( cm_data.scacheLRUFirstp == NULL && cm_data.scacheLRULastp != NULL ||
344          cm_data.scacheLRUFirstp != NULL && cm_data.scacheLRULastp == NULL) {
345         afsi_log("cm_ValidateSCache failure: inconsistent LRU pointers");
346         fprintf(stderr, "cm_ValidateSCache failure: inconsistent LRU pointers\n");
347         return -17;
348     }
349
350     for ( scp = cm_data.scacheLRUFirstp, lscp = NULL, i = 0; 
351           scp;
352           lscp = scp, scp = (cm_scache_t *) osi_QNext(&scp->q), i++ ) {
353         if (scp->magic != CM_SCACHE_MAGIC) {
354             afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
355             fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
356             return -1;
357         }
358         if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
359             afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
360             fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
361             return -2;
362         }
363         if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
364             afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
365             fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
366             return -3;
367         }
368         if (scp->volp && scp->volp->magic != CM_VOLUME_MAGIC) {
369             afsi_log("cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC");
370             fprintf(stderr, "cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC\n");
371             return -4;
372         }
373         if (i > cm_data.currentSCaches ) {
374             afsi_log("cm_ValidateSCache failure: LRU First queue loops");
375             fprintf(stderr, "cm_ValidateSCache failure: LUR First queue loops\n");
376             return -13;
377         }
378         if (lscp != (cm_scache_t *) osi_QPrev(&scp->q)) {
379             afsi_log("cm_ValidateSCache failure: QPrev(scp) != previous");
380             fprintf(stderr, "cm_ValidateSCache failure: QPrev(scp) != previous\n");
381             return -15;
382         }
383     }
384
385     for ( scp = cm_data.scacheLRULastp, lscp = NULL, i = 0; scp;
386           lscp = scp, scp = (cm_scache_t *) osi_QPrev(&scp->q), i++ ) {
387         if (scp->magic != CM_SCACHE_MAGIC) {
388             afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
389             fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
390             return -5;
391         }
392         if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
393             afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
394             fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
395             return -6;
396         }
397         if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
398             afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
399             fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
400             return -7;
401         }
402         if (scp->volp && scp->volp->magic != CM_VOLUME_MAGIC) {
403             afsi_log("cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC");
404             fprintf(stderr, "cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC\n");
405             return -8;
406         }
407         if (i > cm_data.currentSCaches ) {
408             afsi_log("cm_ValidateSCache failure: LRU Last queue loops");
409             fprintf(stderr, "cm_ValidateSCache failure: LUR Last queue loops\n");
410             return -14;
411         }
412         if (lscp != (cm_scache_t *) osi_QNext(&scp->q)) {
413             afsi_log("cm_ValidateSCache failure: QNext(scp) != next");
414             fprintf(stderr, "cm_ValidateSCache failure: QNext(scp) != next\n");
415             return -16;
416         }
417     }
418
419     for ( i=0; i < cm_data.hashTableSize; i++ ) {
420         for ( scp = cm_data.hashTablep[i]; scp; scp = scp->nextp ) {
421             if (scp->magic != CM_SCACHE_MAGIC) {
422                 afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
423                 fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
424                 return -9;
425             }
426             if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
427                 afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
428                 fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
429                 return -10;
430             }
431             if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
432                 afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
433                 fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
434                 return -11;
435             }
436             if (scp->volp && scp->volp->magic != CM_VOLUME_MAGIC) {
437                 afsi_log("cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC");
438                 fprintf(stderr, "cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC\n");
439                 return -12;
440             }
441         }
442     }
443
444     return cm_dnlcValidate();
445 }
446
447 long
448 cm_ShutdownSCache(void)
449 {
450     cm_scache_t * scp;
451
452     for ( scp = cm_data.scacheLRULastp; scp;
453           scp = (cm_scache_t *) osi_QPrev(&scp->q) ) {
454         if (scp->randomACLp) {
455             lock_ObtainMutex(&scp->mx);
456             cm_FreeAllACLEnts(scp);
457             lock_ReleaseMutex(&scp->mx);
458         }
459         lock_FinalizeMutex(&scp->mx);
460         lock_FinalizeRWLock(&scp->bufCreateLock);
461     }
462
463     return cm_dnlcShutdown();
464 }
465
466 void cm_InitSCache(int newFile, long maxSCaches)
467 {
468     static osi_once_t once;
469         
470     if (osi_Once(&once)) {
471         lock_InitializeRWLock(&cm_scacheLock, "cm_scacheLock");
472         if ( newFile ) {
473             memset(cm_data.hashTablep, 0, sizeof(cm_scache_t *) * cm_data.hashTableSize);
474             cm_data.currentSCaches = 0;
475             cm_data.maxSCaches = maxSCaches;
476             cm_data.scacheLRUFirstp = cm_data.scacheLRULastp = NULL;
477         } else {
478             cm_scache_t * scp;
479
480             for ( scp = cm_data.scacheLRULastp; scp;
481                   scp = (cm_scache_t *) osi_QPrev(&scp->q) ) {
482                 lock_InitializeMutex(&scp->mx, "cm_scache_t mutex");
483                 lock_InitializeRWLock(&scp->bufCreateLock, "cm_scache_t bufCreateLock");
484
485                 scp->cbServerp = NULL;
486                 scp->cbExpires = 0;
487                 scp->fileLocksH = NULL;
488                 scp->fileLocksT = NULL;
489                 scp->serverLock = (-1);
490                 scp->lastRefreshCycle = 0;
491                 scp->exclusiveLocks = 0;
492                 scp->sharedLocks = 0;
493                 scp->openReads = 0;
494                 scp->openWrites = 0;
495                 scp->openShares = 0;
496                 scp->openExcls = 0;
497                 scp->waitCount = 0;
498                 scp->flags &= ~CM_SCACHEFLAG_WAITING;
499             }
500         }
501         cm_allFileLocks = NULL;
502         cm_freeFileLocks = NULL;
503         cm_lockRefreshCycle = 0;
504         cm_fakeSCacheInit(newFile);
505         cm_dnlcInit(newFile);
506         osi_EndOnce(&once);
507     }
508 }
509
510 /* version that doesn't bother creating the entry if we don't find it */
511 cm_scache_t *cm_FindSCache(cm_fid_t *fidp)
512 {
513     long hash;
514     cm_scache_t *scp;
515
516     hash = CM_SCACHE_HASH(fidp);
517
518     if (fidp->cell == 0) {
519         return NULL;
520     }
521
522     lock_ObtainWrite(&cm_scacheLock);
523     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
524         if (cm_FidCmp(fidp, &scp->fid) == 0) {
525             cm_HoldSCacheNoLock(scp);
526             cm_AdjustLRU(scp);
527             lock_ReleaseWrite(&cm_scacheLock);
528             return scp;
529         }
530     }
531     lock_ReleaseWrite(&cm_scacheLock);
532     return NULL;
533 }
534
535 long cm_GetSCache(cm_fid_t *fidp, cm_scache_t **outScpp, cm_user_t *userp,
536                   cm_req_t *reqp)
537 {
538     long hash;
539     cm_scache_t *scp;
540     long code;
541     cm_volume_t *volp = 0;
542     cm_cell_t *cellp;
543     char* mp = 0;
544     int special; // yj: boolean variable to test if file is on root.afs
545     int isRoot;
546     extern cm_fid_t cm_rootFid;
547         
548     hash = CM_SCACHE_HASH(fidp);
549         
550     osi_assert(fidp->cell != 0);
551
552     if (fidp->cell== cm_data.rootFid.cell && 
553          fidp->volume==cm_data.rootFid.volume &&
554          fidp->vnode==0x0 && fidp->unique==0x0)
555     {
556         osi_Log0(afsd_logp,"cm_GetSCache called with root cell/volume and vnode=0 and unique=0");
557     }
558
559     // yj: check if we have the scp, if so, we don't need
560     // to do anything else
561     lock_ObtainWrite(&cm_scacheLock);
562     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
563         if (cm_FidCmp(fidp, &scp->fid) == 0) {
564             cm_HoldSCacheNoLock(scp);
565             *outScpp = scp;
566             cm_AdjustLRU(scp);
567             lock_ReleaseWrite(&cm_scacheLock);
568             return 0;
569         }
570     }
571         
572     // yj: when we get here, it means we don't have an scp
573     // so we need to either load it or fake it, depending
574     // on whether the file is "special", see below.
575
576     // yj: if we're trying to get an scp for a file that's
577     // on root.afs of homecell, we want to handle it specially
578     // because we have to fill in the status stuff 'coz we
579     // don't want trybulkstat to fill it in for us
580 #ifdef AFS_FREELANCE_CLIENT
581     special = (fidp->cell==AFS_FAKE_ROOT_CELL_ID && 
582                fidp->volume==AFS_FAKE_ROOT_VOL_ID &&
583                !(fidp->vnode==0x1 && fidp->unique==0x1));
584     isRoot = (fidp->cell==AFS_FAKE_ROOT_CELL_ID && 
585               fidp->volume==AFS_FAKE_ROOT_VOL_ID &&
586               fidp->vnode==0x1 && fidp->unique==0x1);
587     if (cm_freelanceEnabled && isRoot) {
588         osi_Log0(afsd_logp,"cm_GetSCache Freelance and isRoot");
589         /* freelance: if we are trying to get the root scp for the first
590          * time, we will just put in a place holder entry. 
591          */
592         volp = NULL;
593     }
594           
595     if (cm_freelanceEnabled && special) {
596         osi_Log0(afsd_logp,"cm_GetSCache Freelance and special");
597         if (fidp->vnode > 1 && fidp->vnode <= cm_noLocalMountPoints + 2) {
598             lock_ObtainMutex(&cm_Freelance_Lock);
599             mp =(cm_localMountPoints+fidp->vnode-2)->mountPointStringp;
600             lock_ReleaseMutex(&cm_Freelance_Lock);
601         } else {
602             mp = "";
603         }
604         scp = cm_GetNewSCache();
605         if (scp == NULL) {
606             osi_Log0(afsd_logp,"cm_GetSCache unable to obtain *new* scache entry");
607             lock_ReleaseWrite(&cm_scacheLock);
608             return CM_ERROR_WOULDBLOCK;
609         }
610
611 #if not_too_dangerous
612         /* dropping the cm_scacheLock allows more than one thread
613          * to obtain the same cm_scache_t from the LRU list.  Since
614          * the refCount is known to be zero at this point we have to
615          * assume that no one else is using the one this is returned.
616          */
617         lock_ReleaseWrite(&cm_scacheLock);
618         lock_ObtainMutex(&scp->mx);
619         lock_ObtainWrite(&cm_scacheLock);
620 #endif
621         scp->fid = *fidp;
622         scp->volp = cm_data.rootSCachep->volp;
623         scp->dotdotFid.cell=AFS_FAKE_ROOT_CELL_ID;
624         scp->dotdotFid.volume=AFS_FAKE_ROOT_VOL_ID;
625         scp->dotdotFid.unique=1;
626         scp->dotdotFid.vnode=1;
627         scp->flags |= (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO);
628         scp->nextp=cm_data.hashTablep[hash];
629         cm_data.hashTablep[hash]=scp;
630         scp->flags |= CM_SCACHEFLAG_INHASH;
631         scp->refCount = 1;
632         osi_Log1(afsd_logp,"cm_GetSCache (freelance) sets refCount to 1 scp 0x%x", scp);
633         if (fidp->vnode > 1 && fidp->vnode <= cm_noLocalMountPoints + 2)
634             scp->fileType = (cm_localMountPoints+fidp->vnode-2)->fileType;
635         else 
636             scp->fileType = CM_SCACHETYPE_INVALID;
637
638         lock_ObtainMutex(&cm_Freelance_Lock);
639         scp->length.LowPart = (DWORD)strlen(mp)+4;
640         scp->length.HighPart = 0;
641         strncpy(scp->mountPointStringp,mp,MOUNTPOINTLEN);
642         scp->mountPointStringp[MOUNTPOINTLEN-1] = '\0';
643         lock_ReleaseMutex(&cm_Freelance_Lock);
644
645         scp->owner=0x0;
646         scp->unixModeBits=0x1ff;
647         scp->clientModTime=FakeFreelanceModTime;
648         scp->serverModTime=FakeFreelanceModTime;
649         scp->parentUnique = 0x1;
650         scp->parentVnode=0x1;
651         scp->group=0;
652         scp->dataVersion=cm_data.fakeDirVersion;
653         scp->lockDataVersion=-1; /* no lock yet */
654 #if not_too_dangerous
655         lock_ReleaseMutex(&scp->mx);
656 #endif
657         *outScpp = scp;
658         lock_ReleaseWrite(&cm_scacheLock);
659         return 0;
660     }
661     // end of yj code
662 #endif /* AFS_FREELANCE_CLIENT */
663
664     /* otherwise, we need to find the volume */
665     if (!cm_freelanceEnabled || !isRoot) {
666         lock_ReleaseWrite(&cm_scacheLock);      /* for perf. reasons */
667         cellp = cm_FindCellByID(fidp->cell);
668         if (!cellp) 
669             return CM_ERROR_NOSUCHCELL;
670
671         code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, &volp);
672         if (code) 
673             return code;
674         lock_ObtainWrite(&cm_scacheLock);
675     }
676         
677     /* otherwise, we have the volume, now reverify that the scp doesn't
678      * exist, and proceed.
679      */
680     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
681         if (cm_FidCmp(fidp, &scp->fid) == 0) {
682             cm_HoldSCacheNoLock(scp);
683             osi_assert(scp->volp == volp);
684             cm_AdjustLRU(scp);
685             lock_ReleaseWrite(&cm_scacheLock);
686             if (volp)
687                 cm_PutVolume(volp);
688             *outScpp = scp;
689             return 0;
690         }
691     }
692         
693     /* now, if we don't have the fid, recycle something */
694     scp = cm_GetNewSCache();
695     if (scp == NULL) {
696         osi_Log0(afsd_logp,"cm_GetNewSCache unable to obtain *new* scache entry");
697         lock_ReleaseWrite(&cm_scacheLock);
698         return CM_ERROR_WOULDBLOCK;
699     }
700     osi_Log2(afsd_logp,"cm_GetNewSCache returns scp 0x%x flags 0x%x", scp, scp->flags);
701
702     osi_assert(!(scp->flags & CM_SCACHEFLAG_INHASH));
703
704 #if not_too_dangerous
705     /* dropping the cm_scacheLock allows more than one thread
706      * to obtain the same cm_scache_t from the LRU list.  Since
707      * the refCount is known to be zero at this point we have to
708      * assume that no one else is using the one this is returned.
709      */
710     lock_ReleaseWrite(&cm_scacheLock);
711     lock_ObtainMutex(&scp->mx);
712     lock_ObtainWrite(&cm_scacheLock);
713 #endif
714     scp->fid = *fidp;
715     scp->volp = volp;   /* a held reference */
716
717     if (!cm_freelanceEnabled || !isRoot) {
718         /* if this scache entry represents a volume root then we need 
719          * to copy the dotdotFipd from the volume structure where the 
720          * "master" copy is stored (defect 11489)
721          */
722         if (scp->fid.vnode == 1 && scp->fid.unique == 1) {
723             scp->dotdotFid = volp->dotdotFid;
724         }
725           
726         if (volp->roID == fidp->volume)
727             scp->flags |= (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO);
728         else if (volp->bkID == fidp->volume)
729             scp->flags |= CM_SCACHEFLAG_RO;
730     }
731     scp->nextp = cm_data.hashTablep[hash];
732     cm_data.hashTablep[hash] = scp;
733     scp->flags |= CM_SCACHEFLAG_INHASH;
734     scp->refCount = 1;
735     osi_Log1(afsd_logp,"cm_GetSCache sets refCount to 1 scp 0x%x", scp);
736 #if not_too_dangerous
737     lock_ReleaseMutex(&scp->mx);
738 #endif
739
740     /* XXX - The following fields in the cm_scache are 
741      * uninitialized:
742      *   fileType
743      *   parentVnode
744      *   parentUnique
745      */
746     lock_ReleaseWrite(&cm_scacheLock);
747         
748     /* now we have a held scache entry; just return it */
749     *outScpp = scp;
750     return 0;
751 }
752
753 /* Returns a held reference to the scache's parent 
754  * if it exists */
755 cm_scache_t * cm_FindSCacheParent(cm_scache_t * scp)
756 {
757     long code = 0;
758     int i;
759     cm_fid_t    parent_fid;
760     cm_scache_t * pscp = NULL;
761
762     lock_ObtainRead(&cm_scacheLock);
763     parent_fid = scp->fid;
764     parent_fid.vnode = scp->parentVnode;
765     parent_fid.unique = scp->parentUnique;
766
767     if (cm_FidCmp(&scp->fid, &parent_fid)) {
768         i = CM_SCACHE_HASH(&parent_fid);
769         for (pscp = cm_data.hashTablep[i]; pscp; pscp = pscp->nextp) {
770             if (!cm_FidCmp(&pscp->fid, &parent_fid)) {
771                 cm_HoldSCacheNoLock(pscp);
772                 break;
773             }
774         }
775     }
776
777     lock_ReleaseRead(&cm_scacheLock);
778
779     return pscp;
780 }
781
782 /* synchronize a fetch, store, read, write, fetch status or store status.
783  * Called with scache mutex held, and returns with it held, but temporarily
784  * drops it during the fetch.
785  * 
786  * At most one flag can be on in flags, if this is an RPC request.
787  *
788  * Also, if we're fetching or storing data, we must ensure that we have a buffer.
789  *
790  * There are a lot of weird restrictions here; here's an attempt to explain the
791  * rationale for the concurrency restrictions implemented in this function.
792  *
793  * First, although the file server will break callbacks when *another* machine
794  * modifies a file or status block, the client itself is responsible for
795  * concurrency control on its own requests.  Callback breaking events are rare,
796  * and simply invalidate any concurrent new status info.
797  *
798  * In the absence of callback breaking messages, we need to know how to
799  * synchronize incoming responses describing updates to files.  We synchronize
800  * operations that update the data version by comparing the data versions.
801  * However, updates that do not update the data, but only the status, can't be
802  * synchronized with fetches or stores, since there's nothing to compare
803  * to tell which operation executed first at the server.
804  *
805  * Thus, we can allow multiple ops that change file data, or dir data, and
806  * fetches.  However, status storing ops have to be done serially.
807  *
808  * Furthermore, certain data-changing ops are incompatible: we can't read or
809  * write a buffer while doing a truncate.  We can't read and write the same
810  * buffer at the same time, or write while fetching or storing, or read while
811  * fetching a buffer (this may change).  We can't fetch and store at the same
812  * time, either.
813  *
814  * With respect to status, we can't read and write at the same time, read while
815  * fetching, write while fetching or storing, or fetch and store at the same time.
816  *
817  * We can't allow a get callback RPC to run in concurrently with something that
818  * will return updated status, since we could start a call, have the server
819  * return status, have another machine make an update to the status (which
820  * doesn't change serverModTime), have the original machine get a new callback,
821  * and then have the original machine merge in the early, old info from the
822  * first call.  At this point, the easiest way to avoid this problem is to have
823  * getcallback calls conflict with all others for the same vnode.  Other calls
824  * to cm_MergeStatus that aren't associated with calls to cm_SyncOp on the same
825  * vnode must be careful not to merge in their status unless they have obtained
826  * a callback from the start of their call.
827  *
828  * Note added 1/23/96
829  * Concurrent StoreData RPC's can cause trouble if the file is being extended.
830  * Each such RPC passes a FileLength parameter, which the server uses to do
831  * pre-truncation if necessary.  So if two RPC's are processed out of order at
832  * the server, the one with the smaller FileLength will be processed last,
833  * possibly resulting in a bogus truncation.  The simplest way to avoid this
834  * is to serialize all StoreData RPC's.  This is the reason we defined
835  * CM_SCACHESYNC_STOREDATA_EXCL and CM_SCACHEFLAG_DATASTORING.
836  */
837 long cm_SyncOp(cm_scache_t *scp, cm_buf_t *bufp, cm_user_t *userp, cm_req_t *reqp,
838                afs_uint32 rights, afs_uint32 flags)
839 {
840     osi_queueData_t *qdp;
841     long code;
842     cm_buf_t *tbufp;
843     afs_uint32 outRights;
844     int bufLocked;
845     afs_uint32 sleep_scp_flags = 0;
846     afs_uint32 sleep_buf_cmflags = 0;
847     afs_uint32 sleep_scp_bufs = 0;
848
849     /* lookup this first */
850     bufLocked = flags & CM_SCACHESYNC_BUFLOCKED;
851
852         if (bufp)
853                 osi_assert(bufp->refCount > 0);
854
855
856     /* Do the access check.  Now we don't really do the access check
857      * atomically, since the caller doesn't expect the parent dir to be
858      * returned locked, and that is what we'd have to do to prevent a
859      * callback breaking message on the parent due to a setacl call from
860      * being processed while we're running.  So, instead, we check things
861      * here, and if things look fine with the access, we proceed to finish
862      * the rest of this check.  Sort of a hack, but probably good enough.
863      */
864
865     while (1) {
866         if (flags & CM_SCACHESYNC_FETCHSTATUS) {
867             /* if we're bringing in a new status block, ensure that
868              * we aren't already doing so, and that no one is
869              * changing the status concurrently, either.  We need
870              * to do this, even if the status is of a different
871              * type, since we don't have the ability to figure out,
872              * in the AFS 3 protocols, which status-changing
873              * operation ran first, or even which order a read and
874              * a write occurred in.
875              */
876             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
877                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
878                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want FETCHSTATUS", scp);
879                 goto sleep;
880             }
881         }
882         if (flags & (CM_SCACHESYNC_STORESIZE | CM_SCACHESYNC_STORESTATUS
883                       | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_GETCALLBACK)) {
884             /* if we're going to make an RPC to change the status, make sure
885              * that no one is bringing in or sending out the status.
886              */
887             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING |
888                               CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
889                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
890                 goto sleep;
891             }
892             if (scp->bufReadsp || scp->bufWritesp) {
893                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is bufRead|bufWrite want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
894                 goto sleep;
895             }
896         }
897         if (flags & CM_SCACHESYNC_FETCHDATA) {
898             /* if we're bringing in a new chunk of data, make sure that
899              * nothing is happening to that chunk, and that we aren't
900              * changing the basic file status info, either.
901              */
902             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
903                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
904                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want FETCHDATA", scp);
905                 goto sleep;
906             }
907             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
908                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want FETCHDATA", scp, bufp);
909                 goto sleep;
910             }
911         }
912         if (flags & CM_SCACHESYNC_STOREDATA) {
913             /* same as fetch data */
914             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
915                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
916                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STOREDATA", scp);
917                 goto sleep;
918             }
919             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
920                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want STOREDATA", scp, bufp);
921                 goto sleep;
922             }
923         }
924
925         if (flags & CM_SCACHESYNC_STOREDATA_EXCL) {
926             /* Don't allow concurrent StoreData RPC's */
927             if (scp->flags & CM_SCACHEFLAG_DATASTORING) {
928                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is DATASTORING want STOREDATA_EXCL", scp);
929                 goto sleep;
930             }
931         }
932
933         if (flags & CM_SCACHESYNC_ASYNCSTORE) {
934             /* Don't allow more than one BKG store request */
935             if (scp->flags & CM_SCACHEFLAG_ASYNCSTORING) {
936                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is ASYNCSTORING want ASYNCSTORE", scp);
937                 goto sleep;
938             }
939         }
940
941         if (flags & CM_SCACHESYNC_LOCK) {
942             /* Don't allow concurrent fiddling with lock lists */
943             if (scp->flags & CM_SCACHEFLAG_LOCKING) {
944                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is LOCKING want LOCK", scp);
945                 goto sleep;
946             }
947         }
948
949         /* now the operations that don't correspond to making RPCs */
950         if (flags & CM_SCACHESYNC_GETSTATUS) {
951             /* we can use the status that's here, if we're not
952              * bringing in new status.
953              */
954             if (scp->flags & (CM_SCACHEFLAG_FETCHING)) {
955                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want GETSTATUS", scp);
956                 goto sleep;
957             }
958         }
959         if (flags & CM_SCACHESYNC_SETSTATUS) {
960             /* we can make a change to the local status, as long as
961              * the status isn't changing now.
962              *
963              * If we're fetching or storing a chunk of data, we can
964              * change the status locally, since the fetch/store
965              * operations don't change any of the data that we're
966              * changing here.
967              */
968             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING | CM_SCACHEFLAG_SIZESTORING)) {
969                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING want SETSTATUS", scp);
970                 goto sleep;
971             }
972         }
973         if (flags & CM_SCACHESYNC_READ) {
974             /* we're going to read the data, make sure that the
975              * status is available, and that the data is here.  It
976              * is OK to read while storing the data back.
977              */
978             if (scp->flags & CM_SCACHEFLAG_FETCHING) {
979                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want READ", scp);
980                 goto sleep;
981             }
982             if (bufp && ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == CM_BUF_CMFETCHING)) {
983                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING want READ", scp, bufp);
984                 goto sleep;
985             }
986         }
987         if (flags & CM_SCACHESYNC_WRITE) {
988             /* don't write unless the status is stable and the chunk
989              * is stable.
990              */
991             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
992                                | CM_SCACHEFLAG_SIZESTORING)) {
993                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING want WRITE", scp);
994                 goto sleep;
995             }
996             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
997                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want WRITE", scp, bufp);
998                 goto sleep;
999             }
1000         }
1001
1002         // yj: modified this so that callback only checked if we're
1003         // not checking something on /afs
1004         /* fix the conditional to match the one in cm_HaveCallback */
1005         if ((flags & CM_SCACHESYNC_NEEDCALLBACK)
1006 #ifdef AFS_FREELANCE_CLIENT
1007              && (!cm_freelanceEnabled || 
1008                   !(scp->fid.vnode==0x1 && scp->fid.unique==0x1) ||
1009                   scp->fid.cell!=AFS_FAKE_ROOT_CELL_ID ||
1010                   scp->fid.volume!=AFS_FAKE_ROOT_VOL_ID ||
1011                   cm_fakeDirCallback < 2)
1012 #endif /* AFS_FREELANCE_CLIENT */
1013              ) {
1014             if ((flags & CM_SCACHESYNC_FORCECB) || !cm_HaveCallback(scp)) {
1015                 osi_Log1(afsd_logp, "CM SyncOp getting callback on scp 0x%p",
1016                           scp);
1017                 if (bufLocked) 
1018                     lock_ReleaseMutex(&bufp->mx);
1019                 code = cm_GetCallback(scp, userp, reqp, (flags & CM_SCACHESYNC_FORCECB)?1:0);
1020                 if (bufLocked) {
1021                     lock_ReleaseMutex(&scp->mx);
1022                     lock_ObtainMutex(&bufp->mx);
1023                     lock_ObtainMutex(&scp->mx);
1024                 }
1025                 if (code) 
1026                     return code;
1027                 flags &= ~CM_SCACHESYNC_FORCECB;        /* only force once */
1028                 continue;
1029             }
1030         }
1031
1032         if (rights) {
1033             /* can't check access rights without a callback */
1034             osi_assert(flags & CM_SCACHESYNC_NEEDCALLBACK);
1035
1036             if ((rights & PRSFS_WRITE) && (scp->flags & CM_SCACHEFLAG_RO))
1037                 return CM_ERROR_READONLY;
1038
1039             if (cm_HaveAccessRights(scp, userp, rights, &outRights)) {
1040                 if (~outRights & rights) 
1041                     return CM_ERROR_NOACCESS;
1042             }
1043             else {
1044                 /* we don't know the required access rights */
1045                 if (bufLocked) lock_ReleaseMutex(&bufp->mx);
1046                 code = cm_GetAccessRights(scp, userp, reqp);
1047                 if (bufLocked) {
1048                     lock_ReleaseMutex(&scp->mx);
1049                     lock_ObtainMutex(&bufp->mx);
1050                     lock_ObtainMutex(&scp->mx);
1051                 }
1052                 if (code) 
1053                     return code;
1054                 continue;
1055             }
1056         }
1057
1058         /* if we get here, we're happy */
1059         break;
1060
1061       sleep:
1062         /* first check if we're not supposed to wait: fail 
1063          * in this case, returning with everything still locked.
1064          */
1065         if (flags & CM_SCACHESYNC_NOWAIT) 
1066             return CM_ERROR_WOULDBLOCK;
1067
1068         sleep_scp_flags = scp->flags;           /* so we know why we slept */
1069         sleep_buf_cmflags = bufp ? bufp->cmFlags : 0;
1070         sleep_scp_bufs = (scp->bufReadsp ? 1 : 0) | (scp->bufWritesp ? 2 : 0);
1071
1072         /* wait here, then try again */
1073         osi_Log1(afsd_logp, "CM SyncOp sleeping scp 0x%p", scp);
1074         if ( scp->flags & CM_SCACHEFLAG_WAITING ) {
1075             scp->waitCount++;
1076             scp->waitRequests++;
1077             osi_Log3(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING already set for 0x%p; %d threads; %d requests", 
1078                      scp, scp->waitCount, scp->waitRequests);
1079         } else {
1080             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING set for 0x%p", scp);
1081             scp->flags |= CM_SCACHEFLAG_WAITING;
1082             scp->waitCount = scp->waitRequests = 1;
1083         }
1084         if (bufLocked) 
1085             lock_ReleaseMutex(&bufp->mx);
1086         osi_SleepM((LONG_PTR) &scp->flags, &scp->mx);
1087
1088         smb_UpdateServerPriority();
1089
1090         if (bufLocked) 
1091             lock_ObtainMutex(&bufp->mx);
1092         lock_ObtainMutex(&scp->mx);
1093         scp->waitCount--;
1094         osi_Log3(afsd_logp, "CM SyncOp woke! scp 0x%p; still waiting %d threads of %d requests", 
1095                  scp, scp->waitCount, scp->waitRequests);
1096         if (scp->waitCount == 0) {
1097             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING reset for 0x%p", scp);
1098             scp->flags &= ~CM_SCACHEFLAG_WAITING;
1099             scp->waitRequests = 0;
1100         }
1101     } /* big while loop */
1102         
1103     /* now, update the recorded state for RPC-type calls */
1104     if (flags & CM_SCACHESYNC_FETCHSTATUS)
1105         scp->flags |= CM_SCACHEFLAG_FETCHING;
1106     if (flags & CM_SCACHESYNC_STORESTATUS)
1107         scp->flags |= CM_SCACHEFLAG_STORING;
1108     if (flags & CM_SCACHESYNC_STORESIZE)
1109         scp->flags |= CM_SCACHEFLAG_SIZESTORING;
1110     if (flags & CM_SCACHESYNC_GETCALLBACK)
1111         scp->flags |= CM_SCACHEFLAG_GETCALLBACK;
1112     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1113         scp->flags |= CM_SCACHEFLAG_DATASTORING;
1114     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1115         scp->flags |= CM_SCACHEFLAG_ASYNCSTORING;
1116     if (flags & CM_SCACHESYNC_LOCK)
1117         scp->flags |= CM_SCACHEFLAG_LOCKING;
1118
1119     /* now update the buffer pointer */
1120     if (flags & CM_SCACHESYNC_FETCHDATA) {
1121         /* ensure that the buffer isn't already in the I/O list */
1122         if (bufp) {
1123             for(qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1124                 tbufp = osi_GetQData(qdp);
1125                 osi_assert(tbufp != bufp);
1126             }
1127         }
1128
1129         /* queue a held reference to the buffer in the "reading" I/O list */
1130         qdp = osi_QDAlloc();
1131         osi_SetQData(qdp, bufp);
1132         if (bufp) {
1133             buf_Hold(bufp);
1134             bufp->cmFlags |= CM_BUF_CMFETCHING;
1135         }
1136         osi_QAdd((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1137     }
1138
1139     if (flags & CM_SCACHESYNC_STOREDATA) {
1140         /* ensure that the buffer isn't already in the I/O list */
1141         if (bufp) {
1142             for(qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1143                 tbufp = osi_GetQData(qdp);
1144                 osi_assert(tbufp != bufp);
1145             }
1146         }
1147
1148         /* queue a held reference to the buffer in the "writing" I/O list */
1149         qdp = osi_QDAlloc();
1150         osi_SetQData(qdp, bufp);
1151         if (bufp) {
1152             buf_Hold(bufp);
1153             bufp->cmFlags |= CM_BUF_CMSTORING;
1154         }
1155         osi_QAdd((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1156     }
1157
1158     return 0;
1159 }
1160
1161 /* for those syncops that setup for RPCs.
1162  * Called with scache locked.
1163  */
1164 void cm_SyncOpDone(cm_scache_t *scp, cm_buf_t *bufp, afs_uint32 flags)
1165 {
1166     osi_queueData_t *qdp;
1167     cm_buf_t *tbufp;
1168
1169     lock_AssertMutex(&scp->mx);
1170
1171     /* now, update the recorded state for RPC-type calls */
1172     if (flags & CM_SCACHESYNC_FETCHSTATUS)
1173         scp->flags &= ~CM_SCACHEFLAG_FETCHING;
1174     if (flags & CM_SCACHESYNC_STORESTATUS)
1175         scp->flags &= ~CM_SCACHEFLAG_STORING;
1176     if (flags & CM_SCACHESYNC_STORESIZE)
1177         scp->flags &= ~CM_SCACHEFLAG_SIZESTORING;
1178     if (flags & CM_SCACHESYNC_GETCALLBACK)
1179         scp->flags &= ~CM_SCACHEFLAG_GETCALLBACK;
1180     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1181         scp->flags &= ~CM_SCACHEFLAG_DATASTORING;
1182     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1183         scp->flags &= ~CM_SCACHEFLAG_ASYNCSTORING;
1184     if (flags & CM_SCACHESYNC_LOCK)
1185         scp->flags &= ~CM_SCACHEFLAG_LOCKING;
1186
1187     /* now update the buffer pointer */
1188     if (flags & CM_SCACHESYNC_FETCHDATA) {
1189         /* ensure that the buffer isn't already in the I/O list */
1190         for(qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1191             tbufp = osi_GetQData(qdp);
1192             if (tbufp == bufp) 
1193                 break;
1194         }
1195         if (qdp) {
1196             osi_QRemove((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1197             osi_QDFree(qdp);
1198         }
1199         if (bufp) {
1200             int release = 0;
1201             if (bufp->cmFlags & CM_BUF_CMFETCHING)
1202                 release = 1;
1203             bufp->cmFlags &= ~(CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED);
1204             if (bufp->flags & CM_BUF_WAITING) {
1205                 osi_Log2(afsd_logp, "CM SyncOpDone Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1206                 osi_Wakeup((LONG_PTR) &bufp);
1207             }
1208             if (release)
1209                 buf_Release(bufp);
1210         }
1211     }
1212
1213     /* now update the buffer pointer */
1214     if (flags & CM_SCACHESYNC_STOREDATA) {
1215         /* ensure that the buffer isn't already in the I/O list */
1216         for(qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1217             tbufp = osi_GetQData(qdp);
1218             if (tbufp == bufp) 
1219                 break;
1220         }
1221         if (qdp) {
1222             osi_QRemove((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1223             osi_QDFree(qdp);
1224         }
1225         if (bufp) {
1226             int release = 0;
1227             if (bufp->cmFlags & CM_BUF_CMSTORING)
1228                 release = 1;
1229             bufp->cmFlags &= ~CM_BUF_CMSTORING;
1230             if (bufp->flags & CM_BUF_WAITING) {
1231                 osi_Log2(afsd_logp, "CM SyncOpDone Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1232                 osi_Wakeup((LONG_PTR) &bufp);
1233             }
1234             if (release)
1235                 buf_Release(bufp);
1236         }
1237     }
1238
1239     /* and wakeup anyone who is waiting */
1240     if (scp->flags & CM_SCACHEFLAG_WAITING) {
1241         osi_Log1(afsd_logp, "CM SyncOpDone Waking scp 0x%p", scp);
1242         osi_Wakeup((LONG_PTR) &scp->flags);
1243     }
1244 }       
1245
1246 /* merge in a response from an RPC.  The scp must be locked, and the callback
1247  * is optional.
1248  *
1249  * Don't overwrite any status info that is dirty, since we could have a store
1250  * operation (such as store data) that merges some info in, and we don't want
1251  * to lose the local updates.  Typically, there aren't many updates we do
1252  * locally, anyway, probably only mtime.
1253  *
1254  * There is probably a bug in here where a chmod (which doesn't change
1255  * serverModTime) that occurs between two fetches, both of whose responses are
1256  * handled after the callback breaking is done, but only one of whose calls
1257  * started before that, can cause old info to be merged from the first call.
1258  */
1259 void cm_MergeStatus(cm_scache_t *scp, AFSFetchStatus *statusp, AFSVolSync *volp,
1260                     cm_user_t *userp, afs_uint32 flags)
1261 {
1262     // yj: i want to create some fake status for the /afs directory and the
1263     // entries under that directory
1264 #ifdef AFS_FREELANCE_CLIENT
1265     if (cm_freelanceEnabled && scp == cm_data.rootSCachep) {
1266         osi_Log0(afsd_logp,"cm_MergeStatus Freelance cm_data.rootSCachep");
1267         statusp->InterfaceVersion = 0x1;
1268         statusp->FileType = CM_SCACHETYPE_DIRECTORY;
1269         statusp->LinkCount = scp->linkCount;
1270         statusp->Length = cm_fakeDirSize;
1271         statusp->Length_hi = 0;
1272         statusp->DataVersion = cm_data.fakeDirVersion;
1273         statusp->Author = 0x1;
1274         statusp->Owner = 0x0;
1275         statusp->CallerAccess = 0x9;
1276         statusp->AnonymousAccess = 0x9;
1277         statusp->UnixModeBits = 0x1ff;
1278         statusp->ParentVnode = 0x1;
1279         statusp->ParentUnique = 0x1;
1280         statusp->ResidencyMask = 0;
1281         statusp->ClientModTime = FakeFreelanceModTime;
1282         statusp->ServerModTime = FakeFreelanceModTime;
1283         statusp->Group = 0;
1284         statusp->SyncCounter = 0;
1285         statusp->dataVersionHigh = 0;
1286         statusp->errorCode = 0;
1287     }
1288 #endif /* AFS_FREELANCE_CLIENT */
1289
1290     if (statusp->errorCode != 0) {      
1291         scp->flags |= CM_SCACHEFLAG_EACCESS;
1292         osi_Log2(afsd_logp, "Merge, Failure scp %x code 0x%x", scp, statusp->errorCode);
1293         return;
1294     } else {
1295         scp->flags &= ~CM_SCACHEFLAG_EACCESS;
1296     }
1297
1298     if (!(flags & CM_MERGEFLAG_FORCE)
1299          && statusp->DataVersion < (unsigned long) scp->dataVersion) {
1300         struct cm_cell *cellp;
1301
1302         cellp = cm_FindCellByID(scp->fid.cell);
1303         if (scp->cbServerp) {
1304             struct cm_volume *volp = NULL;
1305
1306             cm_GetVolumeByID(cellp, scp->fid.volume, userp,
1307                               (cm_req_t *) NULL, &volp);
1308             osi_Log2(afsd_logp, "old data from server %x volume %s",
1309                       scp->cbServerp->addr.sin_addr.s_addr,
1310                       volp ? volp->namep : "(unknown)");
1311             if (volp)
1312                 cm_PutVolume(volp);
1313         }
1314         osi_Log3(afsd_logp, "Bad merge, scp %x, scp dv %d, RPC dv %d",
1315                   scp, scp->dataVersion, statusp->DataVersion);
1316         /* we have a number of data fetch/store operations running
1317          * concurrently, and we can tell which one executed last at the
1318          * server by its mtime.
1319          * Choose the one with the largest mtime, and ignore the rest.
1320          *
1321          * These concurrent calls are incompatible with setting the
1322          * mtime, so we won't have a locally changed mtime here.
1323          *
1324          * We could also have ACL info for a different user than usual,
1325          * in which case we have to do that part of the merge, anyway.
1326          * We won't have to worry about the info being old, since we
1327          * won't have concurrent calls
1328          * that change file status running from this machine.
1329          *
1330          * Added 3/17/98:  if we see data version regression on an RO
1331          * file, it's probably due to a server holding an out-of-date
1332          * replica, rather than to concurrent RPC's.  Failures to
1333          * release replicas are now flagged by the volserver, but only
1334          * since AFS 3.4 5.22, so there are plenty of clients getting
1335          * out-of-date replicas out there.
1336          *
1337          * If we discover an out-of-date replica, by this time it's too
1338          * late to go to another server and retry.  Also, we can't
1339          * reject the merge, because then there is no way for
1340          * GetAccess to do its work, and the caller gets into an
1341          * infinite loop.  So we just grin and bear it.
1342          */
1343         if (!(scp->flags & CM_SCACHEFLAG_RO))
1344             return;
1345     }       
1346     scp->serverModTime = statusp->ServerModTime;
1347
1348     if (!(scp->mask & CM_SCACHEMASK_CLIENTMODTIME)) {
1349         scp->clientModTime = statusp->ClientModTime;
1350     }
1351     if (!(scp->mask & CM_SCACHEMASK_LENGTH)) {
1352         scp->length.LowPart = statusp->Length;
1353         scp->length.HighPart = statusp->Length_hi;
1354     }
1355
1356     scp->serverLength.LowPart = statusp->Length;
1357     scp->serverLength.HighPart = statusp->Length_hi;
1358
1359     scp->linkCount = statusp->LinkCount;
1360     scp->dataVersion = statusp->DataVersion;
1361     scp->owner = statusp->Owner;
1362     scp->group = statusp->Group;
1363     scp->unixModeBits = statusp->UnixModeBits & 07777;
1364
1365     if (statusp->FileType == File)
1366         scp->fileType = CM_SCACHETYPE_FILE;
1367     else if (statusp->FileType == Directory)
1368         scp->fileType = CM_SCACHETYPE_DIRECTORY;
1369     else if (statusp->FileType == SymbolicLink) {
1370         if ((scp->unixModeBits & 0111) == 0)
1371             scp->fileType = CM_SCACHETYPE_MOUNTPOINT;
1372         else
1373             scp->fileType = CM_SCACHETYPE_SYMLINK;
1374     }       
1375     else {
1376         osi_Log2(afsd_logp, "Merge, Invalid File Type (%d), scp %x", statusp->FileType, scp);
1377         scp->fileType = CM_SCACHETYPE_INVALID;  /* invalid */
1378     }
1379     /* and other stuff */
1380     scp->parentVnode = statusp->ParentVnode;
1381     scp->parentUnique = statusp->ParentUnique;
1382         
1383     /* and merge in the private acl cache info, if this is more than the public
1384      * info; merge in the public stuff in any case.
1385      */
1386     scp->anyAccess = statusp->AnonymousAccess;
1387
1388     if (userp != NULL) {
1389         cm_AddACLCache(scp, userp, statusp->CallerAccess);
1390     }
1391 }
1392
1393 /* note that our stat cache info is incorrect, so force us eventually
1394  * to stat the file again.  There may be dirty data associated with
1395  * this vnode, and we want to preserve that information.
1396  *
1397  * This function works by simply simulating a loss of the callback.
1398  *
1399  * This function must be called with the scache locked.
1400  */
1401 void cm_DiscardSCache(cm_scache_t *scp)
1402 {
1403     lock_AssertMutex(&scp->mx);
1404     if (scp->cbServerp) {
1405         cm_PutServer(scp->cbServerp);
1406         scp->cbServerp = NULL;
1407     }
1408     scp->cbExpires = 0;
1409     scp->flags &= ~CM_SCACHEFLAG_CALLBACK;
1410     cm_dnlcPurgedp(scp);
1411     cm_dnlcPurgevp(scp);
1412     cm_FreeAllACLEnts(scp);
1413
1414     /* Force mount points and symlinks to be re-evaluated */
1415     scp->mountPointStringp[0] = '\0';
1416 }
1417
1418 void cm_AFSFidFromFid(AFSFid *afsFidp, cm_fid_t *fidp)
1419 {
1420     afsFidp->Volume = fidp->volume;
1421     afsFidp->Vnode = fidp->vnode;
1422     afsFidp->Unique = fidp->unique;
1423 }       
1424
1425 void cm_HoldSCacheNoLock(cm_scache_t *scp)
1426 {
1427     osi_assert(scp != 0);
1428     scp->refCount++;
1429 #ifdef DEBUG_REFCOUNT
1430     osi_Log2(afsd_logp,"cm_HoldSCacheNoLock scp 0x%p ref %d",scp, scp->refCount);
1431 #endif
1432 }
1433
1434 void cm_HoldSCache(cm_scache_t *scp)
1435 {
1436     osi_assert(scp != 0);
1437     lock_ObtainWrite(&cm_scacheLock);
1438     scp->refCount++;
1439 #ifdef DEBUG_REFCOUNT
1440     osi_Log2(afsd_logp,"cm_HoldSCache scp 0x%p ref %d",scp, scp->refCount);
1441 #endif
1442     lock_ReleaseWrite(&cm_scacheLock);
1443 }
1444
1445 void cm_ReleaseSCacheNoLock(cm_scache_t *scp)
1446 {
1447     osi_assert(scp != NULL);
1448     if (scp->refCount == 0)
1449         osi_Log1(afsd_logp,"cm_ReleaseSCacheNoLock about to panic scp 0x%x",scp);
1450     osi_assert(scp->refCount-- >= 0);
1451 #ifdef DEBUG_REFCOUNT
1452     osi_Log2(afsd_logp,"cm_ReleaseSCacheNoLock scp 0x%p ref %d",scp,scp->refCount);
1453 #endif
1454 }
1455
1456 void cm_ReleaseSCache(cm_scache_t *scp)
1457 {
1458     osi_assert(scp != NULL);
1459     lock_ObtainWrite(&cm_scacheLock);
1460     if (scp->refCount == 0)
1461         osi_Log1(afsd_logp,"cm_ReleaseSCache about to panic scp 0x%x",scp);
1462     osi_assert(scp->refCount != 0);
1463     scp->refCount--;
1464 #ifdef DEBUG_REFCOUNT
1465     osi_Log2(afsd_logp,"cm_ReleaseSCache scp 0x%p ref %d",scp,scp->refCount);
1466 #endif
1467     lock_ReleaseWrite(&cm_scacheLock);
1468 }
1469
1470 /* just look for the scp entry to get filetype */
1471 /* doesn't need to be perfectly accurate, so locking doesn't matter too much */
1472 int cm_FindFileType(cm_fid_t *fidp)
1473 {
1474     long hash;
1475     cm_scache_t *scp;
1476         
1477     hash = CM_SCACHE_HASH(fidp);
1478         
1479     osi_assert(fidp->cell != 0);
1480
1481     lock_ObtainWrite(&cm_scacheLock);
1482     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
1483         if (cm_FidCmp(fidp, &scp->fid) == 0) {
1484             lock_ReleaseWrite(&cm_scacheLock);
1485             return scp->fileType;
1486         }
1487     }
1488     lock_ReleaseWrite(&cm_scacheLock);
1489     return 0;
1490 }
1491
1492 /* dump all scp's that have reference count > 0 to a file. 
1493  * cookie is used to identify this batch for easy parsing, 
1494  * and it a string provided by a caller 
1495  */
1496 int cm_DumpSCache(FILE *outputFile, char *cookie, int lock)
1497 {
1498     int zilch;
1499     cm_scache_t *scp;
1500     char output[1024];
1501     int i;
1502   
1503     if (lock)
1504         lock_ObtainRead(&cm_scacheLock);
1505   
1506     sprintf(output, "%s - dumping scache - cm_data.currentSCaches=%d, cm_data.maxSCaches=%d\n", cookie, cm_data.currentSCaches, cm_data.maxSCaches);
1507     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1508   
1509     for (scp = cm_data.scacheLRULastp; scp; scp = (cm_scache_t *) osi_QPrev(&scp->q)) 
1510     {
1511         if (scp->refCount != 0)
1512         {
1513             sprintf(output, "%s fid (cell=%d, volume=%d, vnode=%d, unique=%d) refCount=%u\n", 
1514                     cookie, scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique, 
1515                     scp->refCount);
1516             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1517         }
1518     }
1519   
1520     sprintf(output, "%s - dumping cm_data.hashTable - cm_data.hashTableSize=%d\n", cookie, cm_data.hashTableSize);
1521     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1522   
1523     for (i = 0; i < cm_data.hashTableSize; i++)
1524     {
1525         for(scp = cm_data.hashTablep[i]; scp; scp=scp->nextp) 
1526         {
1527             if (scp->refCount != 0)
1528             {
1529                 sprintf(output, "%s scp=0x%p, hash=%d, fid (cell=%d, volume=%d, vnode=%d, unique=%d) refCount=%u\n", 
1530                          cookie, scp, i, scp->fid.cell, scp->fid.volume, scp->fid.vnode, 
1531                          scp->fid.unique, scp->refCount);
1532                 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1533             }
1534         }
1535     }
1536
1537     sprintf(output, "%s - Done dumping scache.\n", cookie);
1538     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1539   
1540     if (lock)
1541         lock_ReleaseRead(&cm_scacheLock);       
1542     return (0);     
1543 }
1544