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