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