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