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