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