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