clean-platform-20071109
[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 = osi_Time();
496
497     lock_ObtainWrite(&cm_scacheLock);
498     for ( scp = cm_data.allSCachesp; scp; scp = scp->allNextp ) {
499         if (scp->cbServerp)
500             scp->cbExpires = now+1;
501     }
502     lock_ReleaseWrite(&cm_scacheLock);
503 }
504
505 long
506 cm_ShutdownSCache(void)
507 {
508     cm_scache_t * scp;
509
510     lock_ObtainWrite(&cm_scacheLock);
511
512     for ( scp = cm_data.allSCachesp; scp;
513           scp = scp->allNextp ) {
514         if (scp->randomACLp) {
515             lock_ObtainMutex(&scp->mx);
516             cm_FreeAllACLEnts(scp);
517             lock_ReleaseMutex(&scp->mx);
518         }
519
520         if (scp->cbServerp) {
521             cm_PutServer(scp->cbServerp);
522             scp->cbServerp = NULL;
523         }
524         scp->cbExpires = 0;
525         scp->flags &= ~CM_SCACHEFLAG_CALLBACK;
526
527 #ifdef USE_BPLUS
528         if (scp->dirBplus)
529             freeBtree(scp->dirBplus);
530         scp->dirBplus = NULL;
531         scp->dirDataVersion = -1;
532         lock_FinalizeRWLock(&scp->dirlock);
533 #endif
534         lock_FinalizeMutex(&scp->mx);
535         lock_FinalizeRWLock(&scp->bufCreateLock);
536     }
537     lock_ReleaseWrite(&cm_scacheLock);
538
539     cm_GiveUpAllCallbacksAllServers(FALSE);
540
541     return cm_dnlcShutdown();
542 }
543
544 void cm_InitSCache(int newFile, long maxSCaches)
545 {
546     static osi_once_t once;
547         
548     if (osi_Once(&once)) {
549         lock_InitializeRWLock(&cm_scacheLock, "cm_scacheLock");
550         if ( newFile ) {
551             memset(cm_data.scacheHashTablep, 0, sizeof(cm_scache_t *) * cm_data.scacheHashTableSize);
552             cm_data.allSCachesp = NULL;
553             cm_data.currentSCaches = 0;
554             cm_data.maxSCaches = maxSCaches;
555             cm_data.scacheLRUFirstp = cm_data.scacheLRULastp = NULL;
556         } else {
557             cm_scache_t * scp;
558
559             for ( scp = cm_data.allSCachesp; scp;
560                   scp = scp->allNextp ) {
561                 lock_InitializeMutex(&scp->mx, "cm_scache_t mutex");
562                 lock_InitializeRWLock(&scp->bufCreateLock, "cm_scache_t bufCreateLock");
563 #ifdef USE_BPLUS
564                 lock_InitializeRWLock(&scp->dirlock, "cm_scache_t dirlock");
565 #endif
566                 scp->cbServerp = NULL;
567                 scp->cbExpires = 0;
568                 scp->fileLocksH = NULL;
569                 scp->fileLocksT = NULL;
570                 scp->serverLock = (-1);
571                 scp->lastRefreshCycle = 0;
572                 scp->exclusiveLocks = 0;
573                 scp->sharedLocks = 0;
574                 scp->openReads = 0;
575                 scp->openWrites = 0;
576                 scp->openShares = 0;
577                 scp->openExcls = 0;
578                 scp->waitCount = 0;
579 #ifdef USE_BPLUS
580                 scp->dirBplus = NULL;
581                 scp->dirDataVersion = -1;
582 #endif
583                 scp->waitQueueT = NULL;
584                 scp->flags &= ~CM_SCACHEFLAG_WAITING;
585             }
586         }
587         cm_allFileLocks = NULL;
588         cm_freeFileLocks = NULL;
589         cm_lockRefreshCycle = 0;
590         cm_fakeSCacheInit(newFile);
591         cm_allFreeWaiters = NULL;
592         cm_dnlcInit(newFile);
593         osi_EndOnce(&once);
594     }
595 }
596
597 /* version that doesn't bother creating the entry if we don't find it */
598 cm_scache_t *cm_FindSCache(cm_fid_t *fidp)
599 {
600     long hash;
601     cm_scache_t *scp;
602
603     hash = CM_SCACHE_HASH(fidp);
604
605     if (fidp->cell == 0) {
606         return NULL;
607     }
608
609     lock_ObtainWrite(&cm_scacheLock);
610     for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
611         if (cm_FidCmp(fidp, &scp->fid) == 0) {
612             cm_HoldSCacheNoLock(scp);
613             cm_AdjustScacheLRU(scp);
614             lock_ReleaseWrite(&cm_scacheLock);
615             return scp;
616         }
617     }
618     lock_ReleaseWrite(&cm_scacheLock);
619     return NULL;
620 }
621
622 #ifdef DEBUG_REFCOUNT
623 long cm_GetSCacheDbg(cm_fid_t *fidp, cm_scache_t **outScpp, cm_user_t *userp,
624                   cm_req_t *reqp, char * file, long line)
625 #else
626 long cm_GetSCache(cm_fid_t *fidp, cm_scache_t **outScpp, cm_user_t *userp,
627                   cm_req_t *reqp)
628 #endif
629 {
630     long hash;
631     cm_scache_t *scp;
632     long code;
633     cm_volume_t *volp = NULL;
634     cm_cell_t *cellp;
635     char* mp = NULL;
636     int special; // yj: boolean variable to test if file is on root.afs
637     int isRoot;
638     extern cm_fid_t cm_rootFid;
639         
640     hash = CM_SCACHE_HASH(fidp);
641         
642     osi_assertx(fidp->cell != 0, "unassigned cell value");
643
644     if (fidp->cell== cm_data.rootFid.cell && 
645          fidp->volume==cm_data.rootFid.volume &&
646          fidp->vnode==0x0 && fidp->unique==0x0)
647     {
648         osi_Log0(afsd_logp,"cm_GetSCache called with root cell/volume and vnode=0 and unique=0");
649     }
650
651     // yj: check if we have the scp, if so, we don't need
652     // to do anything else
653     lock_ObtainWrite(&cm_scacheLock);
654     for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
655         if (cm_FidCmp(fidp, &scp->fid) == 0) {
656 #ifdef DEBUG_REFCOUNT
657             afsi_log("%s:%d cm_GetSCache (1) outScpp 0x%p ref %d", file, line, scp, scp->refCount);
658             osi_Log1(afsd_logp,"cm_GetSCache (1) outScpp 0x%p", scp);
659 #endif
660             cm_HoldSCacheNoLock(scp);
661             *outScpp = scp;
662             cm_AdjustScacheLRU(scp);
663             lock_ReleaseWrite(&cm_scacheLock);
664             return 0;
665         }
666     }
667
668     // yj: when we get here, it means we don't have an scp
669     // so we need to either load it or fake it, depending
670     // on whether the file is "special", see below.
671
672     // yj: if we're trying to get an scp for a file that's
673     // on root.afs of homecell, we want to handle it specially
674     // because we have to fill in the status stuff 'coz we
675     // don't want trybulkstat to fill it in for us
676 #ifdef AFS_FREELANCE_CLIENT
677     special = (fidp->cell==AFS_FAKE_ROOT_CELL_ID && 
678                fidp->volume==AFS_FAKE_ROOT_VOL_ID &&
679                !(fidp->vnode==0x1 && fidp->unique==0x1));
680     isRoot = (fidp->cell==AFS_FAKE_ROOT_CELL_ID && 
681               fidp->volume==AFS_FAKE_ROOT_VOL_ID &&
682               fidp->vnode==0x1 && fidp->unique==0x1);
683     if (cm_freelanceEnabled && isRoot) {
684         osi_Log0(afsd_logp,"cm_GetSCache Freelance and isRoot");
685         /* freelance: if we are trying to get the root scp for the first
686          * time, we will just put in a place holder entry. 
687          */
688         volp = NULL;
689     }
690           
691     if (cm_freelanceEnabled && special) {
692         osi_Log0(afsd_logp,"cm_GetSCache Freelance and special");
693         if (fidp->vnode > 1 && fidp->vnode <= cm_noLocalMountPoints + 2) {
694             lock_ObtainMutex(&cm_Freelance_Lock);
695             mp =(cm_localMountPoints+fidp->vnode-2)->mountPointStringp;
696             lock_ReleaseMutex(&cm_Freelance_Lock);
697         } else {
698             mp = "";
699         }
700         scp = cm_GetNewSCache();
701         if (scp == NULL) {
702             osi_Log0(afsd_logp,"cm_GetSCache unable to obtain *new* scache entry");
703             lock_ReleaseWrite(&cm_scacheLock);
704             return CM_ERROR_WOULDBLOCK;
705         }
706
707 #if not_too_dangerous
708         /* dropping the cm_scacheLock allows more than one thread
709          * to obtain the same cm_scache_t from the LRU list.  Since
710          * the refCount is known to be zero at this point we have to
711          * assume that no one else is using the one this is returned.
712          */
713         lock_ReleaseWrite(&cm_scacheLock);
714         lock_ObtainMutex(&scp->mx);
715         lock_ObtainWrite(&cm_scacheLock);
716 #endif
717         scp->fid = *fidp;
718         scp->volp = cm_data.rootSCachep->volp;
719         cm_GetVolume(scp->volp);        /* grab an additional reference */
720         scp->dotdotFid.cell=AFS_FAKE_ROOT_CELL_ID;
721         scp->dotdotFid.volume=AFS_FAKE_ROOT_VOL_ID;
722         scp->dotdotFid.unique=1;
723         scp->dotdotFid.vnode=1;
724         scp->flags |= (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO);
725         scp->nextp=cm_data.scacheHashTablep[hash];
726         cm_data.scacheHashTablep[hash]=scp;
727         scp->flags |= CM_SCACHEFLAG_INHASH;
728         scp->refCount = 1;
729         osi_Log1(afsd_logp,"cm_GetSCache (freelance) sets refCount to 1 scp 0x%x", scp);
730         if (fidp->vnode > 1 && fidp->vnode <= cm_noLocalMountPoints + 2)
731             scp->fileType = (cm_localMountPoints+fidp->vnode-2)->fileType;
732         else 
733             scp->fileType = CM_SCACHETYPE_INVALID;
734
735         lock_ObtainMutex(&cm_Freelance_Lock);
736         scp->length.LowPart = (DWORD)strlen(mp)+4;
737         scp->length.HighPart = 0;
738         strncpy(scp->mountPointStringp,mp,MOUNTPOINTLEN);
739         scp->mountPointStringp[MOUNTPOINTLEN-1] = '\0';
740         lock_ReleaseMutex(&cm_Freelance_Lock);
741
742         scp->owner=0x0;
743         scp->unixModeBits=0777;
744         scp->clientModTime=FakeFreelanceModTime;
745         scp->serverModTime=FakeFreelanceModTime;
746         scp->parentUnique = 0x1;
747         scp->parentVnode=0x1;
748         scp->group=0;
749         scp->dataVersion=cm_data.fakeDirVersion;
750         scp->lockDataVersion=-1; /* no lock yet */
751 #if not_too_dangerous
752         lock_ReleaseMutex(&scp->mx);
753 #endif
754         *outScpp = scp;
755         lock_ReleaseWrite(&cm_scacheLock);
756 #ifdef DEBUG_REFCOUNT
757         afsi_log("%s:%d cm_GetSCache (2) outScpp 0x%p ref %d", file, line, scp, scp->refCount);
758         osi_Log1(afsd_logp,"cm_GetSCache (2) outScpp 0x%p", scp);
759 #endif
760         return 0;
761     }
762     // end of yj code
763 #endif /* AFS_FREELANCE_CLIENT */
764
765     /* otherwise, we need to find the volume */
766     if (!cm_freelanceEnabled || !isRoot) {
767         lock_ReleaseWrite(&cm_scacheLock);      /* for perf. reasons */
768         cellp = cm_FindCellByID(fidp->cell);
769         if (!cellp) 
770             return CM_ERROR_NOSUCHCELL;
771
772         code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, CM_GETVOL_FLAG_CREATE, &volp);
773         if (code) 
774             return code;
775         lock_ObtainWrite(&cm_scacheLock);
776     }
777         
778     /* otherwise, we have the volume, now reverify that the scp doesn't
779      * exist, and proceed.
780      */
781     for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
782         if (cm_FidCmp(fidp, &scp->fid) == 0) {
783 #ifdef DEBUG_REFCOUNT
784             afsi_log("%s:%d cm_GetSCache (3) outScpp 0x%p ref %d", file, line, scp, scp->refCount);
785             osi_Log1(afsd_logp,"cm_GetSCache (3) outScpp 0x%p", scp);
786 #endif
787             cm_HoldSCacheNoLock(scp);
788             osi_assertx(scp->volp == volp, "cm_scache_t volume has unexpected value");
789             cm_AdjustScacheLRU(scp);
790             lock_ReleaseWrite(&cm_scacheLock);
791             if (volp)
792                 cm_PutVolume(volp);
793             *outScpp = scp;
794             return 0;
795         }
796     }
797         
798     /* now, if we don't have the fid, recycle something */
799     scp = cm_GetNewSCache();
800     if (scp == NULL) {
801         osi_Log0(afsd_logp,"cm_GetNewSCache unable to obtain *new* scache entry");
802         lock_ReleaseWrite(&cm_scacheLock);
803         if (volp)
804             cm_PutVolume(volp);
805         return CM_ERROR_WOULDBLOCK;
806     }
807     osi_Log2(afsd_logp,"cm_GetNewSCache returns scp 0x%x flags 0x%x", scp, scp->flags);
808
809     osi_assertx(!(scp->flags & CM_SCACHEFLAG_INHASH), "CM_SCACHEFLAG_INHASH set");
810
811 #if not_too_dangerous
812     /* dropping the cm_scacheLock allows more than one thread
813      * to obtain the same cm_scache_t from the LRU list.  Since
814      * the refCount is known to be zero at this point we have to
815      * assume that no one else is using the one this is returned.
816      */
817     lock_ReleaseWrite(&cm_scacheLock);
818     lock_ObtainMutex(&scp->mx);
819     lock_ObtainWrite(&cm_scacheLock);
820 #endif
821     scp->fid = *fidp;
822     scp->volp = volp;   /* a held reference */
823
824     if (!cm_freelanceEnabled || !isRoot) {
825         /* if this scache entry represents a volume root then we need 
826          * to copy the dotdotFipd from the volume structure where the 
827          * "master" copy is stored (defect 11489)
828          */
829         if (scp->fid.vnode == 1 && scp->fid.unique == 1) {
830             scp->dotdotFid = volp->dotdotFid;
831         }
832           
833         if (volp->ro.ID == fidp->volume)
834             scp->flags |= (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO);
835         else if (volp->bk.ID == fidp->volume)
836             scp->flags |= CM_SCACHEFLAG_RO;
837     }
838     scp->nextp = cm_data.scacheHashTablep[hash];
839     cm_data.scacheHashTablep[hash] = scp;
840     scp->flags |= CM_SCACHEFLAG_INHASH;
841     scp->refCount = 1;
842     osi_Log1(afsd_logp,"cm_GetSCache sets refCount to 1 scp 0x%x", scp);
843 #if not_too_dangerous
844     lock_ReleaseMutex(&scp->mx);
845 #endif
846
847     /* XXX - The following fields in the cm_scache are 
848      * uninitialized:
849      *   fileType
850      *   parentVnode
851      *   parentUnique
852      */
853     lock_ReleaseWrite(&cm_scacheLock);
854         
855     /* now we have a held scache entry; just return it */
856     *outScpp = scp;
857 #ifdef DEBUG_REFCOUNT
858     afsi_log("%s:%d cm_GetSCache (4) outScpp 0x%p ref %d", file, line, scp, scp->refCount);
859     osi_Log1(afsd_logp,"cm_GetSCache (4) outScpp 0x%p", scp);
860 #endif
861     return 0;
862 }
863
864 /* Returns a held reference to the scache's parent 
865  * if it exists */
866 cm_scache_t * cm_FindSCacheParent(cm_scache_t * scp)
867 {
868     long code = 0;
869     int i;
870     cm_fid_t    parent_fid;
871     cm_scache_t * pscp = NULL;
872
873     lock_ObtainRead(&cm_scacheLock);
874     parent_fid = scp->fid;
875     parent_fid.vnode = scp->parentVnode;
876     parent_fid.unique = scp->parentUnique;
877
878     if (cm_FidCmp(&scp->fid, &parent_fid)) {
879         i = CM_SCACHE_HASH(&parent_fid);
880         for (pscp = cm_data.scacheHashTablep[i]; pscp; pscp = pscp->nextp) {
881             if (!cm_FidCmp(&pscp->fid, &parent_fid)) {
882                 cm_HoldSCacheNoLock(pscp);
883                 break;
884             }
885         }
886     }
887
888     lock_ReleaseRead(&cm_scacheLock);
889
890     return pscp;
891 }
892
893 void cm_SyncOpAddToWaitQueue(cm_scache_t * scp, afs_int32 flags, cm_buf_t * bufp)
894 {
895     cm_scache_waiter_t * w;
896
897     lock_ObtainWrite(&cm_scacheLock);
898     if (cm_allFreeWaiters == NULL) {
899         w = malloc(sizeof(*w));
900         memset(w, 0, sizeof(*w));
901     } else {
902         w = (cm_scache_waiter_t *) cm_allFreeWaiters;
903         osi_QRemove(&cm_allFreeWaiters, (osi_queue_t *) w);
904     }
905
906     w->threadId = thrd_Current();
907     w->scp = scp;
908     cm_HoldSCacheNoLock(scp);
909     w->flags = flags;
910     w->bufp = bufp;
911
912     osi_QAddT(&scp->waitQueueH, &scp->waitQueueT, (osi_queue_t *) w);
913     lock_ReleaseWrite(&cm_scacheLock);
914
915     osi_Log2(afsd_logp, "cm_SyncOpAddToWaitQueue : Adding thread to wait queue scp 0x%p w 0x%p", scp, w);
916 }
917
918 int cm_SyncOpCheckContinue(cm_scache_t * scp, afs_int32 flags, cm_buf_t * bufp)
919 {
920     cm_scache_waiter_t * w;
921     int this_is_me;
922
923     osi_Log0(afsd_logp, "cm_SyncOpCheckContinue checking for continuation");
924
925     lock_ObtainRead(&cm_scacheLock);
926     for (w = (cm_scache_waiter_t *)scp->waitQueueH;
927          w;
928          w = (cm_scache_waiter_t *)osi_QNext((osi_queue_t *) w)) {
929         if (w->flags == flags && w->bufp == bufp) {
930             break;
931         }
932     }
933
934     osi_assertx(w != NULL, "null cm_scache_waiter_t");
935     this_is_me = (w->threadId == thrd_Current());
936     lock_ReleaseRead(&cm_scacheLock);
937
938     if (!this_is_me) {
939         osi_Log1(afsd_logp, "cm_SyncOpCheckContinue MISS: Waiter 0x%p", w);
940         return 0;
941     }
942
943     osi_Log1(afsd_logp, "cm_SyncOpCheckContinue HIT: Waiter 0x%p", w);
944
945     lock_ObtainWrite(&cm_scacheLock);
946     osi_QRemoveHT(&scp->waitQueueH, &scp->waitQueueT, (osi_queue_t *) w);
947     cm_ReleaseSCacheNoLock(scp);
948     memset(w, 0, sizeof(*w));
949     osi_QAdd(&cm_allFreeWaiters, (osi_queue_t *) w);
950     lock_ReleaseWrite(&cm_scacheLock);
951
952     return 1;
953 }
954
955
956 /* synchronize a fetch, store, read, write, fetch status or store status.
957  * Called with scache mutex held, and returns with it held, but temporarily
958  * drops it during the fetch.
959  * 
960  * At most one flag can be on in flags, if this is an RPC request.
961  *
962  * Also, if we're fetching or storing data, we must ensure that we have a buffer.
963  *
964  * There are a lot of weird restrictions here; here's an attempt to explain the
965  * rationale for the concurrency restrictions implemented in this function.
966  *
967  * First, although the file server will break callbacks when *another* machine
968  * modifies a file or status block, the client itself is responsible for
969  * concurrency control on its own requests.  Callback breaking events are rare,
970  * and simply invalidate any concurrent new status info.
971  *
972  * In the absence of callback breaking messages, we need to know how to
973  * synchronize incoming responses describing updates to files.  We synchronize
974  * operations that update the data version by comparing the data versions.
975  * However, updates that do not update the data, but only the status, can't be
976  * synchronized with fetches or stores, since there's nothing to compare
977  * to tell which operation executed first at the server.
978  *
979  * Thus, we can allow multiple ops that change file data, or dir data, and
980  * fetches.  However, status storing ops have to be done serially.
981  *
982  * Furthermore, certain data-changing ops are incompatible: we can't read or
983  * write a buffer while doing a truncate.  We can't read and write the same
984  * buffer at the same time, or write while fetching or storing, or read while
985  * fetching a buffer (this may change).  We can't fetch and store at the same
986  * time, either.
987  *
988  * With respect to status, we can't read and write at the same time, read while
989  * fetching, write while fetching or storing, or fetch and store at the same time.
990  *
991  * We can't allow a get callback RPC to run in concurrently with something that
992  * will return updated status, since we could start a call, have the server
993  * return status, have another machine make an update to the status (which
994  * doesn't change serverModTime), have the original machine get a new callback,
995  * and then have the original machine merge in the early, old info from the
996  * first call.  At this point, the easiest way to avoid this problem is to have
997  * getcallback calls conflict with all others for the same vnode.  Other calls
998  * to cm_MergeStatus that aren't associated with calls to cm_SyncOp on the same
999  * vnode must be careful not to merge in their status unless they have obtained
1000  * a callback from the start of their call.
1001  *
1002  * Note added 1/23/96
1003  * Concurrent StoreData RPC's can cause trouble if the file is being extended.
1004  * Each such RPC passes a FileLength parameter, which the server uses to do
1005  * pre-truncation if necessary.  So if two RPC's are processed out of order at
1006  * the server, the one with the smaller FileLength will be processed last,
1007  * possibly resulting in a bogus truncation.  The simplest way to avoid this
1008  * is to serialize all StoreData RPC's.  This is the reason we defined
1009  * CM_SCACHESYNC_STOREDATA_EXCL and CM_SCACHEFLAG_DATASTORING.
1010  */
1011 long cm_SyncOp(cm_scache_t *scp, cm_buf_t *bufp, cm_user_t *userp, cm_req_t *reqp,
1012                afs_uint32 rights, afs_uint32 flags)
1013 {
1014     osi_queueData_t *qdp;
1015     long code;
1016     cm_buf_t *tbufp;
1017     afs_uint32 outRights;
1018     int bufLocked;
1019     afs_uint32 sleep_scp_flags = 0;
1020     afs_uint32 sleep_buf_cmflags = 0;
1021     afs_uint32 sleep_scp_bufs = 0;
1022     int wakeupCycle;
1023
1024     /* lookup this first */
1025     bufLocked = flags & CM_SCACHESYNC_BUFLOCKED;
1026
1027     if (bufp)
1028         osi_assertx(bufp->refCount > 0, "cm_buf_t refCount 0");
1029
1030
1031     /* Do the access check.  Now we don't really do the access check
1032      * atomically, since the caller doesn't expect the parent dir to be
1033      * returned locked, and that is what we'd have to do to prevent a
1034      * callback breaking message on the parent due to a setacl call from
1035      * being processed while we're running.  So, instead, we check things
1036      * here, and if things look fine with the access, we proceed to finish
1037      * the rest of this check.  Sort of a hack, but probably good enough.
1038      */
1039
1040     while (1) {
1041         if (flags & CM_SCACHESYNC_FETCHSTATUS) {
1042             /* if we're bringing in a new status block, ensure that
1043              * we aren't already doing so, and that no one is
1044              * changing the status concurrently, either.  We need
1045              * to do this, even if the status is of a different
1046              * type, since we don't have the ability to figure out,
1047              * in the AFS 3 protocols, which status-changing
1048              * operation ran first, or even which order a read and
1049              * a write occurred in.
1050              */
1051             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
1052                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
1053                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want FETCHSTATUS", scp);
1054                 goto sleep;
1055             }
1056         }
1057         if (flags & (CM_SCACHESYNC_STORESIZE | CM_SCACHESYNC_STORESTATUS
1058                       | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_GETCALLBACK)) {
1059             /* if we're going to make an RPC to change the status, make sure
1060              * that no one is bringing in or sending out the status.
1061              */
1062             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING |
1063                               CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
1064                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
1065                 goto sleep;
1066             }
1067             if (scp->bufReadsp || scp->bufWritesp) {
1068                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is bufRead|bufWrite want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
1069                 goto sleep;
1070             }
1071         }
1072         if (flags & CM_SCACHESYNC_FETCHDATA) {
1073             /* if we're bringing in a new chunk of data, make sure that
1074              * nothing is happening to that chunk, and that we aren't
1075              * changing the basic file status info, either.
1076              */
1077             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
1078                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
1079                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want FETCHDATA", scp);
1080                 goto sleep;
1081             }
1082             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING | CM_BUF_CMWRITING))) {
1083                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING|BUF_CMWRITING want FETCHDATA", scp, bufp);
1084                 goto sleep;
1085             }
1086         }
1087         if (flags & CM_SCACHESYNC_STOREDATA) {
1088             /* same as fetch data */
1089             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
1090                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
1091                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STOREDATA", scp);
1092                 goto sleep;
1093             }
1094             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING | CM_BUF_CMWRITING))) {
1095                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING|BUF_CMWRITING want STOREDATA", scp, bufp);
1096                 goto sleep;
1097             }
1098         }
1099
1100         if (flags & CM_SCACHESYNC_STOREDATA_EXCL) {
1101             /* Don't allow concurrent StoreData RPC's */
1102             if (scp->flags & CM_SCACHEFLAG_DATASTORING) {
1103                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is DATASTORING want STOREDATA_EXCL", scp);
1104                 goto sleep;
1105             }
1106         }
1107
1108         if (flags & CM_SCACHESYNC_ASYNCSTORE) {
1109             /* Don't allow more than one BKG store request */
1110             if (scp->flags & CM_SCACHEFLAG_ASYNCSTORING) {
1111                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is ASYNCSTORING want ASYNCSTORE", scp);
1112                 goto sleep;
1113             }
1114         }
1115
1116         if (flags & CM_SCACHESYNC_LOCK) {
1117             /* Don't allow concurrent fiddling with lock lists */
1118             if (scp->flags & CM_SCACHEFLAG_LOCKING) {
1119                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is LOCKING want LOCK", scp);
1120                 goto sleep;
1121             }
1122         }
1123
1124         /* now the operations that don't correspond to making RPCs */
1125         if (flags & CM_SCACHESYNC_GETSTATUS) {
1126             /* we can use the status that's here, if we're not
1127              * bringing in new status.
1128              */
1129             if (scp->flags & (CM_SCACHEFLAG_FETCHING)) {
1130                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want GETSTATUS", scp);
1131                 goto sleep;
1132             }
1133         }
1134         if (flags & CM_SCACHESYNC_SETSTATUS) {
1135             /* we can make a change to the local status, as long as
1136              * the status isn't changing now.
1137              *
1138              * If we're fetching or storing a chunk of data, we can
1139              * change the status locally, since the fetch/store
1140              * operations don't change any of the data that we're
1141              * changing here.
1142              */
1143             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING | CM_SCACHEFLAG_SIZESTORING)) {
1144                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING want SETSTATUS", scp);
1145                 goto sleep;
1146             }
1147         }
1148         if (flags & CM_SCACHESYNC_READ) {
1149             /* we're going to read the data, make sure that the
1150              * status is available, and that the data is here.  It
1151              * is OK to read while storing the data back.
1152              */
1153             if (scp->flags & CM_SCACHEFLAG_FETCHING) {
1154                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want READ", scp);
1155                 goto sleep;
1156             }
1157             if (bufp && ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == CM_BUF_CMFETCHING)) {
1158                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING want READ", scp, bufp);
1159                 goto sleep;
1160             }
1161             if (bufp && (bufp->cmFlags & CM_BUF_CMWRITING)) {
1162                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMWRITING want READ", scp, bufp);
1163                 goto sleep;
1164             }
1165         }
1166         if (flags & CM_SCACHESYNC_WRITE) {
1167             /* don't write unless the status is stable and the chunk
1168              * is stable.
1169              */
1170             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
1171                                | CM_SCACHEFLAG_SIZESTORING)) {
1172                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING want WRITE", scp);
1173                 goto sleep;
1174             }
1175             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING |
1176                                           CM_BUF_CMSTORING |
1177                                           CM_BUF_CMWRITING))) {
1178                 osi_Log3(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is %s want WRITE",
1179                          scp, bufp,
1180                          ((bufp->cmFlags & CM_BUF_CMFETCHING) ? "CM_BUF_CMFETCHING":
1181                           ((bufp->cmFlags & CM_BUF_CMSTORING) ? "CM_BUF_CMSTORING" :
1182                            ((bufp->cmFlags & CM_BUF_CMWRITING) ? "CM_BUF_CMWRITING" :
1183                             "UNKNOWN!!!"))));
1184                 goto sleep;
1185             }
1186         }
1187
1188         // yj: modified this so that callback only checked if we're
1189         // not checking something on /afs
1190         /* fix the conditional to match the one in cm_HaveCallback */
1191         if ((flags & CM_SCACHESYNC_NEEDCALLBACK)
1192 #ifdef AFS_FREELANCE_CLIENT
1193              && (!cm_freelanceEnabled || 
1194                   !(scp->fid.vnode==0x1 && scp->fid.unique==0x1) ||
1195                   scp->fid.cell!=AFS_FAKE_ROOT_CELL_ID ||
1196                   scp->fid.volume!=AFS_FAKE_ROOT_VOL_ID ||
1197                   cm_fakeDirCallback < 2)
1198 #endif /* AFS_FREELANCE_CLIENT */
1199              ) {
1200             if ((flags & CM_SCACHESYNC_FORCECB) || !cm_HaveCallback(scp)) {
1201                 osi_Log1(afsd_logp, "CM SyncOp getting callback on scp 0x%p",
1202                           scp);
1203                 if (bufLocked) 
1204                     lock_ReleaseMutex(&bufp->mx);
1205                 code = cm_GetCallback(scp, userp, reqp, (flags & CM_SCACHESYNC_FORCECB)?1:0);
1206                 if (bufLocked) {
1207                     lock_ReleaseMutex(&scp->mx);
1208                     lock_ObtainMutex(&bufp->mx);
1209                     lock_ObtainMutex(&scp->mx);
1210                 }
1211                 if (code) 
1212                     return code;
1213                 flags &= ~CM_SCACHESYNC_FORCECB;        /* only force once */
1214                 continue;
1215             }
1216         }
1217
1218         if (rights) {
1219             /* can't check access rights without a callback */
1220             osi_assertx(flags & CM_SCACHESYNC_NEEDCALLBACK, "!CM_SCACHESYNC_NEEDCALLBACK");
1221
1222             if ((rights & PRSFS_WRITE) && (scp->flags & CM_SCACHEFLAG_RO))
1223                 return CM_ERROR_READONLY;
1224
1225             if (cm_HaveAccessRights(scp, userp, rights, &outRights)) {
1226                 if (~outRights & rights) 
1227                     return CM_ERROR_NOACCESS;
1228             }
1229             else {
1230                 /* we don't know the required access rights */
1231                 if (bufLocked) lock_ReleaseMutex(&bufp->mx);
1232                 code = cm_GetAccessRights(scp, userp, reqp);
1233                 if (bufLocked) {
1234                     lock_ReleaseMutex(&scp->mx);
1235                     lock_ObtainMutex(&bufp->mx);
1236                     lock_ObtainMutex(&scp->mx);
1237                 }
1238                 if (code) 
1239                     return code;
1240                 continue;
1241             }
1242         }
1243
1244         /* if we get here, we're happy */
1245         break;
1246
1247       sleep:
1248         /* first check if we're not supposed to wait: fail 
1249          * in this case, returning with everything still locked.
1250          */
1251         if (flags & CM_SCACHESYNC_NOWAIT) 
1252             return CM_ERROR_WOULDBLOCK;
1253
1254         /* These are used for minidump debugging */
1255         sleep_scp_flags = scp->flags;           /* so we know why we slept */
1256         sleep_buf_cmflags = bufp ? bufp->cmFlags : 0;
1257         sleep_scp_bufs = (scp->bufReadsp ? 1 : 0) | (scp->bufWritesp ? 2 : 0);
1258
1259         /* wait here, then try again */
1260         osi_Log1(afsd_logp, "CM SyncOp sleeping scp 0x%p", scp);
1261         if ( scp->flags & CM_SCACHEFLAG_WAITING ) {
1262             scp->waitCount++;
1263             scp->waitRequests++;
1264             osi_Log3(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING already set for 0x%p; %d threads; %d requests", 
1265                      scp, scp->waitCount, scp->waitRequests);
1266         } else {
1267             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING set for 0x%p", scp);
1268             scp->flags |= CM_SCACHEFLAG_WAITING;
1269             scp->waitCount = scp->waitRequests = 1;
1270         }
1271
1272         if (bufLocked) 
1273             lock_ReleaseMutex(&bufp->mx);
1274
1275         cm_SyncOpAddToWaitQueue(scp, flags, bufp);
1276         wakeupCycle = 0;
1277         do {
1278             if (wakeupCycle++ != 0)
1279                 lock_ObtainMutex(&scp->mx);
1280             osi_SleepM((LONG_PTR) &scp->flags, &scp->mx);
1281         } while (!cm_SyncOpCheckContinue(scp, flags, bufp));
1282
1283         smb_UpdateServerPriority();
1284
1285         if (bufLocked) 
1286             lock_ObtainMutex(&bufp->mx);
1287         lock_ObtainMutex(&scp->mx);
1288         scp->waitCount--;
1289         osi_Log3(afsd_logp, "CM SyncOp woke! scp 0x%p; still waiting %d threads of %d requests", 
1290                  scp, scp->waitCount, scp->waitRequests);
1291         if (scp->waitCount == 0) {
1292             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING reset for 0x%p", scp);
1293             scp->flags &= ~CM_SCACHEFLAG_WAITING;
1294             scp->waitRequests = 0;
1295         }
1296     } /* big while loop */
1297         
1298     /* now, update the recorded state for RPC-type calls */
1299     if (flags & CM_SCACHESYNC_FETCHSTATUS)
1300         scp->flags |= CM_SCACHEFLAG_FETCHING;
1301     if (flags & CM_SCACHESYNC_STORESTATUS)
1302         scp->flags |= CM_SCACHEFLAG_STORING;
1303     if (flags & CM_SCACHESYNC_STORESIZE)
1304         scp->flags |= CM_SCACHEFLAG_SIZESTORING;
1305     if (flags & CM_SCACHESYNC_GETCALLBACK)
1306         scp->flags |= CM_SCACHEFLAG_GETCALLBACK;
1307     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1308         scp->flags |= CM_SCACHEFLAG_DATASTORING;
1309     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1310         scp->flags |= CM_SCACHEFLAG_ASYNCSTORING;
1311     if (flags & CM_SCACHESYNC_LOCK)
1312         scp->flags |= CM_SCACHEFLAG_LOCKING;
1313
1314     /* now update the buffer pointer */
1315     if (flags & CM_SCACHESYNC_FETCHDATA) {
1316         /* ensure that the buffer isn't already in the I/O list */
1317         if (bufp) {
1318             for(qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1319                 tbufp = osi_GetQData(qdp);
1320                 osi_assertx(tbufp != bufp, "unexpected cm_buf_t value");
1321             }
1322         }
1323
1324         /* queue a held reference to the buffer in the "reading" I/O list */
1325         qdp = osi_QDAlloc();
1326         osi_SetQData(qdp, bufp);
1327         if (bufp) {
1328             buf_Hold(bufp);
1329             bufp->cmFlags |= CM_BUF_CMFETCHING;
1330         }
1331         osi_QAdd((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1332     }
1333
1334     if (flags & CM_SCACHESYNC_STOREDATA) {
1335         /* ensure that the buffer isn't already in the I/O list */
1336         if (bufp) {
1337             for(qdp = scp->bufWritesp; 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 "writing" I/O list */
1344         qdp = osi_QDAlloc();
1345         osi_SetQData(qdp, bufp);
1346         if (bufp) {
1347             buf_Hold(bufp);
1348             bufp->cmFlags |= CM_BUF_CMSTORING;
1349         }
1350         osi_QAdd((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1351     }
1352
1353     if (flags & CM_SCACHESYNC_WRITE) {
1354         /* mark the buffer as being written to. */
1355         if (bufp) {
1356             bufp->cmFlags |= CM_BUF_CMWRITING;
1357         }
1358     }
1359
1360     return 0;
1361 }
1362
1363 /* for those syncops that setup for RPCs.
1364  * Called with scache locked.
1365  */
1366 void cm_SyncOpDone(cm_scache_t *scp, cm_buf_t *bufp, afs_uint32 flags)
1367 {
1368     osi_queueData_t *qdp;
1369     cm_buf_t *tbufp;
1370
1371     lock_AssertMutex(&scp->mx);
1372
1373     /* now, update the recorded state for RPC-type calls */
1374     if (flags & CM_SCACHESYNC_FETCHSTATUS)
1375         scp->flags &= ~CM_SCACHEFLAG_FETCHING;
1376     if (flags & CM_SCACHESYNC_STORESTATUS)
1377         scp->flags &= ~CM_SCACHEFLAG_STORING;
1378     if (flags & CM_SCACHESYNC_STORESIZE)
1379         scp->flags &= ~CM_SCACHEFLAG_SIZESTORING;
1380     if (flags & CM_SCACHESYNC_GETCALLBACK)
1381         scp->flags &= ~CM_SCACHEFLAG_GETCALLBACK;
1382     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1383         scp->flags &= ~CM_SCACHEFLAG_DATASTORING;
1384     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1385         scp->flags &= ~CM_SCACHEFLAG_ASYNCSTORING;
1386     if (flags & CM_SCACHESYNC_LOCK)
1387         scp->flags &= ~CM_SCACHEFLAG_LOCKING;
1388
1389     /* now update the buffer pointer */
1390     if (flags & CM_SCACHESYNC_FETCHDATA) {
1391         int release = 0;
1392
1393         /* ensure that the buffer isn't already in the I/O list */
1394         for(qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1395             tbufp = osi_GetQData(qdp);
1396             if (tbufp == bufp) 
1397                 break;
1398         }
1399         if (qdp) {
1400             osi_QRemove((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1401             osi_QDFree(qdp);
1402             release = 1;
1403         }
1404         if (bufp) {
1405             bufp->cmFlags &= ~(CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED);
1406             if (bufp->flags & CM_BUF_WAITING) {
1407                 osi_Log2(afsd_logp, "CM SyncOpDone Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1408                 osi_Wakeup((LONG_PTR) &bufp);
1409             }
1410             if (release)
1411                 buf_Release(bufp);
1412         }
1413     }
1414
1415     /* now update the buffer pointer */
1416     if (flags & CM_SCACHESYNC_STOREDATA) {
1417         int release = 0;
1418         /* ensure that the buffer isn't already in the I/O list */
1419         for(qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1420             tbufp = osi_GetQData(qdp);
1421             if (tbufp == bufp) 
1422                 break;
1423         }
1424         if (qdp) {
1425             osi_QRemove((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1426             osi_QDFree(qdp);
1427             release = 1;
1428         }
1429         if (bufp) {
1430             bufp->cmFlags &= ~CM_BUF_CMSTORING;
1431             if (bufp->flags & CM_BUF_WAITING) {
1432                 osi_Log2(afsd_logp, "CM SyncOpDone Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1433                 osi_Wakeup((LONG_PTR) &bufp);
1434             }
1435             if (release)
1436                 buf_Release(bufp);
1437         }
1438     }
1439
1440     if (flags & CM_SCACHESYNC_WRITE) {
1441         if (bufp) {
1442             osi_assertx(bufp->cmFlags & CM_BUF_CMWRITING, "!CM_BUF_CMWRITING");
1443
1444             bufp->cmFlags &= ~CM_BUF_CMWRITING;
1445         }
1446     }
1447
1448     /* and wakeup anyone who is waiting */
1449     if (scp->flags & CM_SCACHEFLAG_WAITING) {
1450         osi_Log1(afsd_logp, "CM SyncOpDone Waking scp 0x%p", scp);
1451         osi_Wakeup((LONG_PTR) &scp->flags);
1452     }
1453 }       
1454
1455 /* merge in a response from an RPC.  The scp must be locked, and the callback
1456  * is optional.
1457  *
1458  * Don't overwrite any status info that is dirty, since we could have a store
1459  * operation (such as store data) that merges some info in, and we don't want
1460  * to lose the local updates.  Typically, there aren't many updates we do
1461  * locally, anyway, probably only mtime.
1462  *
1463  * There is probably a bug in here where a chmod (which doesn't change
1464  * serverModTime) that occurs between two fetches, both of whose responses are
1465  * handled after the callback breaking is done, but only one of whose calls
1466  * started before that, can cause old info to be merged from the first call.
1467  */
1468 void cm_MergeStatus(cm_scache_t *dscp, 
1469                     cm_scache_t *scp, AFSFetchStatus *statusp, 
1470                     AFSVolSync *volsyncp,
1471                     cm_user_t *userp, afs_uint32 flags)
1472 {
1473     // yj: i want to create some fake status for the /afs directory and the
1474     // entries under that directory
1475 #ifdef AFS_FREELANCE_CLIENT
1476     if (cm_freelanceEnabled && scp == cm_data.rootSCachep) {
1477         osi_Log0(afsd_logp,"cm_MergeStatus Freelance cm_data.rootSCachep");
1478         statusp->InterfaceVersion = 0x1;
1479         statusp->FileType = CM_SCACHETYPE_DIRECTORY;
1480         statusp->LinkCount = scp->linkCount;
1481         statusp->Length = cm_fakeDirSize;
1482         statusp->Length_hi = 0;
1483         statusp->DataVersion = cm_data.fakeDirVersion;
1484         statusp->Author = 0x1;
1485         statusp->Owner = 0x0;
1486         statusp->CallerAccess = 0x9;
1487         statusp->AnonymousAccess = 0x9;
1488         statusp->UnixModeBits = 0777;
1489         statusp->ParentVnode = 0x1;
1490         statusp->ParentUnique = 0x1;
1491         statusp->ResidencyMask = 0;
1492         statusp->ClientModTime = FakeFreelanceModTime;
1493         statusp->ServerModTime = FakeFreelanceModTime;
1494         statusp->Group = 0;
1495         statusp->SyncCounter = 0;
1496         statusp->dataVersionHigh = 0;
1497         statusp->errorCode = 0;
1498     }
1499 #endif /* AFS_FREELANCE_CLIENT */
1500
1501     if (statusp->errorCode != 0) {      
1502         scp->flags |= CM_SCACHEFLAG_EACCESS;
1503         osi_Log2(afsd_logp, "Merge, Failure scp %x code 0x%x", scp, statusp->errorCode);
1504
1505         scp->fileType = 0;      /* unknown */
1506
1507         scp->serverModTime = 0;
1508         scp->clientModTime = 0;
1509         scp->length.LowPart = 0;
1510         scp->length.HighPart = 0;
1511         scp->serverLength.LowPart = 0;
1512         scp->serverLength.HighPart = 0;
1513         scp->linkCount = 0;
1514         scp->owner = 0;
1515         scp->group = 0;
1516         scp->unixModeBits = 0;
1517         scp->anyAccess = 0;
1518         scp->dataVersion = 0;
1519
1520         if (dscp) {
1521             scp->parentVnode = dscp->fid.vnode;
1522             scp->parentUnique = dscp->fid.unique;
1523         } else {
1524             scp->parentVnode = 0;
1525             scp->parentUnique = 0;
1526         }
1527         return;
1528     } else {
1529         scp->flags &= ~CM_SCACHEFLAG_EACCESS;
1530     }
1531
1532     if (!(flags & CM_MERGEFLAG_FORCE)
1533          && statusp->DataVersion < (unsigned long) scp->dataVersion) {
1534         struct cm_cell *cellp;
1535
1536         cellp = cm_FindCellByID(scp->fid.cell);
1537         if (scp->cbServerp) {
1538             struct cm_volume *volp = NULL;
1539
1540             cm_GetVolumeByID(cellp, scp->fid.volume, userp,
1541                               (cm_req_t *) NULL, CM_GETVOL_FLAG_CREATE, &volp);
1542             osi_Log2(afsd_logp, "old data from server %x volume %s",
1543                       scp->cbServerp->addr.sin_addr.s_addr,
1544                       volp ? volp->namep : "(unknown)");
1545             if (volp)
1546                 cm_PutVolume(volp);
1547         }
1548         osi_Log3(afsd_logp, "Bad merge, scp %x, scp dv %d, RPC dv %d",
1549                   scp, scp->dataVersion, statusp->DataVersion);
1550         /* we have a number of data fetch/store operations running
1551          * concurrently, and we can tell which one executed last at the
1552          * server by its mtime.
1553          * Choose the one with the largest mtime, and ignore the rest.
1554          *
1555          * These concurrent calls are incompatible with setting the
1556          * mtime, so we won't have a locally changed mtime here.
1557          *
1558          * We could also have ACL info for a different user than usual,
1559          * in which case we have to do that part of the merge, anyway.
1560          * We won't have to worry about the info being old, since we
1561          * won't have concurrent calls
1562          * that change file status running from this machine.
1563          *
1564          * Added 3/17/98:  if we see data version regression on an RO
1565          * file, it's probably due to a server holding an out-of-date
1566          * replica, rather than to concurrent RPC's.  Failures to
1567          * release replicas are now flagged by the volserver, but only
1568          * since AFS 3.4 5.22, so there are plenty of clients getting
1569          * out-of-date replicas out there.
1570          *
1571          * If we discover an out-of-date replica, by this time it's too
1572          * late to go to another server and retry.  Also, we can't
1573          * reject the merge, because then there is no way for
1574          * GetAccess to do its work, and the caller gets into an
1575          * infinite loop.  So we just grin and bear it.
1576          */
1577         if (!(scp->flags & CM_SCACHEFLAG_RO))
1578             return;
1579     }       
1580
1581     scp->serverModTime = statusp->ServerModTime;
1582
1583     if (!(scp->mask & CM_SCACHEMASK_CLIENTMODTIME)) {
1584         scp->clientModTime = statusp->ClientModTime;
1585     }
1586     if (!(scp->mask & CM_SCACHEMASK_LENGTH)) {
1587         scp->length.LowPart = statusp->Length;
1588         scp->length.HighPart = statusp->Length_hi;
1589     }
1590
1591     scp->serverLength.LowPart = statusp->Length;
1592     scp->serverLength.HighPart = statusp->Length_hi;
1593
1594     scp->linkCount = statusp->LinkCount;
1595     scp->owner = statusp->Owner;
1596     scp->group = statusp->Group;
1597     scp->unixModeBits = statusp->UnixModeBits & 07777;
1598
1599     if (statusp->FileType == File)
1600         scp->fileType = CM_SCACHETYPE_FILE;
1601     else if (statusp->FileType == Directory)
1602         scp->fileType = CM_SCACHETYPE_DIRECTORY;
1603     else if (statusp->FileType == SymbolicLink) {
1604         if ((scp->unixModeBits & 0111) == 0)
1605             scp->fileType = CM_SCACHETYPE_MOUNTPOINT;
1606         else
1607             scp->fileType = CM_SCACHETYPE_SYMLINK;
1608     }       
1609     else {
1610         osi_Log2(afsd_logp, "Merge, Invalid File Type (%d), scp %x", statusp->FileType, scp);
1611         scp->fileType = CM_SCACHETYPE_INVALID;  /* invalid */
1612     }
1613     /* and other stuff */
1614     scp->parentVnode = statusp->ParentVnode;
1615     scp->parentUnique = statusp->ParentUnique;
1616         
1617     /* and merge in the private acl cache info, if this is more than the public
1618      * info; merge in the public stuff in any case.
1619      */
1620     scp->anyAccess = statusp->AnonymousAccess;
1621
1622     if (userp != NULL) {
1623         cm_AddACLCache(scp, userp, statusp->CallerAccess);
1624     }
1625
1626     if ((flags & CM_MERGEFLAG_STOREDATA) &&
1627         statusp->DataVersion - scp->dataVersion == 1) {
1628         cm_buf_t *bp;
1629
1630         for (bp = cm_data.buf_fileHashTablepp[BUF_FILEHASH(&scp->fid)]; bp; bp=bp->fileHashp)
1631         {
1632             if (cm_FidCmp(&scp->fid, &bp->fid) == 0 && 
1633                 bp->dataVersion == scp->dataVersion)
1634                 bp->dataVersion = statusp->DataVersion;
1635         }
1636
1637     }
1638     scp->dataVersion = statusp->DataVersion;
1639 }
1640
1641 /* note that our stat cache info is incorrect, so force us eventually
1642  * to stat the file again.  There may be dirty data associated with
1643  * this vnode, and we want to preserve that information.
1644  *
1645  * This function works by simply simulating a loss of the callback.
1646  *
1647  * This function must be called with the scache locked.
1648  */
1649 void cm_DiscardSCache(cm_scache_t *scp)
1650 {
1651     lock_AssertMutex(&scp->mx);
1652     if (scp->cbServerp) {
1653         cm_PutServer(scp->cbServerp);
1654         scp->cbServerp = NULL;
1655     }
1656     scp->cbExpires = 0;
1657     scp->flags &= ~CM_SCACHEFLAG_CALLBACK;
1658     cm_dnlcPurgedp(scp);
1659     cm_dnlcPurgevp(scp);
1660     cm_FreeAllACLEnts(scp);
1661
1662     /* Force mount points and symlinks to be re-evaluated */
1663     scp->mountPointStringp[0] = '\0';
1664 }
1665
1666 void cm_AFSFidFromFid(AFSFid *afsFidp, cm_fid_t *fidp)
1667 {
1668     afsFidp->Volume = fidp->volume;
1669     afsFidp->Vnode = fidp->vnode;
1670     afsFidp->Unique = fidp->unique;
1671 }       
1672
1673 #ifdef DEBUG_REFCOUNT
1674 void cm_HoldSCacheNoLockDbg(cm_scache_t *scp, char * file, long line)
1675 #else
1676 void cm_HoldSCacheNoLock(cm_scache_t *scp)
1677 #endif
1678 {
1679     osi_assertx(scp != NULL, "null cm_scache_t");
1680     scp->refCount++;
1681 #ifdef DEBUG_REFCOUNT
1682     osi_Log2(afsd_logp,"cm_HoldSCacheNoLock scp 0x%p ref %d",scp, scp->refCount);
1683     afsi_log("%s:%d cm_HoldSCacheNoLock scp 0x%p, ref %d", file, line, scp, scp->refCount);
1684 #endif
1685 }
1686
1687 #ifdef DEBUG_REFCOUNT
1688 void cm_HoldSCacheDbg(cm_scache_t *scp, char * file, long line)
1689 #else
1690 void cm_HoldSCache(cm_scache_t *scp)
1691 #endif
1692 {
1693     osi_assertx(scp != NULL, "null cm_scache_t");
1694     lock_ObtainWrite(&cm_scacheLock);
1695     scp->refCount++;
1696 #ifdef DEBUG_REFCOUNT
1697     osi_Log2(afsd_logp,"cm_HoldSCache scp 0x%p ref %d",scp, scp->refCount);
1698     afsi_log("%s:%d cm_HoldSCache scp 0x%p ref %d", file, line, scp, scp->refCount);
1699 #endif
1700     lock_ReleaseWrite(&cm_scacheLock);
1701 }
1702
1703 #ifdef DEBUG_REFCOUNT
1704 void cm_ReleaseSCacheNoLockDbg(cm_scache_t *scp, char * file, long line)
1705 #else
1706 void cm_ReleaseSCacheNoLock(cm_scache_t *scp)
1707 #endif
1708 {
1709     osi_assertx(scp != NULL, "null cm_scache_t");
1710     if (scp->refCount == 0)
1711         osi_Log1(afsd_logp,"cm_ReleaseSCacheNoLock about to panic scp 0x%x",scp);
1712     osi_assertx(scp->refCount-- >= 0, "cm_scache_t refCount 0");
1713 #ifdef DEBUG_REFCOUNT
1714     osi_Log2(afsd_logp,"cm_ReleaseSCacheNoLock scp 0x%p ref %d",scp,scp->refCount);
1715     afsi_log("%s:%d cm_ReleaseSCacheNoLock scp 0x%p ref %d", file, line, scp, scp->refCount);
1716 #endif
1717 }
1718
1719 #ifdef DEBUG_REFCOUNT
1720 void cm_ReleaseSCacheDbg(cm_scache_t *scp, char * file, long line)
1721 #else
1722 void cm_ReleaseSCache(cm_scache_t *scp)
1723 #endif
1724 {
1725     osi_assertx(scp != NULL, "null cm_scache_t");
1726     lock_ObtainWrite(&cm_scacheLock);
1727     if (scp->refCount == 0)
1728         osi_Log1(afsd_logp,"cm_ReleaseSCache about to panic scp 0x%x",scp);
1729     osi_assertx(scp->refCount != 0, "cm_scache_t refCount 0");
1730     scp->refCount--;
1731 #ifdef DEBUG_REFCOUNT
1732     osi_Log2(afsd_logp,"cm_ReleaseSCache scp 0x%p ref %d",scp,scp->refCount);
1733     afsi_log("%s:%d cm_ReleaseSCache scp 0x%p ref %d", file, line, scp, scp->refCount);
1734 #endif
1735     lock_ReleaseWrite(&cm_scacheLock);
1736 }
1737
1738 /* just look for the scp entry to get filetype */
1739 /* doesn't need to be perfectly accurate, so locking doesn't matter too much */
1740 int cm_FindFileType(cm_fid_t *fidp)
1741 {
1742     long hash;
1743     cm_scache_t *scp;
1744         
1745     hash = CM_SCACHE_HASH(fidp);
1746         
1747     osi_assertx(fidp->cell != 0, "unassigned cell value");
1748
1749     lock_ObtainWrite(&cm_scacheLock);
1750     for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
1751         if (cm_FidCmp(fidp, &scp->fid) == 0) {
1752             lock_ReleaseWrite(&cm_scacheLock);
1753             return scp->fileType;
1754         }
1755     }
1756     lock_ReleaseWrite(&cm_scacheLock);
1757     return 0;
1758 }
1759
1760 /* dump all scp's that have reference count > 0 to a file. 
1761  * cookie is used to identify this batch for easy parsing, 
1762  * and it a string provided by a caller 
1763  */
1764 int cm_DumpSCache(FILE *outputFile, char *cookie, int lock)
1765 {
1766     int zilch;
1767     cm_scache_t *scp;
1768     char output[2048];
1769     int i;
1770   
1771     if (lock)
1772         lock_ObtainRead(&cm_scacheLock);
1773   
1774     sprintf(output, "%s - dumping all scache - cm_data.currentSCaches=%d, cm_data.maxSCaches=%d\r\n", cookie, cm_data.currentSCaches, cm_data.maxSCaches);
1775     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1776   
1777     for (scp = cm_data.allSCachesp; scp; scp = scp->allNextp) 
1778     {
1779         sprintf(output, "%s scp=0x%p, fid (cell=%d, volume=%d, vnode=%d, unique=%d) volp=0x%p type=%d dv=%d len=0x%I64x mp='%s' flags=0x%x cb=0x%x refCount=%u\r\n", 
1780                 cookie, scp, scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique, 
1781                 scp->volp, scp->fileType, scp->dataVersion, scp->length.QuadPart, scp->mountPointStringp, scp->flags,
1782                 (unsigned long)scp->cbExpires, scp->refCount);
1783         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1784     }
1785   
1786     sprintf(output, "%s - Done dumping all scache.\r\n", cookie);
1787     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1788     sprintf(output, "%s - dumping cm_data.scacheHashTable - cm_data.scacheHashTableSize=%d\r\n", cookie, cm_data.scacheHashTableSize);
1789     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1790   
1791     for (i = 0; i < cm_data.scacheHashTableSize; i++)
1792     {
1793         for(scp = cm_data.scacheHashTablep[i]; scp; scp=scp->nextp) 
1794         {
1795             sprintf(output, "%s scp=0x%p, hash=%d, fid (cell=%d, volume=%d, vnode=%d, unique=%d)\r\n", 
1796                     cookie, scp, i, scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
1797             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1798         }
1799     }
1800
1801     sprintf(output, "%s - Done dumping cm_data.scacheHashTable\r\n", cookie);
1802     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1803   
1804     if (lock)
1805         lock_ReleaseRead(&cm_scacheLock);       
1806     return (0);     
1807 }
1808