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