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