309f972e28a6f84c027665ea847ba5821b93bb05
[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 #ifndef DJGPP
14 #include <windows.h>
15 #include <winsock2.h>
16 #include <nb30.h>
17 #endif /* !DJGPP */
18 #include <malloc.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <osi.h>
22
23 #include "afsd.h"
24
25 /*extern void afsi_log(char *pattern, ...);*/
26
27 extern osi_hyper_t hzero;
28
29 /* File locks */
30 osi_queue_t *cm_allFileLocks;
31 osi_queue_t *cm_freeFileLocks;
32 unsigned long cm_lockRefreshCycle;
33
34 /* lock for globals */
35 osi_rwlock_t cm_scacheLock;
36
37 /* Dummy scache entry for use with pioctl fids */
38 cm_scache_t cm_fakeSCache;
39
40 #ifdef AFS_FREELANCE_CLIENT
41 extern osi_mutex_t cm_Freelance_Lock;
42 #endif
43
44 /* must be called with cm_scacheLock write-locked! */
45 void cm_AdjustLRU(cm_scache_t *scp)
46 {
47     if (scp == cm_data.scacheLRULastp)
48         cm_data.scacheLRULastp = (cm_scache_t *) osi_QPrev(&scp->q);
49     osi_QRemoveHT((osi_queue_t **) &cm_data.scacheLRUFirstp, (osi_queue_t **) &cm_data.scacheLRULastp, &scp->q);
50     osi_QAdd((osi_queue_t **) &cm_data.scacheLRUFirstp, &scp->q);
51     if (!cm_data.scacheLRULastp) 
52         cm_data.scacheLRULastp = scp;
53 }
54
55 /* called with cm_scacheLock write-locked; recycles an existing scp. */
56 long cm_RecycleSCache(cm_scache_t *scp, afs_int32 flags)
57 {
58     cm_scache_t **lscpp;
59     cm_scache_t *tscp;
60     int i;
61
62     if (scp->flags & CM_SCACHEFLAG_INHASH) {
63         /* hash it out first */
64         i = CM_SCACHE_HASH(&scp->fid);
65         for (lscpp = &cm_data.hashTablep[i], tscp = cm_data.hashTablep[i];
66               tscp;
67               lscpp = &tscp->nextp, tscp = tscp->nextp) {
68             if (tscp == scp) {
69                 *lscpp = scp->nextp;
70                 scp->flags &= ~CM_SCACHEFLAG_INHASH;
71                 break;
72             }
73         }
74         osi_assertx(tscp, "afsd: scache hash screwup");
75     }
76
77     if (flags & CM_SCACHE_RECYCLEFLAG_DESTROY_BUFFERS) {
78         osi_queueData_t *qdp;
79         cm_buf_t *bufp;
80
81         while(qdp = scp->bufWritesp) {
82             bufp = osi_GetQData(qdp);
83             osi_QRemove((osi_queue_t **) &scp->bufWritesp, &qdp->q);
84             osi_QDFree(qdp);
85             if (bufp) {
86                 lock_ObtainMutex(&bufp->mx);
87                 bufp->cmFlags &= ~CM_BUF_CMSTORING;
88                 bufp->flags &= ~CM_BUF_DIRTY;
89                 bufp->dataVersion = -1; /* bad */
90                 bufp->dirtyCounter++;
91                 if (bufp->flags & CM_BUF_WAITING) {
92                     osi_Log2(afsd_logp, "CM RecycleSCache Waking [scp 0x%x] bufp 0x%x", scp, bufp);
93                     osi_Wakeup((long) &bufp);
94                 }
95                 lock_ReleaseMutex(&bufp->mx);
96                 buf_Release(bufp);
97             }
98         }
99         while(qdp = scp->bufReadsp) {
100             bufp = osi_GetQData(qdp);
101             osi_QRemove((osi_queue_t **) &scp->bufReadsp, &qdp->q);
102             osi_QDFree(qdp);
103             if (bufp) {
104                 lock_ObtainMutex(&bufp->mx);
105                 bufp->cmFlags &= ~CM_BUF_CMFETCHING;
106                 bufp->flags &= ~CM_BUF_DIRTY;
107                 bufp->dataVersion = -1; /* bad */
108                 bufp->dirtyCounter++;
109                 if (bufp->flags & CM_BUF_WAITING) {
110                     osi_Log2(afsd_logp, "CM RecycleSCache Waking [scp 0x%x] bufp 0x%x", scp, bufp);
111                     osi_Wakeup((long) &bufp);
112                 }
113                 lock_ReleaseMutex(&bufp->mx);
114                 buf_Release(bufp);
115             }
116         }
117     } else {
118         /* look for things that shouldn't still be set */
119         osi_assert(scp->bufWritesp == NULL);
120         osi_assert(scp->bufReadsp == NULL);
121     }
122
123     /* invalidate so next merge works fine;
124      * also initialize some flags */
125     scp->flags &= ~(CM_SCACHEFLAG_STATD
126                      | CM_SCACHEFLAG_RO
127                      | CM_SCACHEFLAG_PURERO
128                      | CM_SCACHEFLAG_OVERQUOTA
129                      | CM_SCACHEFLAG_OUTOFSPACE);
130     scp->serverModTime = 0;
131     scp->dataVersion = 0;
132     scp->bulkStatProgress = hzero;
133     scp->waitCount = 0;
134
135     scp->fid.vnode = 0;
136     scp->fid.volume = 0;
137     scp->fid.unique = 0;
138     scp->fid.cell = 0;
139
140     /* discard callback */
141     if (scp->cbServerp) {
142         cm_PutServer(scp->cbServerp);
143         scp->cbServerp = NULL;
144     }
145     scp->cbExpires = 0;
146
147     /* remove from dnlc */
148     cm_dnlcPurgedp(scp);
149     cm_dnlcPurgevp(scp);
150
151     /* discard cached status; if non-zero, Close
152      * tried to store this to server but failed */
153     scp->mask = 0;
154
155     /* drop held volume ref */
156     if (scp->volp) {
157         cm_PutVolume(scp->volp);
158         scp->volp = NULL;
159     }
160
161     /* discard symlink info */
162     scp->mountPointStringp[0] = 0;
163     memset(&scp->mountRootFid, 0, sizeof(cm_fid_t));
164     memset(&scp->dotdotFid, 0, sizeof(cm_fid_t));
165
166     /* reset locking info */
167     scp->fileLocksH = NULL;
168     scp->fileLocksT = NULL;
169     scp->serverLock = (-1);
170     scp->exclusiveLocks = 0;
171     scp->sharedLocks = 0;
172
173     /* not locked, but there can be no references to this guy
174      * while we hold the global refcount lock.
175      */
176     cm_FreeAllACLEnts(scp);
177
178     return 0;
179 }
180
181
182 /* called with cm_scacheLock write-locked; find a vnode to recycle.
183  * Can allocate a new one if desperate, or if below quota (cm_data.maxSCaches).
184  */
185 cm_scache_t *cm_GetNewSCache(void)
186 {
187     cm_scache_t *scp;
188
189   start:
190     if (cm_data.currentSCaches >= cm_data.maxSCaches) {
191         for (scp = cm_data.scacheLRULastp;
192               scp;
193               scp = (cm_scache_t *) osi_QPrev(&scp->q)) {
194             if (scp->refCount == 0) 
195                 break;
196         }
197                 
198         if (scp) {
199             osi_assert(scp >= cm_data.scacheBaseAddress && scp < (cm_scache_t *)cm_data.hashTablep);
200
201             if (!cm_RecycleSCache(scp, 0)) {
202             
203                 /* we found an entry, so return it */
204                 /* now remove from the LRU queue and put it back at the
205                  * head of the LRU queue.
206                  */
207                 cm_AdjustLRU(scp);
208
209                 /* and we're done */
210                 return scp;
211             } else {
212                 /* We don't like this entry, choose another one. */
213                 goto start;
214             }
215         }
216     }
217         
218     /* if we get here, we should allocate a new scache entry.  We either are below
219      * quota or we have a leak and need to allocate a new one to avoid panicing.
220      */
221     scp = cm_data.scacheBaseAddress + cm_data.currentSCaches;
222     osi_assert(scp >= cm_data.scacheBaseAddress && scp < (cm_scache_t *)cm_data.hashTablep);
223     memset(scp, 0, sizeof(cm_scache_t));
224     scp->magic = CM_SCACHE_MAGIC;
225     lock_InitializeMutex(&scp->mx, "cm_scache_t mutex");
226     lock_InitializeRWLock(&scp->bufCreateLock, "cm_scache_t bufCreateLock");
227     scp->serverLock = -1;
228
229     /* and put it in the LRU queue */
230     osi_QAdd((osi_queue_t **) &cm_data.scacheLRUFirstp, &scp->q);
231     if (!cm_data.scacheLRULastp) 
232         cm_data.scacheLRULastp = scp;
233     cm_data.currentSCaches++;
234     cm_dnlcPurgedp(scp); /* make doubly sure that this is not in dnlc */
235     cm_dnlcPurgevp(scp); 
236     return scp;
237 }       
238
239 /* like strcmp, only for fids */
240 int cm_FidCmp(cm_fid_t *ap, cm_fid_t *bp)
241 {
242     if (ap->vnode != bp->vnode) 
243         return 1;
244     if (ap->volume != bp->volume) 
245         return 1;
246     if (ap->unique != bp->unique) 
247         return 1;
248     if (ap->cell != bp->cell) 
249         return 1;
250     return 0;
251 }
252
253 void cm_fakeSCacheInit(int newFile)
254 {
255     if ( newFile ) {
256         memset(&cm_data.fakeSCache, 0, sizeof(cm_scache_t));
257         cm_data.fakeSCache.cbServerp = (struct cm_server *)(-1);
258         /* can leave clientModTime at 0 */
259         cm_data.fakeSCache.fileType = CM_SCACHETYPE_FILE;
260         cm_data.fakeSCache.unixModeBits = 0777;
261         cm_data.fakeSCache.length.LowPart = 1000;
262         cm_data.fakeSCache.linkCount = 1;
263         cm_data.fakeSCache.refCount = 1;
264     }
265     lock_InitializeMutex(&cm_data.fakeSCache.mx, "cm_scache_t mutex");
266 }
267
268 long
269 cm_ValidateSCache(void)
270 {
271     cm_scache_t * scp, *lscp;
272     long i;
273
274     if ( cm_data.scacheLRUFirstp == NULL && cm_data.scacheLRULastp != NULL ||
275          cm_data.scacheLRUFirstp != NULL && cm_data.scacheLRULastp == NULL) {
276         afsi_log("cm_ValidateSCache failure: inconsistent LRU pointers");
277         fprintf(stderr, "cm_ValidateSCache failure: inconsistent LRU pointers\n");
278         return -17;
279     }
280
281     for ( scp = cm_data.scacheLRUFirstp, lscp = NULL, i = 0; 
282           scp;
283           lscp = scp, scp = (cm_scache_t *) osi_QNext(&scp->q), i++ ) {
284         if (scp->magic != CM_SCACHE_MAGIC) {
285             afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
286             fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
287             return -1;
288         }
289         if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
290             afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
291             fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
292             return -2;
293         }
294         if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
295             afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
296             fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
297             return -3;
298         }
299         if (scp->volp && scp->volp->magic != CM_VOLUME_MAGIC) {
300             afsi_log("cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC");
301             fprintf(stderr, "cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC\n");
302             return -4;
303         }
304         if (i > cm_data.currentSCaches ) {
305             afsi_log("cm_ValidateSCache failure: LRU First queue loops");
306             fprintf(stderr, "cm_ValidateSCache failure: LUR First queue loops\n");
307             return -13;
308         }
309         if (lscp != (cm_scache_t *) osi_QPrev(&scp->q)) {
310             afsi_log("cm_ValidateSCache failure: QPrev(scp) != previous");
311             fprintf(stderr, "cm_ValidateSCache failure: QPrev(scp) != previous\n");
312             return -15;
313         }
314     }
315
316     for ( scp = cm_data.scacheLRULastp, lscp = NULL, i = 0; scp;
317           lscp = scp, scp = (cm_scache_t *) osi_QPrev(&scp->q), i++ ) {
318         if (scp->magic != CM_SCACHE_MAGIC) {
319             afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
320             fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
321             return -5;
322         }
323         if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
324             afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
325             fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
326             return -6;
327         }
328         if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
329             afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
330             fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
331             return -7;
332         }
333         if (scp->volp && scp->volp->magic != CM_VOLUME_MAGIC) {
334             afsi_log("cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC");
335             fprintf(stderr, "cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC\n");
336             return -8;
337         }
338         if (i > cm_data.currentSCaches ) {
339             afsi_log("cm_ValidateSCache failure: LRU Last queue loops");
340             fprintf(stderr, "cm_ValidateSCache failure: LUR Last queue loops\n");
341             return -14;
342         }
343         if (lscp != (cm_scache_t *) osi_QNext(&scp->q)) {
344             afsi_log("cm_ValidateSCache failure: QNext(scp) != next");
345             fprintf(stderr, "cm_ValidateSCache failure: QNext(scp) != next\n");
346             return -16;
347         }
348     }
349
350     for ( i=0; i < cm_data.hashTableSize; i++ ) {
351         for ( scp = cm_data.hashTablep[i]; scp; scp = scp->nextp ) {
352             if (scp->magic != CM_SCACHE_MAGIC) {
353                 afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
354                 fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
355                 return -9;
356             }
357             if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
358                 afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
359                 fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
360                 return -10;
361             }
362             if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
363                 afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
364                 fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
365                 return -11;
366             }
367             if (scp->volp && scp->volp->magic != CM_VOLUME_MAGIC) {
368                 afsi_log("cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC");
369                 fprintf(stderr, "cm_ValidateSCache failure: scp->volp->magic != CM_VOLUME_MAGIC\n");
370                 return -12;
371             }
372         }
373     }
374
375     return cm_dnlcValidate();
376 }
377
378 long
379 cm_ShutdownSCache(void)
380 {
381     cm_scache_t * scp;
382
383     for ( scp = cm_data.scacheLRULastp; scp;
384           scp = (cm_scache_t *) osi_QPrev(&scp->q) ) {
385         if (scp->randomACLp) {
386             lock_ObtainMutex(&scp->mx);
387             cm_FreeAllACLEnts(scp);
388             lock_ReleaseMutex(&scp->mx);
389         }
390         lock_FinalizeMutex(&scp->mx);
391         lock_FinalizeRWLock(&scp->bufCreateLock);
392     }
393
394     return cm_dnlcShutdown();
395 }
396
397 void cm_InitSCache(int newFile, long maxSCaches)
398 {
399     static osi_once_t once;
400         
401     if (osi_Once(&once)) {
402         lock_InitializeRWLock(&cm_scacheLock, "cm_scacheLock");
403         if ( newFile ) {
404             memset(cm_data.hashTablep, 0, sizeof(cm_scache_t *) * cm_data.hashTableSize);
405             cm_data.currentSCaches = 0;
406             cm_data.maxSCaches = maxSCaches;
407             cm_data.scacheLRUFirstp = cm_data.scacheLRULastp = NULL;
408         } else {
409             cm_scache_t * scp;
410
411             for ( scp = cm_data.scacheLRULastp; scp;
412                   scp = (cm_scache_t *) osi_QPrev(&scp->q) ) {
413                 lock_InitializeMutex(&scp->mx, "cm_scache_t mutex");
414                 lock_InitializeRWLock(&scp->bufCreateLock, "cm_scache_t bufCreateLock");
415
416                 scp->cbServerp = NULL;
417                 scp->cbExpires = 0;
418                 scp->fileLocksH = NULL;
419                 scp->fileLocksT = NULL;
420                 scp->serverLock = (-1);
421                 scp->lastRefreshCycle = 0;
422                 scp->exclusiveLocks = 0;
423                 scp->sharedLocks = 0;
424                 scp->openReads = 0;
425                 scp->openWrites = 0;
426                 scp->openShares = 0;
427                 scp->openExcls = 0;
428                 scp->waitCount = 0;
429                 scp->flags &= ~CM_SCACHEFLAG_WAITING;
430             }
431         }
432         cm_allFileLocks = NULL;
433         cm_freeFileLocks = NULL;
434         cm_lockRefreshCycle = 0;
435         cm_fakeSCacheInit(newFile);
436         cm_dnlcInit(newFile);
437         osi_EndOnce(&once);
438     }
439 }
440
441 /* version that doesn't bother creating the entry if we don't find it */
442 cm_scache_t *cm_FindSCache(cm_fid_t *fidp)
443 {
444     long hash;
445     cm_scache_t *scp;
446
447     hash = CM_SCACHE_HASH(fidp);
448         
449     osi_assert(fidp->cell != 0);
450
451     lock_ObtainWrite(&cm_scacheLock);
452     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
453         if (cm_FidCmp(fidp, &scp->fid) == 0) {
454             cm_HoldSCacheNoLock(scp);
455             cm_AdjustLRU(scp);
456             lock_ReleaseWrite(&cm_scacheLock);
457             return scp;
458         }
459     }
460     lock_ReleaseWrite(&cm_scacheLock);
461     return NULL;
462 }
463
464 long cm_GetSCache(cm_fid_t *fidp, cm_scache_t **outScpp, cm_user_t *userp,
465                   cm_req_t *reqp)
466 {
467     long hash;
468     cm_scache_t *scp;
469     long code;
470     cm_volume_t *volp = 0;
471     cm_cell_t *cellp;
472     char* mp = 0;
473     int special; // yj: boolean variable to test if file is on root.afs
474     int isRoot;
475     extern cm_fid_t cm_rootFid;
476         
477     hash = CM_SCACHE_HASH(fidp);
478         
479     osi_assert(fidp->cell != 0);
480
481     if (fidp->cell== cm_data.rootFid.cell && 
482          fidp->volume==cm_data.rootFid.volume &&
483          fidp->vnode==0x0 && fidp->unique==0x0)
484     {
485         osi_Log0(afsd_logp,"cm_getSCache called with root cell/volume and vnode=0 and unique=0");
486     }
487
488     // yj: check if we have the scp, if so, we don't need
489     // to do anything else
490     lock_ObtainWrite(&cm_scacheLock);
491     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
492         if (cm_FidCmp(fidp, &scp->fid) == 0) {
493             cm_HoldSCacheNoLock(scp);
494             *outScpp = scp;
495             cm_AdjustLRU(scp);
496             lock_ReleaseWrite(&cm_scacheLock);
497             return 0;
498         }
499     }
500         
501     // yj: when we get here, it means we don't have an scp
502     // so we need to either load it or fake it, depending
503     // on whether the file is "special", see below.
504
505     // yj: if we're trying to get an scp for a file that's
506     // on root.afs of homecell, we want to handle it specially
507     // because we have to fill in the status stuff 'coz we
508     // don't want trybulkstat to fill it in for us
509 #ifdef AFS_FREELANCE_CLIENT
510     special = (fidp->cell==AFS_FAKE_ROOT_CELL_ID && 
511                fidp->volume==AFS_FAKE_ROOT_VOL_ID &&
512                !(fidp->vnode==0x1 && fidp->unique==0x1));
513     isRoot = (fidp->cell==AFS_FAKE_ROOT_CELL_ID && 
514               fidp->volume==AFS_FAKE_ROOT_VOL_ID &&
515               fidp->vnode==0x1 && fidp->unique==0x1);
516     if (cm_freelanceEnabled && isRoot) {
517         osi_Log0(afsd_logp,"cm_getSCache Freelance and isRoot");
518         /* freelance: if we are trying to get the root scp for the first
519          * time, we will just put in a place holder entry. 
520          */
521         volp = NULL;
522     }
523           
524     if (cm_freelanceEnabled && special) {
525         osi_Log0(afsd_logp,"cm_getSCache Freelance and special");
526         if (fidp->vnode > 1 && fidp->vnode <= cm_noLocalMountPoints + 2) {
527             lock_ObtainMutex(&cm_Freelance_Lock);
528             mp =(cm_localMountPoints+fidp->vnode-2)->mountPointStringp;
529             lock_ReleaseMutex(&cm_Freelance_Lock);
530         } else {
531             mp = "";
532         }
533         scp = cm_GetNewSCache();
534           
535         lock_ObtainMutex(&scp->mx);
536         scp->fid = *fidp;
537         scp->volp = cm_data.rootSCachep->volp;
538         scp->dotdotFid.cell=AFS_FAKE_ROOT_CELL_ID;
539         scp->dotdotFid.volume=AFS_FAKE_ROOT_VOL_ID;
540         scp->dotdotFid.unique=1;
541         scp->dotdotFid.vnode=1;
542         scp->flags |= (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO);
543         scp->nextp=cm_data.hashTablep[hash];
544         cm_data.hashTablep[hash]=scp;
545         scp->flags |= CM_SCACHEFLAG_INHASH;
546         scp->refCount = 1;
547         if (fidp->vnode > 1 && fidp->vnode <= cm_noLocalMountPoints + 2)
548             scp->fileType = (cm_localMountPoints+fidp->vnode-2)->fileType;
549         else 
550             scp->fileType = CM_SCACHETYPE_INVALID;
551
552         lock_ObtainMutex(&cm_Freelance_Lock);
553         scp->length.LowPart = (DWORD)strlen(mp)+4;
554         strncpy(scp->mountPointStringp,mp,MOUNTPOINTLEN);
555         scp->mountPointStringp[MOUNTPOINTLEN-1] = '\0';
556         lock_ReleaseMutex(&cm_Freelance_Lock);
557
558         scp->owner=0x0;
559         scp->unixModeBits=0x1ff;
560         scp->clientModTime=FakeFreelanceModTime;
561         scp->serverModTime=FakeFreelanceModTime;
562         scp->parentUnique = 0x1;
563         scp->parentVnode=0x1;
564         scp->group=0;
565         scp->dataVersion=cm_data.fakeDirVersion;
566         scp->lockDataVersion=-1; /* no lock yet */
567         lock_ReleaseMutex(&scp->mx);
568         *outScpp = scp;
569         lock_ReleaseWrite(&cm_scacheLock);
570         return 0;
571     }
572     // end of yj code
573 #endif /* AFS_FREELANCE_CLIENT */
574
575     /* otherwise, we need to find the volume */
576     if (!cm_freelanceEnabled || !isRoot) {
577         lock_ReleaseWrite(&cm_scacheLock);      /* for perf. reasons */
578         cellp = cm_FindCellByID(fidp->cell);
579         if (!cellp) 
580             return CM_ERROR_NOSUCHCELL;
581
582         code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, &volp);
583         if (code) 
584             return code;
585         lock_ObtainWrite(&cm_scacheLock);
586     }
587         
588     /* otherwise, we have the volume, now reverify that the scp doesn't
589      * exist, and proceed.
590      */
591     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
592         if (cm_FidCmp(fidp, &scp->fid) == 0) {
593             cm_HoldSCacheNoLock(scp);
594             osi_assert(scp->volp == volp);
595             cm_AdjustLRU(scp);
596             lock_ReleaseWrite(&cm_scacheLock);
597             if (volp)
598                 cm_PutVolume(volp);
599             *outScpp = scp;
600             return 0;
601         }
602     }
603         
604     /* now, if we don't have the fid, recycle something */
605     scp = cm_GetNewSCache();
606     osi_assert(!(scp->flags & CM_SCACHEFLAG_INHASH));
607     lock_ObtainMutex(&scp->mx);
608     scp->fid = *fidp;
609     scp->volp = volp;   /* a held reference */
610
611     if (!cm_freelanceEnabled || !isRoot) {
612         /* if this scache entry represents a volume root then we need 
613          * to copy the dotdotFipd from the volume structure where the 
614          * "master" copy is stored (defect 11489)
615          */
616         if (scp->fid.vnode == 1 && scp->fid.unique == 1) {
617             scp->dotdotFid = volp->dotdotFid;
618         }
619           
620         if (volp->roID == fidp->volume)
621             scp->flags |= (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO);
622         else if (volp->bkID == fidp->volume)
623             scp->flags |= CM_SCACHEFLAG_RO;
624     }
625     scp->nextp = cm_data.hashTablep[hash];
626     cm_data.hashTablep[hash] = scp;
627     scp->flags |= CM_SCACHEFLAG_INHASH;
628     scp->refCount = 1;
629     lock_ReleaseMutex(&scp->mx);
630
631     /* XXX - The following fields in the cm_scache are 
632      * uninitialized:
633      *   fileType
634      *   parentVnode
635      *   parentUnique
636      */
637     lock_ReleaseWrite(&cm_scacheLock);
638         
639     /* now we have a held scache entry; just return it */
640     *outScpp = scp;
641     return 0;
642 }
643
644 /* Returns a held reference to the scache's parent 
645  * if it exists */
646 cm_scache_t * cm_FindSCacheParent(cm_scache_t * scp)
647 {
648     long code = 0;
649     int i;
650     cm_fid_t    parent_fid;
651     cm_scache_t * pscp = NULL;
652
653     lock_ObtainWrite(&cm_scacheLock);
654     parent_fid = scp->fid;
655     parent_fid.vnode = scp->parentVnode;
656     parent_fid.unique = scp->parentUnique;
657
658     if (cm_FidCmp(&scp->fid, &parent_fid)) {
659         for (i=0; i<cm_data.hashTableSize; i++) {
660             for (pscp = cm_data.hashTablep[i]; pscp; pscp = pscp->nextp) {
661                 if (!cm_FidCmp(&pscp->fid, &parent_fid)) {
662                     cm_HoldSCacheNoLock(pscp);
663                     break;
664                 }
665             }
666         }
667     }
668     lock_ReleaseWrite(&cm_scacheLock);
669
670     return pscp;
671 }
672
673 /* synchronize a fetch, store, read, write, fetch status or store status.
674  * Called with scache mutex held, and returns with it held, but temporarily
675  * drops it during the fetch.
676  * 
677  * At most one flag can be on in flags, if this is an RPC request.
678  *
679  * Also, if we're fetching or storing data, we must ensure that we have a buffer.
680  *
681  * There are a lot of weird restrictions here; here's an attempt to explain the
682  * rationale for the concurrency restrictions implemented in this function.
683  *
684  * First, although the file server will break callbacks when *another* machine
685  * modifies a file or status block, the client itself is responsible for
686  * concurrency control on its own requests.  Callback breaking events are rare,
687  * and simply invalidate any concurrent new status info.
688  *
689  * In the absence of callback breaking messages, we need to know how to
690  * synchronize incoming responses describing updates to files.  We synchronize
691  * operations that update the data version by comparing the data versions.
692  * However, updates that do not update the data, but only the status, can't be
693  * synchronized with fetches or stores, since there's nothing to compare
694  * to tell which operation executed first at the server.
695  *
696  * Thus, we can allow multiple ops that change file data, or dir data, and
697  * fetches.  However, status storing ops have to be done serially.
698  *
699  * Furthermore, certain data-changing ops are incompatible: we can't read or
700  * write a buffer while doing a truncate.  We can't read and write the same
701  * buffer at the same time, or write while fetching or storing, or read while
702  * fetching a buffer (this may change).  We can't fetch and store at the same
703  * time, either.
704  *
705  * With respect to status, we can't read and write at the same time, read while
706  * fetching, write while fetching or storing, or fetch and store at the same time.
707  *
708  * We can't allow a get callback RPC to run in concurrently with something that
709  * will return updated status, since we could start a call, have the server
710  * return status, have another machine make an update to the status (which
711  * doesn't change serverModTime), have the original machine get a new callback,
712  * and then have the original machine merge in the early, old info from the
713  * first call.  At this point, the easiest way to avoid this problem is to have
714  * getcallback calls conflict with all others for the same vnode.  Other calls
715  * to cm_MergeStatus that aren't associated with calls to cm_SyncOp on the same
716  * vnode must be careful not to merge in their status unless they have obtained
717  * a callback from the start of their call.
718  *
719  * Note added 1/23/96
720  * Concurrent StoreData RPC's can cause trouble if the file is being extended.
721  * Each such RPC passes a FileLength parameter, which the server uses to do
722  * pre-truncation if necessary.  So if two RPC's are processed out of order at
723  * the server, the one with the smaller FileLength will be processed last,
724  * possibly resulting in a bogus truncation.  The simplest way to avoid this
725  * is to serialize all StoreData RPC's.  This is the reason we defined
726  * CM_SCACHESYNC_STOREDATA_EXCL and CM_SCACHEFLAG_DATASTORING.
727  */
728 long cm_SyncOp(cm_scache_t *scp, cm_buf_t *bufp, cm_user_t *userp, cm_req_t *reqp,
729                afs_uint32 rights, afs_uint32 flags)
730 {
731     osi_queueData_t *qdp;
732     long code;
733     cm_buf_t *tbufp;
734     afs_uint32 outRights;
735     int bufLocked;
736
737     /* lookup this first */
738     bufLocked = flags & CM_SCACHESYNC_BUFLOCKED;
739
740     /* some minor assertions */
741     if (flags & (CM_SCACHESYNC_STOREDATA | CM_SCACHESYNC_FETCHDATA
742                   | CM_SCACHESYNC_READ | CM_SCACHESYNC_WRITE
743                   | CM_SCACHESYNC_SETSIZE)) {
744         if (bufp) {
745             osi_assert(bufp->refCount > 0);
746             /*
747                osi_assert(cm_FidCmp(&bufp->fid, &scp->fid) == 0);
748              */
749         }
750     }
751     else osi_assert(bufp == NULL);
752
753     /* Do the access check.  Now we don't really do the access check
754      * atomically, since the caller doesn't expect the parent dir to be
755      * returned locked, and that is what we'd have to do to prevent a
756      * callback breaking message on the parent due to a setacl call from
757      * being processed while we're running.  So, instead, we check things
758      * here, and if things look fine with the access, we proceed to finish
759      * the rest of this check.  Sort of a hack, but probably good enough.
760      */
761
762     while (1) {
763         if (flags & CM_SCACHESYNC_FETCHSTATUS) {
764             /* if we're bringing in a new status block, ensure that
765              * we aren't already doing so, and that no one is
766              * changing the status concurrently, either.  We need
767              * to do this, even if the status is of a different
768              * type, since we don't have the ability to figure out,
769              * in the AFS 3 protocols, which status-changing
770              * operation ran first, or even which order a read and
771              * a write occurred in.
772              */
773             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
774                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
775                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want FETCHSTATUS", scp);
776                 goto sleep;
777             }
778         }
779         if (flags & (CM_SCACHESYNC_STORESIZE | CM_SCACHESYNC_STORESTATUS
780                       | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_GETCALLBACK)) {
781             /* if we're going to make an RPC to change the status, make sure
782              * that no one is bringing in or sending out the status.
783              */
784             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING |
785                               CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
786                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
787                 goto sleep;
788             }
789             if (scp->bufReadsp || scp->bufWritesp) {
790                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is bufRead|bufWrite want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
791                 goto sleep;
792             }
793         }
794         if (flags & CM_SCACHESYNC_FETCHDATA) {
795             /* if we're bringing in a new chunk of data, make sure that
796              * nothing is happening to that chunk, and that we aren't
797              * changing the basic file status info, either.
798              */
799             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
800                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
801                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want FETCHDATA", scp);
802                 goto sleep;
803             }
804             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
805                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want FETCHDATA", scp, bufp);
806                 goto sleep;
807             }
808         }
809         if (flags & CM_SCACHESYNC_STOREDATA) {
810             /* same as fetch data */
811             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
812                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
813                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STOREDATA", scp);
814                 goto sleep;
815             }
816             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
817                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want STOREDATA", scp, bufp);
818                 goto sleep;
819             }
820         }
821
822         if (flags & CM_SCACHESYNC_STOREDATA_EXCL) {
823             /* Don't allow concurrent StoreData RPC's */
824             if (scp->flags & CM_SCACHEFLAG_DATASTORING) {
825                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is DATASTORING want STOREDATA_EXCL", scp);
826                 goto sleep;
827             }
828         }
829
830         if (flags & CM_SCACHESYNC_ASYNCSTORE) {
831             /* Don't allow more than one BKG store request */
832             if (scp->flags & CM_SCACHEFLAG_ASYNCSTORING) {
833                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is ASYNCSTORING want ASYNCSTORE", scp);
834                 goto sleep;
835             }
836         }
837
838         if (flags & CM_SCACHESYNC_LOCK) {
839             /* Don't allow concurrent fiddling with lock lists */
840             if (scp->flags & CM_SCACHEFLAG_LOCKING) {
841                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is LOCKING want LOCK", scp);
842                 goto sleep;
843             }
844         }
845
846         /* now the operations that don't correspond to making RPCs */
847         if (flags & CM_SCACHESYNC_GETSTATUS) {
848             /* we can use the status that's here, if we're not
849              * bringing in new status.
850              */
851             if (scp->flags & (CM_SCACHEFLAG_FETCHING)) {
852                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want GETSTATUS", scp);
853                 goto sleep;
854             }
855         }
856         if (flags & CM_SCACHESYNC_SETSTATUS) {
857             /* we can make a change to the local status, as long as
858              * the status isn't changing now.
859              *
860              * If we're fetching or storing a chunk of data, we can
861              * change the status locally, since the fetch/store
862              * operations don't change any of the data that we're
863              * changing here.
864              */
865             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING | CM_SCACHEFLAG_SIZESTORING)) {
866                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING want SETSTATUS", scp);
867                 goto sleep;
868             }
869         }
870         if (flags & CM_SCACHESYNC_READ) {
871             /* we're going to read the data, make sure that the
872              * status is available, and that the data is here.  It
873              * is OK to read while storing the data back.
874              */
875             if (scp->flags & CM_SCACHEFLAG_FETCHING) {
876                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want READ", scp);
877                 goto sleep;
878             }
879             if (bufp && ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == CM_BUF_CMFETCHING)) {
880                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING want READ", scp, bufp);
881                 goto sleep;
882             }
883         }
884         if (flags & CM_SCACHESYNC_WRITE) {
885             /* don't write unless the status is stable and the chunk
886              * is stable.
887              */
888             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
889                                | CM_SCACHEFLAG_SIZESTORING)) {
890                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING want WRITE", scp);
891                 goto sleep;
892             }
893             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
894                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want WRITE", scp, bufp);
895                 goto sleep;
896             }
897         }
898
899         // yj: modified this so that callback only checked if we're
900         // not checking something on /afs
901         /* fix the conditional to match the one in cm_HaveCallback */
902         if (  (flags & CM_SCACHESYNC_NEEDCALLBACK)
903 #ifdef AFS_FREELANCE_CLIENT
904              && (!cm_freelanceEnabled || 
905                   !(scp->fid.vnode==0x1 && scp->fid.unique==0x1) ||
906                   scp->fid.cell!=AFS_FAKE_ROOT_CELL_ID ||
907                   scp->fid.volume!=AFS_FAKE_ROOT_VOL_ID ||
908                   cm_fakeDirCallback < 2)
909 #endif /* AFS_FREELANCE_CLIENT */
910              ) {
911             if (!cm_HaveCallback(scp)) {
912                 osi_Log1(afsd_logp, "CM SyncOp getting callback on scp 0x%p",
913                           scp);
914                 if (bufLocked) 
915                     lock_ReleaseMutex(&bufp->mx);
916                 code = cm_GetCallback(scp, userp, reqp, 0);
917                 if (bufLocked) {
918                     lock_ReleaseMutex(&scp->mx);
919                     lock_ObtainMutex(&bufp->mx);
920                     lock_ObtainMutex(&scp->mx);
921                 }
922                 if (code) 
923                     return code;
924                 continue;
925             }
926         }
927
928         if (rights) {
929             /* can't check access rights without a callback */
930             osi_assert(flags & CM_SCACHESYNC_NEEDCALLBACK);
931
932             if ((rights & PRSFS_WRITE) && (scp->flags & CM_SCACHEFLAG_RO))
933                 return CM_ERROR_READONLY;
934
935             if (cm_HaveAccessRights(scp, userp, rights, &outRights)) {
936                 if (~outRights & rights) 
937                     return CM_ERROR_NOACCESS;
938             }
939             else {
940                 /* we don't know the required access rights */
941                 if (bufLocked) lock_ReleaseMutex(&bufp->mx);
942                 code = cm_GetAccessRights(scp, userp, reqp);
943                 if (bufLocked) {
944                     lock_ReleaseMutex(&scp->mx);
945                     lock_ObtainMutex(&bufp->mx);
946                     lock_ObtainMutex(&scp->mx);
947                 }
948                 if (code) 
949                     return code;
950                 continue;
951             }
952         }
953
954         /* if we get here, we're happy */
955         break;
956
957       sleep:
958         /* first check if we're not supposed to wait: fail 
959          * in this case, returning with everything still locked.
960          */
961         if (flags & CM_SCACHESYNC_NOWAIT) 
962             return CM_ERROR_WOULDBLOCK;
963
964         /* wait here, then try again */
965         osi_Log1(afsd_logp, "CM SyncOp sleeping scp 0x%p", scp);
966         if ( scp->flags & CM_SCACHEFLAG_WAITING ) {
967             scp->waitCount++;
968             scp->waitRequests++;
969             osi_Log3(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING already set for 0x%p; %d threads; %d requests", 
970                      scp, scp->waitCount, scp->waitRequests);
971         } else {
972             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING set for 0x%p", scp);
973             scp->flags |= CM_SCACHEFLAG_WAITING;
974             scp->waitCount = scp->waitRequests = 1;
975         }
976         if (bufLocked) 
977             lock_ReleaseMutex(&bufp->mx);
978         osi_SleepM((LONG_PTR) &scp->flags, &scp->mx);
979
980         smb_UpdateServerPriority();
981
982         if (bufLocked) 
983             lock_ObtainMutex(&bufp->mx);
984         lock_ObtainMutex(&scp->mx);
985         scp->waitCount--;
986         osi_Log3(afsd_logp, "CM SyncOp woke! scp 0x%p; still waiting %d threads of %d requests", 
987                  scp, scp->waitCount, scp->waitRequests);
988         if (scp->waitCount == 0) {
989             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING reset for 0x%p", scp);
990             scp->flags &= ~CM_SCACHEFLAG_WAITING;
991             scp->waitRequests = 0;
992         }
993     } /* big while loop */
994         
995     /* now, update the recorded state for RPC-type calls */
996     if (flags & CM_SCACHESYNC_FETCHSTATUS)
997         scp->flags |= CM_SCACHEFLAG_FETCHING;
998     if (flags & CM_SCACHESYNC_STORESTATUS)
999         scp->flags |= CM_SCACHEFLAG_STORING;
1000     if (flags & CM_SCACHESYNC_STORESIZE)
1001         scp->flags |= CM_SCACHEFLAG_SIZESTORING;
1002     if (flags & CM_SCACHESYNC_GETCALLBACK)
1003         scp->flags |= CM_SCACHEFLAG_GETCALLBACK;
1004     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1005         scp->flags |= CM_SCACHEFLAG_DATASTORING;
1006     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1007         scp->flags |= CM_SCACHEFLAG_ASYNCSTORING;
1008     if (flags & CM_SCACHESYNC_LOCK)
1009         scp->flags |= CM_SCACHEFLAG_LOCKING;
1010
1011     /* now update the buffer pointer */
1012     if (flags & CM_SCACHESYNC_FETCHDATA) {
1013         /* ensure that the buffer isn't already in the I/O list */
1014         if (bufp) {
1015             for(qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1016                 tbufp = osi_GetQData(qdp);
1017                 osi_assert(tbufp != bufp);
1018             }
1019         }
1020
1021         /* queue a held reference to the buffer in the "reading" I/O list */
1022         qdp = osi_QDAlloc();
1023         osi_SetQData(qdp, bufp);
1024         if (bufp) {
1025             buf_Hold(bufp);
1026             bufp->cmFlags |= CM_BUF_CMFETCHING;
1027         }
1028         osi_QAdd((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1029     }
1030
1031     if (flags & CM_SCACHESYNC_STOREDATA) {
1032         /* ensure that the buffer isn't already in the I/O list */
1033         if (bufp) {
1034             for(qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1035                 tbufp = osi_GetQData(qdp);
1036                 osi_assert(tbufp != bufp);
1037             }
1038         }
1039
1040         /* queue a held reference to the buffer in the "writing" I/O list */
1041         qdp = osi_QDAlloc();
1042         osi_SetQData(qdp, bufp);
1043         if (bufp) {
1044             buf_Hold(bufp);
1045             bufp->cmFlags |= CM_BUF_CMSTORING;
1046         }
1047         osi_QAdd((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1048     }
1049
1050     return 0;
1051 }
1052
1053 /* for those syncops that setup for RPCs.
1054  * Called with scache locked.
1055  */
1056 void cm_SyncOpDone(cm_scache_t *scp, cm_buf_t *bufp, afs_uint32 flags)
1057 {
1058     osi_queueData_t *qdp;
1059     cm_buf_t *tbufp;
1060
1061     /* now, update the recorded state for RPC-type calls */
1062     if (flags & CM_SCACHESYNC_FETCHSTATUS)
1063         scp->flags &= ~CM_SCACHEFLAG_FETCHING;
1064     if (flags & CM_SCACHESYNC_STORESTATUS)
1065         scp->flags &= ~CM_SCACHEFLAG_STORING;
1066     if (flags & CM_SCACHESYNC_STORESIZE)
1067         scp->flags &= ~CM_SCACHEFLAG_SIZESTORING;
1068     if (flags & CM_SCACHESYNC_GETCALLBACK)
1069         scp->flags &= ~CM_SCACHEFLAG_GETCALLBACK;
1070     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1071         scp->flags &= ~CM_SCACHEFLAG_DATASTORING;
1072     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1073         scp->flags &= ~CM_SCACHEFLAG_ASYNCSTORING;
1074     if (flags & CM_SCACHESYNC_LOCK)
1075         scp->flags &= ~CM_SCACHEFLAG_LOCKING;
1076
1077     /* now update the buffer pointer */
1078     if (flags & CM_SCACHESYNC_FETCHDATA) {
1079         /* ensure that the buffer isn't already in the I/O list */
1080         for(qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1081             tbufp = osi_GetQData(qdp);
1082             if (tbufp == bufp) break;
1083         }
1084         osi_assert(qdp != NULL);
1085         osi_assert(osi_GetQData(qdp) == bufp);
1086         osi_QRemove((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1087         osi_QDFree(qdp);
1088         if (bufp) {
1089             bufp->cmFlags &= ~(CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED);
1090             if (bufp->flags & CM_BUF_WAITING) {
1091                 osi_Log2(afsd_logp, "CM SyncOpDone Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1092                 osi_Wakeup((LONG_PTR) &bufp);
1093             }
1094             buf_Release(bufp);
1095         }
1096     }
1097
1098     /* now update the buffer pointer */
1099     if (flags & CM_SCACHESYNC_STOREDATA) {
1100         /* ensure that the buffer isn't already in the I/O list */
1101         for(qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1102             tbufp = osi_GetQData(qdp);
1103             if (tbufp == bufp) break;
1104         }
1105         osi_assert(qdp != NULL);
1106         osi_assert(osi_GetQData(qdp) == bufp);
1107         osi_QRemove((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1108         osi_QDFree(qdp);
1109         if (bufp) {
1110             bufp->cmFlags &= ~CM_BUF_CMSTORING;
1111             if (bufp->flags & CM_BUF_WAITING) {
1112                 osi_Log2(afsd_logp, "CM SyncOpDone Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1113                 osi_Wakeup((LONG_PTR) &bufp);
1114             }
1115             buf_Release(bufp);
1116         }
1117     }
1118
1119     /* and wakeup anyone who is waiting */
1120     if (scp->flags & CM_SCACHEFLAG_WAITING) {
1121         osi_Log1(afsd_logp, "CM SyncOpDone Waking scp 0x%p", scp);
1122         osi_Wakeup((LONG_PTR) &scp->flags);
1123     }
1124 }       
1125
1126 /* merge in a response from an RPC.  The scp must be locked, and the callback
1127  * is optional.
1128  *
1129  * Don't overwrite any status info that is dirty, since we could have a store
1130  * operation (such as store data) that merges some info in, and we don't want
1131  * to lose the local updates.  Typically, there aren't many updates we do
1132  * locally, anyway, probably only mtime.
1133  *
1134  * There is probably a bug in here where a chmod (which doesn't change
1135  * serverModTime) that occurs between two fetches, both of whose responses are
1136  * handled after the callback breaking is done, but only one of whose calls
1137  * started before that, can cause old info to be merged from the first call.
1138  */
1139 void cm_MergeStatus(cm_scache_t *scp, AFSFetchStatus *statusp, AFSVolSync *volp,
1140                     cm_user_t *userp, afs_uint32 flags)
1141 {
1142     // yj: i want to create some fake status for the /afs directory and the
1143     // entries under that directory
1144 #ifdef AFS_FREELANCE_CLIENT
1145     if (cm_freelanceEnabled && scp == cm_data.rootSCachep) {
1146         osi_Log0(afsd_logp,"cm_MergeStatus Freelance cm_data.rootSCachep");
1147         statusp->InterfaceVersion = 0x1;
1148         statusp->FileType = CM_SCACHETYPE_DIRECTORY;
1149         statusp->LinkCount = scp->linkCount;
1150         statusp->Length = cm_fakeDirSize;
1151         statusp->DataVersion = cm_data.fakeDirVersion;
1152         statusp->Author = 0x1;
1153         statusp->Owner = 0x0;
1154         statusp->CallerAccess = 0x9;
1155         statusp->AnonymousAccess = 0x9;
1156         statusp->UnixModeBits = 0x1ff;
1157         statusp->ParentVnode = 0x1;
1158         statusp->ParentUnique = 0x1;
1159         statusp->ResidencyMask = 0;
1160         statusp->ClientModTime = FakeFreelanceModTime;
1161         statusp->ServerModTime = FakeFreelanceModTime;
1162         statusp->Group = 0;
1163         statusp->SyncCounter = 0;
1164         statusp->dataVersionHigh = 0;
1165     }
1166 #endif /* AFS_FREELANCE_CLIENT */
1167
1168     if (!(flags & CM_MERGEFLAG_FORCE)
1169          && statusp->DataVersion < (unsigned long) scp->dataVersion) {
1170         struct cm_cell *cellp;
1171
1172         cellp = cm_FindCellByID(scp->fid.cell);
1173         if (scp->cbServerp) {
1174             struct cm_volume *volp = NULL;
1175
1176             cm_GetVolumeByID(cellp, scp->fid.volume, userp,
1177                               (cm_req_t *) NULL, &volp);
1178             osi_Log2(afsd_logp, "old data from server %x volume %s",
1179                       scp->cbServerp->addr.sin_addr.s_addr,
1180                       volp ? volp->namep : "(unknown)");
1181             if (volp)
1182                 cm_PutVolume(volp);
1183         }
1184         osi_Log3(afsd_logp, "Bad merge, scp %x, scp dv %d, RPC dv %d",
1185                   scp, scp->dataVersion, statusp->DataVersion);
1186         /* we have a number of data fetch/store operations running
1187          * concurrently, and we can tell which one executed last at the
1188          * server by its mtime.
1189          * Choose the one with the largest mtime, and ignore the rest.
1190          *
1191          * These concurrent calls are incompatible with setting the
1192          * mtime, so we won't have a locally changed mtime here.
1193          *
1194          * We could also have ACL info for a different user than usual,
1195          * in which case we have to do that part of the merge, anyway.
1196          * We won't have to worry about the info being old, since we
1197          * won't have concurrent calls
1198          * that change file status running from this machine.
1199          *
1200          * Added 3/17/98:  if we see data version regression on an RO
1201          * file, it's probably due to a server holding an out-of-date
1202          * replica, rather than to concurrent RPC's.  Failures to
1203          * release replicas are now flagged by the volserver, but only
1204          * since AFS 3.4 5.22, so there are plenty of clients getting
1205          * out-of-date replicas out there.
1206          *
1207          * If we discover an out-of-date replica, by this time it's too
1208          * late to go to another server and retry.  Also, we can't
1209          * reject the merge, because then there is no way for
1210          * GetAccess to do its work, and the caller gets into an
1211          * infinite loop.  So we just grin and bear it.
1212          */
1213         if (!(scp->flags & CM_SCACHEFLAG_RO))
1214             return;
1215     }       
1216     scp->serverModTime = statusp->ServerModTime;
1217
1218     if (!(scp->mask & CM_SCACHEMASK_CLIENTMODTIME)) {
1219         scp->clientModTime = statusp->ClientModTime;
1220     }
1221     if (!(scp->mask & CM_SCACHEMASK_LENGTH)) {
1222         scp->length.LowPart = statusp->Length;
1223         scp->length.HighPart = 0;
1224     }
1225
1226     scp->serverLength.LowPart = statusp->Length;
1227     scp->serverLength.HighPart = 0;
1228
1229     scp->linkCount = statusp->LinkCount;
1230     scp->dataVersion = statusp->DataVersion;
1231     scp->owner = statusp->Owner;
1232     scp->group = statusp->Group;
1233     scp->unixModeBits = statusp->UnixModeBits & 07777;
1234
1235     if (statusp->FileType == File)
1236         scp->fileType = CM_SCACHETYPE_FILE;
1237     else if (statusp->FileType == Directory)
1238         scp->fileType = CM_SCACHETYPE_DIRECTORY;
1239     else if (statusp->FileType == SymbolicLink) {
1240         if ((scp->unixModeBits & 0111) == 0)
1241             scp->fileType = CM_SCACHETYPE_MOUNTPOINT;
1242         else
1243             scp->fileType = CM_SCACHETYPE_SYMLINK;
1244     }       
1245     else {
1246         osi_Log1(afsd_logp, "Merge, Invalid File Type, scp %x", scp);
1247         scp->fileType = 0;      /* invalid */
1248     }
1249     /* and other stuff */
1250     scp->parentVnode = statusp->ParentVnode;
1251     scp->parentUnique = statusp->ParentUnique;
1252         
1253     /* and merge in the private acl cache info, if this is more than the public
1254      * info; merge in the public stuff in any case.
1255      */
1256     scp->anyAccess = statusp->AnonymousAccess;
1257
1258     if (userp != NULL) {
1259         cm_AddACLCache(scp, userp, statusp->CallerAccess);
1260     }
1261 }
1262
1263 /* note that our stat cache info is incorrect, so force us eventually
1264  * to stat the file again.  There may be dirty data associated with
1265  * this vnode, and we want to preserve that information.
1266  *
1267  * This function works by simply simulating a loss of the callback.
1268  *
1269  * This function must be called with the scache locked.
1270  */
1271 void cm_DiscardSCache(cm_scache_t *scp)
1272 {
1273     lock_AssertMutex(&scp->mx);
1274     if (scp->cbServerp) {
1275         cm_PutServer(scp->cbServerp);
1276         scp->cbServerp = NULL;
1277     }
1278     scp->cbExpires = 0;
1279     scp->flags &= ~CM_SCACHEFLAG_CALLBACK;
1280     cm_dnlcPurgedp(scp);
1281     cm_dnlcPurgevp(scp);
1282     cm_FreeAllACLEnts(scp);
1283
1284     /* Force mount points and symlinks to be re-evaluated */
1285     scp->mountPointStringp[0] = '\0';
1286 }
1287
1288 void cm_AFSFidFromFid(AFSFid *afsFidp, cm_fid_t *fidp)
1289 {
1290     afsFidp->Volume = fidp->volume;
1291     afsFidp->Vnode = fidp->vnode;
1292     afsFidp->Unique = fidp->unique;
1293 }       
1294
1295 void cm_HoldSCacheNoLock(cm_scache_t *scp)
1296 {
1297     osi_assert(scp != 0);
1298     osi_assert(scp->refCount >= 0);
1299     scp->refCount++;
1300 }
1301
1302 void cm_HoldSCache(cm_scache_t *scp)
1303 {
1304     osi_assert(scp != 0);
1305     lock_ObtainWrite(&cm_scacheLock);
1306     osi_assert(scp->refCount >= 0);
1307     scp->refCount++;
1308     lock_ReleaseWrite(&cm_scacheLock);
1309 }
1310
1311 void cm_ReleaseSCacheNoLock(cm_scache_t *scp)
1312 {
1313     osi_assert(scp != 0);
1314     osi_assert(scp->refCount-- >= 0);
1315 }
1316
1317 void cm_ReleaseSCache(cm_scache_t *scp)
1318 {
1319     osi_assert(scp != 0);
1320     lock_ObtainWrite(&cm_scacheLock);
1321     osi_assert(scp->refCount != 0);
1322     scp->refCount--;
1323     lock_ReleaseWrite(&cm_scacheLock);
1324 }
1325
1326 /* just look for the scp entry to get filetype */
1327 /* doesn't need to be perfectly accurate, so locking doesn't matter too much */
1328 int cm_FindFileType(cm_fid_t *fidp)
1329 {
1330     long hash;
1331     cm_scache_t *scp;
1332         
1333     hash = CM_SCACHE_HASH(fidp);
1334         
1335     osi_assert(fidp->cell != 0);
1336
1337     lock_ObtainWrite(&cm_scacheLock);
1338     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
1339         if (cm_FidCmp(fidp, &scp->fid) == 0) {
1340             lock_ReleaseWrite(&cm_scacheLock);
1341             return scp->fileType;
1342         }
1343     }
1344     lock_ReleaseWrite(&cm_scacheLock);
1345     return 0;
1346 }
1347
1348 /* dump all scp's that have reference count > 0 to a file. 
1349  * cookie is used to identify this batch for easy parsing, 
1350  * and it a string provided by a caller 
1351  */
1352 int cm_DumpSCache(FILE *outputFile, char *cookie, int lock)
1353 {
1354     int zilch;
1355     cm_scache_t *scp;
1356     char output[1024];
1357     int i;
1358   
1359     if (lock)
1360         lock_ObtainRead(&cm_scacheLock);
1361   
1362     sprintf(output, "%s - dumping scache - cm_data.currentSCaches=%d, cm_data.maxSCaches=%d\n", cookie, cm_data.currentSCaches, cm_data.maxSCaches);
1363     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1364   
1365     for (scp = cm_data.scacheLRULastp; scp; scp = (cm_scache_t *) osi_QPrev(&scp->q)) 
1366     {
1367         if (scp->refCount != 0)
1368         {
1369             sprintf(output, "%s fid (cell=%d, volume=%d, vnode=%d, unique=%d) refCount=%u\n", 
1370                     cookie, scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique, 
1371                     scp->refCount);
1372             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1373         }
1374     }
1375   
1376     sprintf(output, "%s - dumping cm_data.hashTable - cm_data.hashTableSize=%d\n", cookie, cm_data.hashTableSize);
1377     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1378   
1379     for (i = 0; i < cm_data.hashTableSize; i++)
1380     {
1381         for(scp = cm_data.hashTablep[i]; scp; scp=scp->nextp) 
1382         {
1383             if (scp->refCount != 0)
1384             {
1385                 sprintf(output, "%s scp=0x%p, hash=%d, fid (cell=%d, volume=%d, vnode=%d, unique=%d) refCount=%u\n", 
1386                          cookie, scp, i, scp->fid.cell, scp->fid.volume, scp->fid.vnode, 
1387                          scp->fid.unique, scp->refCount);
1388                 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1389             }
1390         }
1391     }
1392
1393     sprintf(output, "%s - Done dumping scache.\n", cookie);
1394     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1395   
1396     if (lock)
1397         lock_ReleaseRead(&cm_scacheLock);       
1398     return (0);     
1399 }
1400