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