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