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