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