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