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