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