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