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