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