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