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