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