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