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