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