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