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