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