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