windows-largefile-support-20060623
[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         scp->length.HighPart = 0;
555         strncpy(scp->mountPointStringp,mp,MOUNTPOINTLEN);
556         scp->mountPointStringp[MOUNTPOINTLEN-1] = '\0';
557         lock_ReleaseMutex(&cm_Freelance_Lock);
558
559         scp->owner=0x0;
560         scp->unixModeBits=0x1ff;
561         scp->clientModTime=FakeFreelanceModTime;
562         scp->serverModTime=FakeFreelanceModTime;
563         scp->parentUnique = 0x1;
564         scp->parentVnode=0x1;
565         scp->group=0;
566         scp->dataVersion=cm_data.fakeDirVersion;
567         scp->lockDataVersion=-1; /* no lock yet */
568         lock_ReleaseMutex(&scp->mx);
569         *outScpp = scp;
570         lock_ReleaseWrite(&cm_scacheLock);
571         return 0;
572     }
573     // end of yj code
574 #endif /* AFS_FREELANCE_CLIENT */
575
576     /* otherwise, we need to find the volume */
577     if (!cm_freelanceEnabled || !isRoot) {
578         lock_ReleaseWrite(&cm_scacheLock);      /* for perf. reasons */
579         cellp = cm_FindCellByID(fidp->cell);
580         if (!cellp) 
581             return CM_ERROR_NOSUCHCELL;
582
583         code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, &volp);
584         if (code) 
585             return code;
586         lock_ObtainWrite(&cm_scacheLock);
587     }
588         
589     /* otherwise, we have the volume, now reverify that the scp doesn't
590      * exist, and proceed.
591      */
592     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
593         if (cm_FidCmp(fidp, &scp->fid) == 0) {
594             cm_HoldSCacheNoLock(scp);
595             osi_assert(scp->volp == volp);
596             cm_AdjustLRU(scp);
597             lock_ReleaseWrite(&cm_scacheLock);
598             if (volp)
599                 cm_PutVolume(volp);
600             *outScpp = scp;
601             return 0;
602         }
603     }
604         
605     /* now, if we don't have the fid, recycle something */
606     scp = cm_GetNewSCache();
607     osi_assert(!(scp->flags & CM_SCACHEFLAG_INHASH));
608     lock_ObtainMutex(&scp->mx);
609     scp->fid = *fidp;
610     scp->volp = volp;   /* a held reference */
611
612     if (!cm_freelanceEnabled || !isRoot) {
613         /* if this scache entry represents a volume root then we need 
614          * to copy the dotdotFipd from the volume structure where the 
615          * "master" copy is stored (defect 11489)
616          */
617         if (scp->fid.vnode == 1 && scp->fid.unique == 1) {
618             scp->dotdotFid = volp->dotdotFid;
619         }
620           
621         if (volp->roID == fidp->volume)
622             scp->flags |= (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO);
623         else if (volp->bkID == fidp->volume)
624             scp->flags |= CM_SCACHEFLAG_RO;
625     }
626     scp->nextp = cm_data.hashTablep[hash];
627     cm_data.hashTablep[hash] = scp;
628     scp->flags |= CM_SCACHEFLAG_INHASH;
629     scp->refCount = 1;
630     lock_ReleaseMutex(&scp->mx);
631
632     /* XXX - The following fields in the cm_scache are 
633      * uninitialized:
634      *   fileType
635      *   parentVnode
636      *   parentUnique
637      */
638     lock_ReleaseWrite(&cm_scacheLock);
639         
640     /* now we have a held scache entry; just return it */
641     *outScpp = scp;
642     return 0;
643 }
644
645 /* Returns a held reference to the scache's parent 
646  * if it exists */
647 cm_scache_t * cm_FindSCacheParent(cm_scache_t * scp)
648 {
649     long code = 0;
650     int i;
651     cm_fid_t    parent_fid;
652     cm_scache_t * pscp = NULL;
653
654     lock_ObtainWrite(&cm_scacheLock);
655     parent_fid = scp->fid;
656     parent_fid.vnode = scp->parentVnode;
657     parent_fid.unique = scp->parentUnique;
658
659     if (cm_FidCmp(&scp->fid, &parent_fid)) {
660         for (i=0; i<cm_data.hashTableSize; i++) {
661             for (pscp = cm_data.hashTablep[i]; pscp; pscp = pscp->nextp) {
662                 if (!cm_FidCmp(&pscp->fid, &parent_fid)) {
663                     cm_HoldSCacheNoLock(pscp);
664                     break;
665                 }
666             }
667         }
668     }
669     lock_ReleaseWrite(&cm_scacheLock);
670
671     return pscp;
672 }
673
674 /* synchronize a fetch, store, read, write, fetch status or store status.
675  * Called with scache mutex held, and returns with it held, but temporarily
676  * drops it during the fetch.
677  * 
678  * At most one flag can be on in flags, if this is an RPC request.
679  *
680  * Also, if we're fetching or storing data, we must ensure that we have a buffer.
681  *
682  * There are a lot of weird restrictions here; here's an attempt to explain the
683  * rationale for the concurrency restrictions implemented in this function.
684  *
685  * First, although the file server will break callbacks when *another* machine
686  * modifies a file or status block, the client itself is responsible for
687  * concurrency control on its own requests.  Callback breaking events are rare,
688  * and simply invalidate any concurrent new status info.
689  *
690  * In the absence of callback breaking messages, we need to know how to
691  * synchronize incoming responses describing updates to files.  We synchronize
692  * operations that update the data version by comparing the data versions.
693  * However, updates that do not update the data, but only the status, can't be
694  * synchronized with fetches or stores, since there's nothing to compare
695  * to tell which operation executed first at the server.
696  *
697  * Thus, we can allow multiple ops that change file data, or dir data, and
698  * fetches.  However, status storing ops have to be done serially.
699  *
700  * Furthermore, certain data-changing ops are incompatible: we can't read or
701  * write a buffer while doing a truncate.  We can't read and write the same
702  * buffer at the same time, or write while fetching or storing, or read while
703  * fetching a buffer (this may change).  We can't fetch and store at the same
704  * time, either.
705  *
706  * With respect to status, we can't read and write at the same time, read while
707  * fetching, write while fetching or storing, or fetch and store at the same time.
708  *
709  * We can't allow a get callback RPC to run in concurrently with something that
710  * will return updated status, since we could start a call, have the server
711  * return status, have another machine make an update to the status (which
712  * doesn't change serverModTime), have the original machine get a new callback,
713  * and then have the original machine merge in the early, old info from the
714  * first call.  At this point, the easiest way to avoid this problem is to have
715  * getcallback calls conflict with all others for the same vnode.  Other calls
716  * to cm_MergeStatus that aren't associated with calls to cm_SyncOp on the same
717  * vnode must be careful not to merge in their status unless they have obtained
718  * a callback from the start of their call.
719  *
720  * Note added 1/23/96
721  * Concurrent StoreData RPC's can cause trouble if the file is being extended.
722  * Each such RPC passes a FileLength parameter, which the server uses to do
723  * pre-truncation if necessary.  So if two RPC's are processed out of order at
724  * the server, the one with the smaller FileLength will be processed last,
725  * possibly resulting in a bogus truncation.  The simplest way to avoid this
726  * is to serialize all StoreData RPC's.  This is the reason we defined
727  * CM_SCACHESYNC_STOREDATA_EXCL and CM_SCACHEFLAG_DATASTORING.
728  */
729 long cm_SyncOp(cm_scache_t *scp, cm_buf_t *bufp, cm_user_t *userp, cm_req_t *reqp,
730                afs_uint32 rights, afs_uint32 flags)
731 {
732     osi_queueData_t *qdp;
733     long code;
734     cm_buf_t *tbufp;
735     afs_uint32 outRights;
736     int bufLocked;
737
738     /* lookup this first */
739     bufLocked = flags & CM_SCACHESYNC_BUFLOCKED;
740
741     /* some minor assertions */
742     if (flags & (CM_SCACHESYNC_STOREDATA | CM_SCACHESYNC_FETCHDATA
743                   | CM_SCACHESYNC_READ | CM_SCACHESYNC_WRITE
744                   | CM_SCACHESYNC_SETSIZE)) {
745         if (bufp) {
746             osi_assert(bufp->refCount > 0);
747             /*
748                osi_assert(cm_FidCmp(&bufp->fid, &scp->fid) == 0);
749              */
750         }
751     }
752     else osi_assert(bufp == NULL);
753
754     /* Do the access check.  Now we don't really do the access check
755      * atomically, since the caller doesn't expect the parent dir to be
756      * returned locked, and that is what we'd have to do to prevent a
757      * callback breaking message on the parent due to a setacl call from
758      * being processed while we're running.  So, instead, we check things
759      * here, and if things look fine with the access, we proceed to finish
760      * the rest of this check.  Sort of a hack, but probably good enough.
761      */
762
763     while (1) {
764         if (flags & CM_SCACHESYNC_FETCHSTATUS) {
765             /* if we're bringing in a new status block, ensure that
766              * we aren't already doing so, and that no one is
767              * changing the status concurrently, either.  We need
768              * to do this, even if the status is of a different
769              * type, since we don't have the ability to figure out,
770              * in the AFS 3 protocols, which status-changing
771              * operation ran first, or even which order a read and
772              * a write occurred in.
773              */
774             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
775                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
776                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want FETCHSTATUS", scp);
777                 goto sleep;
778             }
779         }
780         if (flags & (CM_SCACHESYNC_STORESIZE | CM_SCACHESYNC_STORESTATUS
781                       | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_GETCALLBACK)) {
782             /* if we're going to make an RPC to change the status, make sure
783              * that no one is bringing in or sending out the status.
784              */
785             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING |
786                               CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
787                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
788                 goto sleep;
789             }
790             if (scp->bufReadsp || scp->bufWritesp) {
791                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is bufRead|bufWrite want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
792                 goto sleep;
793             }
794         }
795         if (flags & CM_SCACHESYNC_FETCHDATA) {
796             /* if we're bringing in a new chunk of data, make sure that
797              * nothing is happening to that chunk, and that we aren't
798              * changing the basic file status info, either.
799              */
800             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
801                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
802                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want FETCHDATA", scp);
803                 goto sleep;
804             }
805             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
806                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want FETCHDATA", scp, bufp);
807                 goto sleep;
808             }
809         }
810         if (flags & CM_SCACHESYNC_STOREDATA) {
811             /* same as fetch data */
812             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
813                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
814                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STOREDATA", scp);
815                 goto sleep;
816             }
817             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
818                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want STOREDATA", scp, bufp);
819                 goto sleep;
820             }
821         }
822
823         if (flags & CM_SCACHESYNC_STOREDATA_EXCL) {
824             /* Don't allow concurrent StoreData RPC's */
825             if (scp->flags & CM_SCACHEFLAG_DATASTORING) {
826                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is DATASTORING want STOREDATA_EXCL", scp);
827                 goto sleep;
828             }
829         }
830
831         if (flags & CM_SCACHESYNC_ASYNCSTORE) {
832             /* Don't allow more than one BKG store request */
833             if (scp->flags & CM_SCACHEFLAG_ASYNCSTORING) {
834                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is ASYNCSTORING want ASYNCSTORE", scp);
835                 goto sleep;
836             }
837         }
838
839         if (flags & CM_SCACHESYNC_LOCK) {
840             /* Don't allow concurrent fiddling with lock lists */
841             if (scp->flags & CM_SCACHEFLAG_LOCKING) {
842                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is LOCKING want LOCK", scp);
843                 goto sleep;
844             }
845         }
846
847         /* now the operations that don't correspond to making RPCs */
848         if (flags & CM_SCACHESYNC_GETSTATUS) {
849             /* we can use the status that's here, if we're not
850              * bringing in new status.
851              */
852             if (scp->flags & (CM_SCACHEFLAG_FETCHING)) {
853                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want GETSTATUS", scp);
854                 goto sleep;
855             }
856         }
857         if (flags & CM_SCACHESYNC_SETSTATUS) {
858             /* we can make a change to the local status, as long as
859              * the status isn't changing now.
860              *
861              * If we're fetching or storing a chunk of data, we can
862              * change the status locally, since the fetch/store
863              * operations don't change any of the data that we're
864              * changing here.
865              */
866             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING | CM_SCACHEFLAG_SIZESTORING)) {
867                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING want SETSTATUS", scp);
868                 goto sleep;
869             }
870         }
871         if (flags & CM_SCACHESYNC_READ) {
872             /* we're going to read the data, make sure that the
873              * status is available, and that the data is here.  It
874              * is OK to read while storing the data back.
875              */
876             if (scp->flags & CM_SCACHEFLAG_FETCHING) {
877                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want READ", scp);
878                 goto sleep;
879             }
880             if (bufp && ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == CM_BUF_CMFETCHING)) {
881                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING want READ", scp, bufp);
882                 goto sleep;
883             }
884         }
885         if (flags & CM_SCACHESYNC_WRITE) {
886             /* don't write unless the status is stable and the chunk
887              * is stable.
888              */
889             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
890                                | CM_SCACHEFLAG_SIZESTORING)) {
891                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING want WRITE", scp);
892                 goto sleep;
893             }
894             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING))) {
895                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING want WRITE", scp, bufp);
896                 goto sleep;
897             }
898         }
899
900         // yj: modified this so that callback only checked if we're
901         // not checking something on /afs
902         /* fix the conditional to match the one in cm_HaveCallback */
903         if (  (flags & CM_SCACHESYNC_NEEDCALLBACK)
904 #ifdef AFS_FREELANCE_CLIENT
905              && (!cm_freelanceEnabled || 
906                   !(scp->fid.vnode==0x1 && scp->fid.unique==0x1) ||
907                   scp->fid.cell!=AFS_FAKE_ROOT_CELL_ID ||
908                   scp->fid.volume!=AFS_FAKE_ROOT_VOL_ID ||
909                   cm_fakeDirCallback < 2)
910 #endif /* AFS_FREELANCE_CLIENT */
911              ) {
912             if (!cm_HaveCallback(scp)) {
913                 osi_Log1(afsd_logp, "CM SyncOp getting callback on scp 0x%p",
914                           scp);
915                 if (bufLocked) 
916                     lock_ReleaseMutex(&bufp->mx);
917                 code = cm_GetCallback(scp, userp, reqp, 0);
918                 if (bufLocked) {
919                     lock_ReleaseMutex(&scp->mx);
920                     lock_ObtainMutex(&bufp->mx);
921                     lock_ObtainMutex(&scp->mx);
922                 }
923                 if (code) 
924                     return code;
925                 continue;
926             }
927         }
928
929         if (rights) {
930             /* can't check access rights without a callback */
931             osi_assert(flags & CM_SCACHESYNC_NEEDCALLBACK);
932
933             if ((rights & PRSFS_WRITE) && (scp->flags & CM_SCACHEFLAG_RO))
934                 return CM_ERROR_READONLY;
935
936             if (cm_HaveAccessRights(scp, userp, rights, &outRights)) {
937                 if (~outRights & rights) 
938                     return CM_ERROR_NOACCESS;
939             }
940             else {
941                 /* we don't know the required access rights */
942                 if (bufLocked) lock_ReleaseMutex(&bufp->mx);
943                 code = cm_GetAccessRights(scp, userp, reqp);
944                 if (bufLocked) {
945                     lock_ReleaseMutex(&scp->mx);
946                     lock_ObtainMutex(&bufp->mx);
947                     lock_ObtainMutex(&scp->mx);
948                 }
949                 if (code) 
950                     return code;
951                 continue;
952             }
953         }
954
955         /* if we get here, we're happy */
956         break;
957
958       sleep:
959         /* first check if we're not supposed to wait: fail 
960          * in this case, returning with everything still locked.
961          */
962         if (flags & CM_SCACHESYNC_NOWAIT) 
963             return CM_ERROR_WOULDBLOCK;
964
965         /* wait here, then try again */
966         osi_Log1(afsd_logp, "CM SyncOp sleeping scp 0x%p", scp);
967         if ( scp->flags & CM_SCACHEFLAG_WAITING ) {
968             scp->waitCount++;
969             scp->waitRequests++;
970             osi_Log3(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING already set for 0x%p; %d threads; %d requests", 
971                      scp, scp->waitCount, scp->waitRequests);
972         } else {
973             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING set for 0x%p", scp);
974             scp->flags |= CM_SCACHEFLAG_WAITING;
975             scp->waitCount = scp->waitRequests = 1;
976         }
977         if (bufLocked) 
978             lock_ReleaseMutex(&bufp->mx);
979         osi_SleepM((LONG_PTR) &scp->flags, &scp->mx);
980
981         smb_UpdateServerPriority();
982
983         if (bufLocked) 
984             lock_ObtainMutex(&bufp->mx);
985         lock_ObtainMutex(&scp->mx);
986         scp->waitCount--;
987         osi_Log3(afsd_logp, "CM SyncOp woke! scp 0x%p; still waiting %d threads of %d requests", 
988                  scp, scp->waitCount, scp->waitRequests);
989         if (scp->waitCount == 0) {
990             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING reset for 0x%p", scp);
991             scp->flags &= ~CM_SCACHEFLAG_WAITING;
992             scp->waitRequests = 0;
993         }
994     } /* big while loop */
995         
996     /* now, update the recorded state for RPC-type calls */
997     if (flags & CM_SCACHESYNC_FETCHSTATUS)
998         scp->flags |= CM_SCACHEFLAG_FETCHING;
999     if (flags & CM_SCACHESYNC_STORESTATUS)
1000         scp->flags |= CM_SCACHEFLAG_STORING;
1001     if (flags & CM_SCACHESYNC_STORESIZE)
1002         scp->flags |= CM_SCACHEFLAG_SIZESTORING;
1003     if (flags & CM_SCACHESYNC_GETCALLBACK)
1004         scp->flags |= CM_SCACHEFLAG_GETCALLBACK;
1005     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1006         scp->flags |= CM_SCACHEFLAG_DATASTORING;
1007     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1008         scp->flags |= CM_SCACHEFLAG_ASYNCSTORING;
1009     if (flags & CM_SCACHESYNC_LOCK)
1010         scp->flags |= CM_SCACHEFLAG_LOCKING;
1011
1012     /* now update the buffer pointer */
1013     if (flags & CM_SCACHESYNC_FETCHDATA) {
1014         /* ensure that the buffer isn't already in the I/O list */
1015         if (bufp) {
1016             for(qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1017                 tbufp = osi_GetQData(qdp);
1018                 osi_assert(tbufp != bufp);
1019             }
1020         }
1021
1022         /* queue a held reference to the buffer in the "reading" I/O list */
1023         qdp = osi_QDAlloc();
1024         osi_SetQData(qdp, bufp);
1025         if (bufp) {
1026             buf_Hold(bufp);
1027             bufp->cmFlags |= CM_BUF_CMFETCHING;
1028         }
1029         osi_QAdd((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1030     }
1031
1032     if (flags & CM_SCACHESYNC_STOREDATA) {
1033         /* ensure that the buffer isn't already in the I/O list */
1034         if (bufp) {
1035             for(qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1036                 tbufp = osi_GetQData(qdp);
1037                 osi_assert(tbufp != bufp);
1038             }
1039         }
1040
1041         /* queue a held reference to the buffer in the "writing" I/O list */
1042         qdp = osi_QDAlloc();
1043         osi_SetQData(qdp, bufp);
1044         if (bufp) {
1045             buf_Hold(bufp);
1046             bufp->cmFlags |= CM_BUF_CMSTORING;
1047         }
1048         osi_QAdd((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1049     }
1050
1051     return 0;
1052 }
1053
1054 /* for those syncops that setup for RPCs.
1055  * Called with scache locked.
1056  */
1057 void cm_SyncOpDone(cm_scache_t *scp, cm_buf_t *bufp, afs_uint32 flags)
1058 {
1059     osi_queueData_t *qdp;
1060     cm_buf_t *tbufp;
1061
1062     /* now, update the recorded state for RPC-type calls */
1063     if (flags & CM_SCACHESYNC_FETCHSTATUS)
1064         scp->flags &= ~CM_SCACHEFLAG_FETCHING;
1065     if (flags & CM_SCACHESYNC_STORESTATUS)
1066         scp->flags &= ~CM_SCACHEFLAG_STORING;
1067     if (flags & CM_SCACHESYNC_STORESIZE)
1068         scp->flags &= ~CM_SCACHEFLAG_SIZESTORING;
1069     if (flags & CM_SCACHESYNC_GETCALLBACK)
1070         scp->flags &= ~CM_SCACHEFLAG_GETCALLBACK;
1071     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1072         scp->flags &= ~CM_SCACHEFLAG_DATASTORING;
1073     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1074         scp->flags &= ~CM_SCACHEFLAG_ASYNCSTORING;
1075     if (flags & CM_SCACHESYNC_LOCK)
1076         scp->flags &= ~CM_SCACHEFLAG_LOCKING;
1077
1078     /* now update the buffer pointer */
1079     if (flags & CM_SCACHESYNC_FETCHDATA) {
1080         /* ensure that the buffer isn't already in the I/O list */
1081         for(qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1082             tbufp = osi_GetQData(qdp);
1083             if (tbufp == bufp) break;
1084         }
1085         osi_assert(qdp != NULL);
1086         osi_assert(osi_GetQData(qdp) == bufp);
1087         osi_QRemove((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1088         osi_QDFree(qdp);
1089         if (bufp) {
1090             bufp->cmFlags &= ~(CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED);
1091             if (bufp->flags & CM_BUF_WAITING) {
1092                 osi_Log2(afsd_logp, "CM SyncOpDone Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1093                 osi_Wakeup((LONG_PTR) &bufp);
1094             }
1095             buf_Release(bufp);
1096         }
1097     }
1098
1099     /* now update the buffer pointer */
1100     if (flags & CM_SCACHESYNC_STOREDATA) {
1101         /* ensure that the buffer isn't already in the I/O list */
1102         for(qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1103             tbufp = osi_GetQData(qdp);
1104             if (tbufp == bufp) break;
1105         }
1106         osi_assert(qdp != NULL);
1107         osi_assert(osi_GetQData(qdp) == bufp);
1108         osi_QRemove((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1109         osi_QDFree(qdp);
1110         if (bufp) {
1111             bufp->cmFlags &= ~CM_BUF_CMSTORING;
1112             if (bufp->flags & CM_BUF_WAITING) {
1113                 osi_Log2(afsd_logp, "CM SyncOpDone Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1114                 osi_Wakeup((LONG_PTR) &bufp);
1115             }
1116             buf_Release(bufp);
1117         }
1118     }
1119
1120     /* and wakeup anyone who is waiting */
1121     if (scp->flags & CM_SCACHEFLAG_WAITING) {
1122         osi_Log1(afsd_logp, "CM SyncOpDone Waking scp 0x%p", scp);
1123         osi_Wakeup((LONG_PTR) &scp->flags);
1124     }
1125 }       
1126
1127 /* merge in a response from an RPC.  The scp must be locked, and the callback
1128  * is optional.
1129  *
1130  * Don't overwrite any status info that is dirty, since we could have a store
1131  * operation (such as store data) that merges some info in, and we don't want
1132  * to lose the local updates.  Typically, there aren't many updates we do
1133  * locally, anyway, probably only mtime.
1134  *
1135  * There is probably a bug in here where a chmod (which doesn't change
1136  * serverModTime) that occurs between two fetches, both of whose responses are
1137  * handled after the callback breaking is done, but only one of whose calls
1138  * started before that, can cause old info to be merged from the first call.
1139  */
1140 void cm_MergeStatus(cm_scache_t *scp, AFSFetchStatus *statusp, AFSVolSync *volp,
1141                     cm_user_t *userp, afs_uint32 flags)
1142 {
1143     // yj: i want to create some fake status for the /afs directory and the
1144     // entries under that directory
1145 #ifdef AFS_FREELANCE_CLIENT
1146     if (cm_freelanceEnabled && scp == cm_data.rootSCachep) {
1147         osi_Log0(afsd_logp,"cm_MergeStatus Freelance cm_data.rootSCachep");
1148         statusp->InterfaceVersion = 0x1;
1149         statusp->FileType = CM_SCACHETYPE_DIRECTORY;
1150         statusp->LinkCount = scp->linkCount;
1151         statusp->Length = cm_fakeDirSize;
1152         statusp->Length_hi = 0;
1153         statusp->DataVersion = cm_data.fakeDirVersion;
1154         statusp->Author = 0x1;
1155         statusp->Owner = 0x0;
1156         statusp->CallerAccess = 0x9;
1157         statusp->AnonymousAccess = 0x9;
1158         statusp->UnixModeBits = 0x1ff;
1159         statusp->ParentVnode = 0x1;
1160         statusp->ParentUnique = 0x1;
1161         statusp->ResidencyMask = 0;
1162         statusp->ClientModTime = FakeFreelanceModTime;
1163         statusp->ServerModTime = FakeFreelanceModTime;
1164         statusp->Group = 0;
1165         statusp->SyncCounter = 0;
1166         statusp->dataVersionHigh = 0;
1167     }
1168 #endif /* AFS_FREELANCE_CLIENT */
1169
1170     if (!(flags & CM_MERGEFLAG_FORCE)
1171          && statusp->DataVersion < (unsigned long) scp->dataVersion) {
1172         struct cm_cell *cellp;
1173
1174         cellp = cm_FindCellByID(scp->fid.cell);
1175         if (scp->cbServerp) {
1176             struct cm_volume *volp = NULL;
1177
1178             cm_GetVolumeByID(cellp, scp->fid.volume, userp,
1179                               (cm_req_t *) NULL, &volp);
1180             osi_Log2(afsd_logp, "old data from server %x volume %s",
1181                       scp->cbServerp->addr.sin_addr.s_addr,
1182                       volp ? volp->namep : "(unknown)");
1183             if (volp)
1184                 cm_PutVolume(volp);
1185         }
1186         osi_Log3(afsd_logp, "Bad merge, scp %x, scp dv %d, RPC dv %d",
1187                   scp, scp->dataVersion, statusp->DataVersion);
1188         /* we have a number of data fetch/store operations running
1189          * concurrently, and we can tell which one executed last at the
1190          * server by its mtime.
1191          * Choose the one with the largest mtime, and ignore the rest.
1192          *
1193          * These concurrent calls are incompatible with setting the
1194          * mtime, so we won't have a locally changed mtime here.
1195          *
1196          * We could also have ACL info for a different user than usual,
1197          * in which case we have to do that part of the merge, anyway.
1198          * We won't have to worry about the info being old, since we
1199          * won't have concurrent calls
1200          * that change file status running from this machine.
1201          *
1202          * Added 3/17/98:  if we see data version regression on an RO
1203          * file, it's probably due to a server holding an out-of-date
1204          * replica, rather than to concurrent RPC's.  Failures to
1205          * release replicas are now flagged by the volserver, but only
1206          * since AFS 3.4 5.22, so there are plenty of clients getting
1207          * out-of-date replicas out there.
1208          *
1209          * If we discover an out-of-date replica, by this time it's too
1210          * late to go to another server and retry.  Also, we can't
1211          * reject the merge, because then there is no way for
1212          * GetAccess to do its work, and the caller gets into an
1213          * infinite loop.  So we just grin and bear it.
1214          */
1215         if (!(scp->flags & CM_SCACHEFLAG_RO))
1216             return;
1217     }       
1218     scp->serverModTime = statusp->ServerModTime;
1219
1220     if (!(scp->mask & CM_SCACHEMASK_CLIENTMODTIME)) {
1221         scp->clientModTime = statusp->ClientModTime;
1222     }
1223     if (!(scp->mask & CM_SCACHEMASK_LENGTH)) {
1224         scp->length.LowPart = statusp->Length;
1225         scp->length.HighPart = statusp->Length_hi;
1226     }
1227
1228     scp->serverLength.LowPart = statusp->Length;
1229     scp->serverLength.HighPart = statusp->Length_hi;
1230
1231     scp->linkCount = statusp->LinkCount;
1232     scp->dataVersion = statusp->DataVersion;
1233     scp->owner = statusp->Owner;
1234     scp->group = statusp->Group;
1235     scp->unixModeBits = statusp->UnixModeBits & 07777;
1236
1237     if (statusp->FileType == File)
1238         scp->fileType = CM_SCACHETYPE_FILE;
1239     else if (statusp->FileType == Directory)
1240         scp->fileType = CM_SCACHETYPE_DIRECTORY;
1241     else if (statusp->FileType == SymbolicLink) {
1242         if ((scp->unixModeBits & 0111) == 0)
1243             scp->fileType = CM_SCACHETYPE_MOUNTPOINT;
1244         else
1245             scp->fileType = CM_SCACHETYPE_SYMLINK;
1246     }       
1247     else {
1248         osi_Log1(afsd_logp, "Merge, Invalid File Type, scp %x", scp);
1249         scp->fileType = 0;      /* invalid */
1250     }
1251     /* and other stuff */
1252     scp->parentVnode = statusp->ParentVnode;
1253     scp->parentUnique = statusp->ParentUnique;
1254         
1255     /* and merge in the private acl cache info, if this is more than the public
1256      * info; merge in the public stuff in any case.
1257      */
1258     scp->anyAccess = statusp->AnonymousAccess;
1259
1260     if (userp != NULL) {
1261         cm_AddACLCache(scp, userp, statusp->CallerAccess);
1262     }
1263 }
1264
1265 /* note that our stat cache info is incorrect, so force us eventually
1266  * to stat the file again.  There may be dirty data associated with
1267  * this vnode, and we want to preserve that information.
1268  *
1269  * This function works by simply simulating a loss of the callback.
1270  *
1271  * This function must be called with the scache locked.
1272  */
1273 void cm_DiscardSCache(cm_scache_t *scp)
1274 {
1275     lock_AssertMutex(&scp->mx);
1276     if (scp->cbServerp) {
1277         cm_PutServer(scp->cbServerp);
1278         scp->cbServerp = NULL;
1279     }
1280     scp->cbExpires = 0;
1281     scp->flags &= ~CM_SCACHEFLAG_CALLBACK;
1282     cm_dnlcPurgedp(scp);
1283     cm_dnlcPurgevp(scp);
1284     cm_FreeAllACLEnts(scp);
1285
1286     /* Force mount points and symlinks to be re-evaluated */
1287     scp->mountPointStringp[0] = '\0';
1288 }
1289
1290 void cm_AFSFidFromFid(AFSFid *afsFidp, cm_fid_t *fidp)
1291 {
1292     afsFidp->Volume = fidp->volume;
1293     afsFidp->Vnode = fidp->vnode;
1294     afsFidp->Unique = fidp->unique;
1295 }       
1296
1297 void cm_HoldSCacheNoLock(cm_scache_t *scp)
1298 {
1299     osi_assert(scp != 0);
1300     osi_assert(scp->refCount >= 0);
1301     scp->refCount++;
1302 }
1303
1304 void cm_HoldSCache(cm_scache_t *scp)
1305 {
1306     osi_assert(scp != 0);
1307     lock_ObtainWrite(&cm_scacheLock);
1308     osi_assert(scp->refCount >= 0);
1309     scp->refCount++;
1310     lock_ReleaseWrite(&cm_scacheLock);
1311 }
1312
1313 void cm_ReleaseSCacheNoLock(cm_scache_t *scp)
1314 {
1315     osi_assert(scp != 0);
1316     osi_assert(scp->refCount-- >= 0);
1317 }
1318
1319 void cm_ReleaseSCache(cm_scache_t *scp)
1320 {
1321     osi_assert(scp != 0);
1322     lock_ObtainWrite(&cm_scacheLock);
1323     osi_assert(scp->refCount != 0);
1324     scp->refCount--;
1325     lock_ReleaseWrite(&cm_scacheLock);
1326 }
1327
1328 /* just look for the scp entry to get filetype */
1329 /* doesn't need to be perfectly accurate, so locking doesn't matter too much */
1330 int cm_FindFileType(cm_fid_t *fidp)
1331 {
1332     long hash;
1333     cm_scache_t *scp;
1334         
1335     hash = CM_SCACHE_HASH(fidp);
1336         
1337     osi_assert(fidp->cell != 0);
1338
1339     lock_ObtainWrite(&cm_scacheLock);
1340     for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
1341         if (cm_FidCmp(fidp, &scp->fid) == 0) {
1342             lock_ReleaseWrite(&cm_scacheLock);
1343             return scp->fileType;
1344         }
1345     }
1346     lock_ReleaseWrite(&cm_scacheLock);
1347     return 0;
1348 }
1349
1350 /* dump all scp's that have reference count > 0 to a file. 
1351  * cookie is used to identify this batch for easy parsing, 
1352  * and it a string provided by a caller 
1353  */
1354 int cm_DumpSCache(FILE *outputFile, char *cookie, int lock)
1355 {
1356     int zilch;
1357     cm_scache_t *scp;
1358     char output[1024];
1359     int i;
1360   
1361     if (lock)
1362         lock_ObtainRead(&cm_scacheLock);
1363   
1364     sprintf(output, "%s - dumping scache - cm_data.currentSCaches=%d, cm_data.maxSCaches=%d\n", cookie, cm_data.currentSCaches, cm_data.maxSCaches);
1365     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1366   
1367     for (scp = cm_data.scacheLRULastp; scp; scp = (cm_scache_t *) osi_QPrev(&scp->q)) 
1368     {
1369         if (scp->refCount != 0)
1370         {
1371             sprintf(output, "%s fid (cell=%d, volume=%d, vnode=%d, unique=%d) refCount=%u\n", 
1372                     cookie, scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique, 
1373                     scp->refCount);
1374             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1375         }
1376     }
1377   
1378     sprintf(output, "%s - dumping cm_data.hashTable - cm_data.hashTableSize=%d\n", cookie, cm_data.hashTableSize);
1379     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1380   
1381     for (i = 0; i < cm_data.hashTableSize; i++)
1382     {
1383         for(scp = cm_data.hashTablep[i]; scp; scp=scp->nextp) 
1384         {
1385             if (scp->refCount != 0)
1386             {
1387                 sprintf(output, "%s scp=0x%p, hash=%d, fid (cell=%d, volume=%d, vnode=%d, unique=%d) refCount=%u\n", 
1388                          cookie, scp, i, scp->fid.cell, scp->fid.volume, scp->fid.vnode, 
1389                          scp->fid.unique, scp->refCount);
1390                 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1391             }
1392         }
1393     }
1394
1395     sprintf(output, "%s - Done dumping scache.\n", cookie);
1396     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
1397   
1398     if (lock)
1399         lock_ReleaseRead(&cm_scacheLock);       
1400     return (0);     
1401 }
1402