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