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