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