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