Initial IBM OpenAFS 1.0 tree
[openafs.git] / src / afs / afs_vcache.c
1 /* Copyright (C) 1995, 1989, 1998 Transarc Corporation - All rights reserved */
2 /*
3  * For copyright information, see IPL which you accepted in order to
4  * download this software.
5  *
6  */
7
8 /*
9  * afs_vcache.c
10  *
11  * Implements:
12  * afs_FlushVCache
13  * afs_AllocCBR
14  * afs_FreeCBR
15  * afs_FlushVCBs
16  * afs_QueueVCB
17  * afs_RemoveVCB
18  * afs_NewVCache
19  * afs_FlushActiveVcaches
20  * afs_VerifyVCache2
21  * afs_WriteVCache
22  * afs_SimpleVStat
23  * afs_ProcessFS
24  * TellALittleWhiteLie
25  * afs_RemoteLookup
26  * afs_GetVCache
27  * afs_LookupVCache
28  * afs_GetRootVCache
29  * afs_FetchStatus
30  * afs_StuffVcache
31  * afs_PutVCache
32  * afs_FindVCache
33  * afs_NFSFindVCache
34  * afs_vcacheInit
35  * shutdown_vcache
36  *
37  */
38 #include "../afs/param.h"       /*Should be always first*/
39 #include "../afs/sysincludes.h" /*Standard vendor system headers*/
40 #include "../afs/afsincludes.h" /*AFS-based standard headers*/
41 #include "../afs/afs_stats.h"
42 #include "../afs/afs_cbqueue.h"
43 #include "../afs/afs_osidnlc.h"
44
45 #ifdef AFS_OSF_ENV
46 afs_int32 afs_maxvcount = 0;            /* max number of vcache entries */
47 afs_int32 afs_vcount = 0;                       /* number of vcache in use now */
48 #if     defined(AFS_OSF30_ENV)
49 extern int max_vnodes;                  /* number of total system vnodes */
50 #else
51 extern int nvnode;                      /* number of total system vnodes */
52 #endif 
53 #ifndef AFS_OSF30_ENV
54 extern int numvnodes;                   /* number vnodes in use now */ 
55 #endif
56 #endif /* AFS_OSF_ENV */
57 #ifdef AFS_SGI_ENV
58 int afsvnumbers = 0;
59 #endif
60
61 /* Imported variables */
62 extern struct server *afs_servers[NSERVERS];
63 extern afs_rwlock_t afs_xserver;
64 extern afs_rwlock_t afs_xcbhash;
65 extern struct vcache *afs_globalVp;
66 #ifdef AFS_OSF_ENV
67 extern struct mount *afs_globalVFS;
68 extern struct vnodeops Afs_vnodeops;
69 #else
70 extern struct vfs *afs_globalVFS;
71 #endif /* AFS_OSF_ENV */
72 #if     defined(AFS_DUX40_ENV)
73 extern struct vfs_ubcops afs_ubcops;
74 #endif
75 #ifdef AFS_SGI62_ENV
76 extern struct vnodeops Afs_vnodeops;
77 #endif
78 #ifdef AFS_SGI64_ENV
79 char *makesname();
80 #endif /* AFS_SGI64_ENV */
81  
82 /* Exported variables */
83 afs_rwlock_t afs_xvcache;               /*Lock: alloc new stat cache entries*/
84 afs_lock_t afs_xvcb;                    /*Lock: fids on which there are callbacks*/
85 struct vcache *freeVCList;              /*Free list for stat cache entries*/
86 struct vcache *Initial_freeVCList;      /*Initial list for above*/
87 struct afs_q VLRU;                      /*vcache LRU*/
88 afs_int32 vcachegen = 0;
89 unsigned int afs_paniconwarn = 0;
90 struct vcache *afs_vhashT[VCSIZE];
91 afs_int32 afs_bulkStatsLost;
92 int afs_norefpanic = 0;
93
94 /* Forward declarations */
95 static afs_int32 afs_QueueVCB(struct vcache *avc);
96
97
98 /*
99  * afs_FlushVCache
100  *
101  * Description:
102  *      Flush the given vcache entry.
103  *
104  * Parameters:
105  *      avc : Pointer to vcache entry to flush.
106  *      slept : Pointer to int to set 1 if we sleep/drop locks, 0 if we don't.
107  *
108  * Environment:
109  *      afs_xvcache lock must be held for writing upon entry to
110  *      prevent people from changing the vrefCount field, and to
111  *      protect the lruq and hnext fields.
112  * LOCK: afs_FlushVCache afs_xvcache W 
113  * REFCNT: vcache ref count must be zero on entry except for osf1
114  * RACE: lock is dropped and reobtained, permitting race in caller
115  */
116
117 int afs_FlushVCache(struct vcache *avc, int *slept)
118 { /*afs_FlushVCache*/
119
120     register afs_int32 i, code;
121     register struct vcache **uvc, *wvc, *tvc;
122
123     *slept = 0;
124     AFS_STATCNT(afs_FlushVCache);
125     afs_Trace2(afs_iclSetp, CM_TRACE_FLUSHV, ICL_TYPE_POINTER, avc,
126                ICL_TYPE_INT32, avc->states);
127 #ifdef  AFS_OSF_ENV
128     AFS_GUNLOCK();
129     VN_LOCK((struct vnode *)avc);
130     AFS_GLOCK();
131 #endif
132
133     code = osi_VM_FlushVCache(avc, slept);
134     if (code)
135         goto bad;
136
137     if (avc->states & CVFlushed) {
138         code = EBUSY;
139         goto bad;
140     }
141     if (avc->nextfree || !avc->vlruq.prev || !avc->vlruq.next) { /* qv afs.h */
142       refpanic ("LRU vs. Free inconsistency");
143     }
144     avc->states |= CVFlushed;
145     /* pull the entry out of the lruq and put it on the free list */
146     QRemove(&avc->vlruq);
147     avc->vlruq.prev = avc->vlruq.next = (struct afs_q *) 0;
148
149     /* keep track of # of files that we bulk stat'd, but never used
150      * before they got recycled.
151      */
152     if (avc->states & CBulkStat)
153         afs_bulkStatsLost++;
154     vcachegen++;
155     /* remove entry from the hash chain */
156     i = VCHash(&avc->fid);
157     uvc = &afs_vhashT[i];
158     for(wvc = *uvc; wvc; uvc = &wvc->hnext, wvc = *uvc) {
159         if (avc == wvc) {
160             *uvc = avc->hnext;
161             avc->hnext = (struct vcache *) NULL;
162             break;
163         }
164     }
165     if (!wvc) osi_Panic("flushvcache"); /* not in correct hash bucket */
166     if (avc->mvid) osi_FreeSmallSpace(avc->mvid);
167     avc->mvid = (struct VenusFid*)0;
168     if (avc->linkData) {
169       afs_osi_Free(avc->linkData, strlen(avc->linkData)+1);
170       avc->linkData = NULL;
171     }
172     afs_FreeAllAxs(&(avc->Access));
173
174     /* we can't really give back callbacks on RO files, since the 
175      * server only tracks them on a per-volume basis, and we don't
176      * know whether we still have some other files from the same
177      * volume. */
178     if ((avc->states & CRO) == 0 && avc->callback) {
179         afs_QueueVCB(avc);
180     }
181     ObtainWriteLock(&afs_xcbhash, 460);
182     afs_DequeueCallback(avc);  /* remove it from queued callbacks list */
183     avc->states &= ~(CStatd | CUnique);
184     ReleaseWriteLock(&afs_xcbhash);
185     afs_symhint_inval(avc);
186     if ((avc->states & CForeign) || (avc->fid.Fid.Vnode & 1)) 
187       osi_dnlc_purgedp (avc);  /* if it (could be) a directory */
188     else 
189       osi_dnlc_purgevp (avc);
190
191     /*
192      * Next, keep track of which vnodes we've deleted for create's
193      * optimistic synchronization algorithm
194      */
195     afs_allZaps++;
196     if (avc->fid.Fid.Vnode & 1) afs_oddZaps++;
197     else afs_evenZaps++;
198
199 #if     !defined(AFS_OSF_ENV)
200     /* put the entry in the free list */
201     avc->nextfree = freeVCList;
202     freeVCList = avc;
203     if (avc->vlruq.prev || avc->vlruq.next) {
204        refpanic ("LRU vs. Free inconsistency");
205     }
206 #else 
207     /* This should put it back on the vnode free list since usecount is 1 */
208     afs_vcount--;
209     vSetType(avc, VREG);
210     if (avc->vrefCount > 0) {
211         VN_UNLOCK((struct vnode *)avc);
212         AFS_RELE((struct vnode *)avc);
213     } else {
214        if (afs_norefpanic) {
215           printf ("flush vc refcnt < 1");
216           afs_norefpanic++;
217           (void) vgone(avc, VX_NOSLEEP, (struct vnodeops *) 0);
218           AFS_GLOCK();
219           VN_UNLOCK((struct vnode *)avc);
220        }
221        else osi_Panic ("flush vc refcnt < 1");
222     }
223 #endif  /* AFS_OSF_ENV */
224     avc->states |= CVFlushed;
225     return 0;
226
227 bad:
228 #ifdef  AFS_OSF_ENV
229     VN_UNLOCK((struct vnode *)avc);
230 #endif
231     return code;
232
233 } /*afs_FlushVCache*/
234
235 #ifndef AFS_SGI_ENV
236 /*
237  * afs_InactiveVCache
238  *
239  * The core of the inactive vnode op for all but IRIX.
240  */
241 void afs_InactiveVCache(struct vcache *avc, struct AFS_UCRED *acred)
242 {
243     extern afs_rwlock_t afs_xdcache, afs_xvcache;
244     
245     AFS_STATCNT(afs_inactive);
246     if (avc->states & CDirty) {
247       /* we can't keep trying to push back dirty data forever.  Give up. */
248       afs_InvalidateAllSegments(avc, 1/*set lock*/);  /* turns off dirty bit */
249     }
250     avc->states &= ~CMAPPED;    /* mainly used by SunOS 4.0.x */
251     avc->states &= ~CDirty;     /* Turn it off */
252     if (avc->states & CUnlinked) {
253         if (CheckLock(&afs_xvcache) || CheckLock(&afs_xdcache)) { 
254             avc->states |= CUnlinkedDel;
255             return; 
256         }
257         afs_remunlink(avc, 1);  /* ignore any return code */
258     }
259
260 }
261 #endif
262
263 /*
264  * afs_AllocCBR
265  *
266  * Description: allocate a callback return structure from the
267  * free list and return it.
268  *
269  * Env: The alloc and free routines are both called with the afs_xvcb lock
270  * held, so we don't have to worry about blocking in osi_Alloc.
271  */
272 static struct afs_cbr *afs_cbrSpace = 0;
273 struct afs_cbr *afs_AllocCBR() {
274     register struct afs_cbr *tsp;
275     int i;
276
277     while (!afs_cbrSpace) {
278         if (afs_stats_cmperf.CallBackAlloced >= 2) {
279             /* don't allocate more than 2 * AFS_NCBRS for now */
280             afs_FlushVCBs(0);
281             afs_stats_cmperf.CallBackFlushes++;
282         }
283         else {
284             /* try allocating */
285             tsp = (struct afs_cbr *) afs_osi_Alloc(AFS_NCBRS * sizeof(struct afs_cbr));
286             for(i=0; i < AFS_NCBRS-1; i++) {
287                 tsp[i].next = &tsp[i+1];
288             }
289             tsp[AFS_NCBRS-1].next = 0;
290             afs_cbrSpace = tsp;
291             afs_stats_cmperf.CallBackAlloced++;
292         }
293     }
294     tsp = afs_cbrSpace;
295     afs_cbrSpace = tsp->next;
296     return tsp;
297 }
298
299 /*
300  * afs_FreeCBR
301  *
302  * Description: free a callback return structure.
303  *
304  * Parameters:
305  *      asp -- the address of the structure to free.
306  *
307  * Environment: the xvcb lock is held over these calls.
308  */
309 afs_FreeCBR(asp)
310 register struct afs_cbr *asp; {
311     asp->next = afs_cbrSpace;
312     afs_cbrSpace = asp;
313     return 0;
314 }
315
316 /*
317  * afs_FlushVCBs
318  *
319  * Description: flush all queued callbacks to all servers.
320  *
321  * Parameters: none.
322  *
323  * Environment: holds xvcb lock over RPC to guard against race conditions
324  *      when a new callback is granted for the same file later on.
325  */
326 afs_int32 afs_FlushVCBs (afs_int32 lockit) 
327 {
328     struct AFSFid tfids[AFS_MAXCBRSCALL];
329     struct AFSCallBack callBacks[1];
330     struct AFSCBFids fidArray;
331     struct AFSCBs cbArray;
332     afs_int32 code;
333     struct afs_cbr *tcbrp;
334     int tcount;
335     struct server *tsp;
336     int i;
337     struct vrequest treq;
338     struct conn *tc;
339     int safety1, safety2, safety3;
340     extern int afs_totalServers;
341     XSTATS_DECLS
342
343     if (code = afs_InitReq(&treq, &afs_osi_cred)) return code;
344     treq.flags |= O_NONBLOCK;
345
346     if (lockit) MObtainWriteLock(&afs_xvcb,273);
347     ObtainReadLock(&afs_xserver);
348     for(i=0; i<NSERVERS; i++) {
349         for(safety1 = 0, tsp = afs_servers[i];
350             tsp && safety1 < afs_totalServers+10; tsp=tsp->next, safety1++) { 
351             /* don't have any */
352             if (tsp->cbrs == (struct afs_cbr *) 0) continue;
353
354             /* otherwise, grab a block of AFS_MAXCBRSCALL from the list
355              * and make an RPC, over and over again.
356              */
357             tcount = 0; /* number found so far */
358             for (safety2 = 0; safety2 < afs_cacheStats ; safety2++) {
359                 if (tcount >= AFS_MAXCBRSCALL || !tsp->cbrs) {
360                     /* if buffer is full, or we've queued all we're going
361                      * to from this server, we should flush out the
362                      * callbacks.
363                      */
364                     fidArray.AFSCBFids_len = tcount;
365                     fidArray.AFSCBFids_val = (struct AFSFid *) tfids;
366                     cbArray.AFSCBs_len = 1;
367                     cbArray.AFSCBs_val = callBacks;
368                     callBacks[0].CallBackType = CB_EXCLUSIVE;
369                     for (safety3 = 0; safety3 < MAXHOSTS*2; safety3++) {
370                         tc = afs_ConnByHost(tsp, tsp->cell->fsport,
371                                             tsp->cell->cell, &treq, 0,
372                                             SHARED_LOCK);
373                         if (tc) {
374                           XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS);
375 #ifdef RX_ENABLE_LOCKS
376                           AFS_GUNLOCK();
377 #endif /* RX_ENABLE_LOCKS */
378                           code = RXAFS_GiveUpCallBacks(tc->id, &fidArray,
379                                                        &cbArray);
380 #ifdef RX_ENABLE_LOCKS
381                           AFS_GLOCK();
382 #endif /* RX_ENABLE_LOCKS */
383                           XSTATS_END_TIME;
384                         }
385                         else code = -1;
386                         if (!afs_Analyze(tc, code, 0, &treq,
387                                      AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS,
388                                      SHARED_LOCK, tsp->cell)) {
389                            break;
390                         }
391                     }
392                     /* ignore return code, since callbacks may have
393                      * been returned anyway, we shouldn't leave them
394                      * around to be returned again.
395                      *
396                      * Next, see if we are done with this server, and if so,
397                      * break to deal with the next one.
398                      */
399                     if (!tsp->cbrs) break;
400                     tcount = 0;
401                 }       /* if to flush full buffer */
402                 /* if we make it here, we have an entry at the head of cbrs,
403                  * which we should copy to the file ID array and then free.
404                  */
405                 tcbrp = tsp->cbrs;
406                 tfids[tcount++] = tcbrp->fid;
407                 tsp->cbrs = tcbrp->next;
408                 afs_FreeCBR(tcbrp);
409             }           /* while loop for this one server */
410             if (safety2 > afs_cacheStats) {
411               afs_warn("possible internal error afs_flushVCBs (%d)\n", safety2);
412             }
413         }               /* for loop for this hash chain */
414     }                   /* loop through all hash chains */
415     if (safety1 > afs_totalServers+2)  {
416        afs_warn("AFS internal error (afs_flushVCBs) (%d > %d), continuing...\n", safety1, afs_totalServers+2);
417        if (afs_paniconwarn)
418          osi_Panic("afs_flushVCBS safety1");
419     }
420
421     ReleaseReadLock(&afs_xserver);
422     if (lockit) MReleaseWriteLock(&afs_xvcb);
423     return 0;
424 }
425
426 /*
427  * afs_QueueVCB
428  *
429  * Description:
430  *      Queue a callback on the given fid.
431  *
432  * Parameters:
433  *      avc: vcache entry
434  *
435  * Environment:
436  *      Locks the xvcb lock.
437  *      Called when the xvcache lock is already held.
438  */
439
440 static afs_int32 afs_QueueVCB(struct vcache *avc)
441 {
442     register struct server *tsp;
443     register struct afs_cbr *tcbp;
444
445     AFS_STATCNT(afs_QueueVCB);
446     /* The callback is really just a struct server ptr. */
447     tsp = (struct server *)(avc->callback);
448
449     /* we now have a pointer to the server, so we just allocate
450      * a queue entry and queue it.
451      */
452     MObtainWriteLock(&afs_xvcb,274);
453     tcbp = afs_AllocCBR();
454     tcbp->fid = avc->fid.Fid;
455     tcbp->next = tsp->cbrs;
456     tsp->cbrs = tcbp;
457
458     /* now release locks and return */
459     MReleaseWriteLock(&afs_xvcb);
460     return 0;
461 }
462
463
464 /*
465  * afs_RemoveVCB
466  *
467  * Description:
468  *      Remove a queued callback by looking through all the servers
469  *      to see if any have this callback queued.
470  *
471  * Parameters:
472  *      afid: The fid we want cleansed of queued callbacks.
473  *
474  * Environment:
475  *      Locks xvcb and xserver locks.
476  *      Typically called with xdcache, xvcache and/or individual vcache
477  *      entries locked.
478  */
479
480 afs_RemoveVCB(afid)
481     register struct VenusFid *afid;
482
483 { /*afs_RemoveVCB*/
484
485     register int i, j;
486     register struct server *tsp;
487     register struct afs_cbr *tcbrp;
488     struct afs_cbr **lcbrpp;
489
490     AFS_STATCNT(afs_RemoveVCB);
491     MObtainWriteLock(&afs_xvcb,275);
492     ObtainReadLock(&afs_xserver);
493     for(i=0;i<NSERVERS;i++) {
494         for(tsp=afs_servers[i]; tsp; tsp=tsp->next) {
495             /* if cell is known, and is wrong, then skip this server */
496             if (tsp->cell && tsp->cell->cell != afid->Cell) continue;
497
498             /*
499              * Otherwise, iterate through file IDs we're sending to the
500              * server.
501              */
502             lcbrpp = &tsp->cbrs;        /* first queued return callback */
503             for(tcbrp = *lcbrpp; tcbrp; lcbrpp = &tcbrp->next, tcbrp = *lcbrpp) {
504                 if (afid->Fid.Volume == tcbrp->fid.Volume &&
505                     afid->Fid.Unique == tcbrp->fid.Unique &&
506                     afid->Fid.Vnode == tcbrp->fid.Vnode) {
507                     *lcbrpp = tcbrp->next;      /* unthread from list */
508                     afs_FreeCBR(tcbrp);
509                     goto done;
510                 }
511             }
512         }
513     }
514   done:
515     ReleaseReadLock(&afs_xserver);
516     MReleaseWriteLock(&afs_xvcb);
517     return 0;
518
519 } /*afs_RemoveVCB*/
520
521
522
523 /*
524  * afs_NewVCache
525  *
526  * Description:
527  *      This routine is responsible for allocating a new cache entry
528  *      from the free list.  It formats the cache entry and inserts it
529  *      into the appropriate hash tables.  It must be called with
530  *      afs_xvcache write-locked so as to prevent several processes from
531  *      trying to create a new cache entry simultaneously.
532  *
533  * Parameters:
534  *      afid  : The file id of the file whose cache entry is being
535  *              created.
536  */
537 /* LOCK: afs_NewVCache  afs_xvcache W */ 
538 struct vcache *afs_NewVCache(struct VenusFid *afid, struct server *serverp,
539                              afs_int32 lockit, afs_int32 locktype)
540 {
541     struct vcache *tvc;
542     afs_int32 i;
543     afs_int32 anumber = VCACHE_FREE;
544 #ifdef  AFS_AIX_ENV
545     struct gnode *gnodepnt;
546 #endif
547 #ifdef  AFS_MACH_ENV
548     struct vm_info * vm_info_ptr;
549 #endif /* AFS_MACH_ENV */
550 #ifdef  AFS_OSF_ENV
551     struct vcache *nvc;
552 #endif  /* AFS_OSF_ENV */
553     struct afs_q *tq, *uq;
554     int code, fv_slept;
555
556     AFS_STATCNT(afs_NewVCache);
557 #ifdef AFS_LINUX22_ENV
558     if (!freeVCList) {
559         /* Free some if possible. */
560          struct afs_q *tq, *uq;
561          int i; char *panicstr;
562          int vmax = 2 * afs_cacheStats;
563          int vn = VCACHE_FREE;
564
565          i = 0;
566          for(tq = VLRU.prev; tq != &VLRU && vn > 0; tq = uq) {
567             tvc = QTOV(tq);
568             uq = QPrev(tq);
569             if (tvc->states & CVFlushed) 
570                  refpanic ("CVFlushed on VLRU");
571             else if (i++ > vmax)
572                  refpanic ("Exceeded pool of AFS vnodes(VLRU cycle?)");
573             else if (QNext(uq) != tq)
574                  refpanic ("VLRU inconsistent");
575
576             if (tvc == afs_globalVp)
577                 continue;
578
579             if ( tvc->vrefCount && tvc->opens == 0 ) {
580                 struct inode *ip = (struct inode*)tvc;
581                 if (list_empty(&ip->i_dentry)) {
582                     vn --;
583                 }
584                 else {
585                     struct list_head *cur;
586                     struct list_head *head = &ip->i_dentry;
587                     int all = 1;
588                 retry:
589                     cur = head;
590                     while ((cur = cur->next) != head) {
591                         struct dentry *dentry = list_entry(cur, struct dentry, d_alias);
592                         if (!dentry->d_count) {
593                             AFS_GUNLOCK();
594                             dget(dentry);
595                             d_drop(dentry);
596                             dput(dentry);
597                             AFS_GLOCK();
598                             goto retry;
599                         }
600                         else {
601                             all = 0;
602                         }
603                     }
604                     if (all) vn --;
605                 }
606             }
607             if (tq == uq) break;
608          }
609     }
610 #endif /* AFS_LINUX22_ENV */
611 #ifdef  AFS_OSF_ENV
612 #ifdef  AFS_OSF30_ENV
613     if (afs_vcount >= afs_maxvcount) 
614 #else
615     /*
616      * If we are using > 33 % of the total system vnodes for AFS vcache
617      * entries or we are using the maximum number of vcache entries,
618      * then free some.  (if our usage is > 33% we should free some, if
619      * our usage is > afs_maxvcount, set elsewhere to 0.5*nvnode, 
620      * we _must_ free some -- no choice).
621      */
622     if ( (( 3 * afs_vcount ) > nvnode) || ( afs_vcount >= afs_maxvcount ))
623 #endif
624        {
625          struct afs_q *tq, *uq;
626          int i; char *panicstr;
627
628          i = 0;
629          for(tq = VLRU.prev; tq != &VLRU && anumber > 0; tq = uq) {
630             tvc = QTOV(tq);
631             uq = QPrev(tq);
632             if (tvc->states & CVFlushed) 
633                  refpanic ("CVFlushed on VLRU");
634             else if (i++ > afs_maxvcount)
635                  refpanic ("Exceeded pool of AFS vnodes(VLRU cycle?)");
636             else if (QNext(uq) != tq)
637                  refpanic ("VLRU inconsistent");
638             else if (tvc->vrefCount < 1) 
639                  refpanic ("refcnt 0 on VLRU");
640
641             if ( tvc->vrefCount == 1   &&   tvc->opens == 0 
642                 && (tvc->states & CUnlinkedDel) == 0) {
643                 code = afs_FlushVCache(tvc, &fv_slept);
644                 if (code == 0) {
645                   anumber--;
646                 }
647                 if (fv_slept) {
648                   uq = VLRU.prev;
649                   i = 0;
650                   continue;  /* start over - may have raced. */
651                 }
652             }
653             if (tq == uq) break;
654          }
655          if (anumber == VCACHE_FREE) {
656             printf("NewVCache: warning none freed, using %d of %d\n", 
657                    afs_vcount, afs_maxvcount);
658             if (afs_vcount >= afs_maxvcount) {
659                 osi_Panic("NewVCache - none freed");
660                 /* XXX instead of panicing, should do afs_maxvcount++ 
661                    and magic up another one */
662             }
663          }
664       }
665
666     AFS_GUNLOCK();
667     if (getnewvnode(MOUNT_AFS, &Afs_vnodeops, &nvc)) {
668         /* What should we do ???? */
669         osi_Panic("afs_NewVCache: no more vnodes");
670     }
671     AFS_GLOCK();
672
673     tvc = nvc;
674     tvc->nextfree = (struct vcache *)0; 
675     afs_vcount++;
676 #else   /* AFS_OSF_ENV */
677     /* pull out a free cache entry */
678     if (!freeVCList) {
679         i = 0;
680         for(tq = VLRU.prev; (anumber > 0) && (tq != &VLRU); tq = uq) {
681            tvc = QTOV(tq);
682            uq = QPrev(tq);
683
684            if (tvc->states & CVFlushed)
685                 refpanic("CVFlushed on VLRU");
686            else if (i++ > 2*afs_cacheStats) /* even allowing for a few xallocs...*/
687                 refpanic("Increase -stat parameter of afsd(VLRU cycle?)");
688            else if (QNext(uq) != tq)
689                 refpanic("VLRU inconsistent");
690
691            if (tvc->vrefCount == 0 && tvc->opens == 0
692                && (tvc->states & CUnlinkedDel) == 0) {
693                 code = afs_FlushVCache(tvc, &fv_slept);
694                 if (code == 0) {
695                   anumber--;
696                 }
697                 if (fv_slept) {
698                   uq = VLRU.prev;
699                   i = 0;
700                   continue;  /* start over - may have raced. */
701                 }
702            } 
703            if (tq == uq ) break;
704         }
705     }
706     if (!freeVCList) {
707         /* none free, making one is better than a panic */
708         afs_stats_cmperf.vcacheXAllocs++;       /* count in case we have a leak */
709         tvc = (struct vcache *) afs_osi_Alloc(sizeof (struct vcache));
710 #ifdef  AFS_AIX32_ENV
711         pin((char *)tvc, sizeof(struct vcache));        /* XXX */
712 #endif
713 #ifdef  AFS_MACH_ENV
714         /* In case it still comes here we need to fill this */
715         tvc->v.v_vm_info = VM_INFO_NULL;
716         vm_info_init(tvc->v.v_vm_info);
717         /* perhaps we should also do close_flush on non-NeXT mach systems;
718          * who knows; we don't currently have the sources.
719          */
720 #endif /* AFS_MACH_ENV */
721 #if defined(AFS_SGI_ENV)
722         { char name[METER_NAMSZ];
723         bzero(tvc, sizeof(struct vcache));
724         tvc->v.v_number = ++afsvnumbers;
725         tvc->vc_rwlockid = OSI_NO_LOCKID;
726         initnsema(&tvc->vc_rwlock, 1, makesname(name, "vrw", tvc->v.v_number));
727 #ifndef AFS_SGI53_ENV
728         initnsema(&tvc->v.v_sync, 0, makesname(name, "vsy", tvc->v.v_number));
729 #endif
730 #ifndef AFS_SGI62_ENV
731         initnlock(&tvc->v.v_lock, makesname(name, "vlk", tvc->v.v_number));
732 #endif
733         }
734 #endif /* AFS_SGI_ENV */
735     }
736     else {
737         tvc = freeVCList;   /* take from free list */
738         freeVCList = tvc->nextfree;
739         tvc->nextfree = (struct vcache *)0;
740     }
741 #endif  /* AFS_OSF_ENV */
742
743 #ifdef  AFS_MACH_ENV
744     vm_info_ptr = tvc->v.v_vm_info;
745 #endif /* AFS_MACH_ENV */
746
747 #if !defined(AFS_SGI_ENV) && !defined(AFS_OSF_ENV)
748     bzero((char *)tvc, sizeof(struct vcache));
749 #else
750     tvc->uncred = 0;
751 #endif
752
753     RWLOCK_INIT(&tvc->lock, "vcache lock");
754 #if     defined(AFS_SUN5_ENV)
755     RWLOCK_INIT(&tvc->vlock, "vcache vlock");
756 #endif /* defined(AFS_SUN5_ENV) */
757
758 #ifdef  AFS_MACH_ENV
759     tvc->v.v_vm_info = vm_info_ptr;
760     tvc->v.v_vm_info->pager = MEMORY_OBJECT_NULL;
761 #endif /* AFS_MACH_ENV */
762     tvc->parentVnode = 0;
763     tvc->mvid = (struct VenusFid *) 0;
764     tvc->linkData = (char *) 0;
765     tvc->cbExpires = 0;
766     tvc->opens = 0;
767     tvc->execsOrWriters = 0;
768     tvc->flockCount = 0;
769     tvc->anyAccess = 0;
770     tvc->states = 0;
771     tvc->last_looker = 0;
772     tvc->fid = *afid;
773     tvc->asynchrony = -1;
774     tvc->vc_error = 0;
775     afs_symhint_inval(tvc);
776 #ifdef AFS_TEXT_ENV
777     tvc->flushDV.low = tvc->flushDV.high =  AFS_MAXDV;
778 #endif
779     hzero(tvc->mapDV);
780     tvc->truncPos = AFS_NOTRUNC;        /* don't truncate until we need to */
781     hzero(tvc->m.DataVersion);          /* in case we copy it into flushDV */
782 #ifdef  AFS_OSF_ENV
783     /* Hold it for the LRU (should make count 2) */
784     VN_HOLD((struct vnode *)tvc);
785 #else   /* AFS_OSF_ENV */
786     tvc->vrefCount = 1; /* us */
787 #endif  /* AFS_OSF_ENV */
788 #ifdef  AFS_AIX32_ENV
789     LOCK_INIT(&tvc->pvmlock, "vcache pvmlock");
790     tvc->vmh = tvc->segid = NULL;
791     tvc->credp = NULL;
792 #endif
793 #if defined(AFS_SUN_ENV) || defined(AFS_ALPHA_ENV) || defined(AFS_SUN5_ENV)
794 #if     defined(AFS_SUN5_ENV)
795     rw_init(&tvc->rwlock, "vcache rwlock", RW_DEFAULT, NULL);
796
797 #if     defined(AFS_SUN55_ENV)
798         /* This is required if the kaio (kernel aynchronous io)
799         ** module is installed. Inside the kernel, the function
800         ** check_vp( common/os/aio.c) checks to see if the kernel has 
801         ** to provide asynchronous io for this vnode. This
802         ** function extracts the device number by following the
803         ** v_data field of the vnode. If we do not set this field
804         ** then the system panics. The  value of the v_data field
805         ** is not really important for AFS vnodes because the kernel
806         ** does not do asynchronous io for regular files. Hence,
807         ** for the time being, we fill up the v_data field with the
808         ** vnode pointer itself. */
809     tvc->v.v_data = (char *)tvc;
810 #endif /* AFS_SUN55_ENV */
811 #endif
812     afs_BozonInit(&tvc->pvnLock, tvc);
813 #endif
814
815     tvc->Access = NULL;
816     tvc->callback = serverp;    /* to minimize chance that clear
817                                    request is lost */
818     /* initialize vnode data, note vrefCount is v.v_count */
819 #ifdef  AFS_AIX_ENV
820     /* Don't forget to free the gnode space */
821     tvc->v.v_gnode = gnodepnt = (struct gnode *) osi_AllocSmallSpace(sizeof(struct gnode));
822     bzero((char *)gnodepnt, sizeof(struct gnode));
823 #endif
824 #ifdef AFS_SGI64_ENV
825     bzero((void*)&(tvc->vc_bhv_desc), sizeof(tvc->vc_bhv_desc));
826     bhv_desc_init(&(tvc->vc_bhv_desc), tvc, tvc, &Afs_vnodeops);
827 #ifdef AFS_SGI65_ENV
828     vn_bhv_head_init(&(tvc->v.v_bh), "afsvp");
829     vn_bhv_insert_initial(&(tvc->v.v_bh), &(tvc->vc_bhv_desc));
830 #else
831     bhv_head_init(&(tvc->v.v_bh));
832     bhv_insert_initial(&(tvc->v.v_bh), &(tvc->vc_bhv_desc));
833 #endif
834 #ifdef AFS_SGI65_ENV
835     tvc->v.v_mreg = tvc->v.v_mregb = (struct pregion*)tvc;
836 #ifdef VNODE_TRACING
837     tvc->v.v_trace = ktrace_alloc(VNODE_TRACE_SIZE, 0);
838 #endif
839     init_bitlock(&tvc->v.v_pcacheflag, VNODE_PCACHE_LOCKBIT, "afs_pcache",
840                  tvc->v.v_number);
841     init_mutex(&tvc->v.v_filocksem, MUTEX_DEFAULT, "afsvfl", (long)tvc);
842     init_mutex(&tvc->v.v_buf_lock, MUTEX_DEFAULT, "afsvnbuf", (long)tvc);
843 #endif
844     vnode_pcache_init(&tvc->v);
845 #if defined(DEBUG) && defined(VNODE_INIT_BITLOCK)
846     /* Above define is never true execpt in SGI test kernels. */
847     init_bitlock(&(tvc->v.v_flag, VLOCK, "vnode", tvc->v.v_number);
848 #endif
849 #ifdef INTR_KTHREADS
850     AFS_VN_INIT_BUF_LOCK(&(tvc->v));
851 #endif
852 #else
853     SetAfsVnode((struct vnode *)tvc);
854 #endif /* AFS_SGI64_ENV */
855     /*
856      * The proper value for mvstat (for root fids) is setup by the caller.
857      */
858     tvc->mvstat = 0;           
859     if (afid->Fid.Vnode == 1 && afid->Fid.Unique == 1)
860         tvc->mvstat = 2;   
861     if (afs_globalVFS == 0) osi_Panic("afs globalvfs");
862     vSetVfsp(tvc, afs_globalVFS);
863     vSetType(tvc, VREG);
864 #ifdef  AFS_AIX_ENV
865     tvc->v.v_vfsnext = afs_globalVFS->vfs_vnodes;   /* link off vfs */
866     tvc->v.v_vfsprev = NULL;
867     afs_globalVFS->vfs_vnodes = &tvc->v;
868     if (tvc->v.v_vfsnext != NULL)
869         tvc->v.v_vfsnext->v_vfsprev = &tvc->v;
870     tvc->v.v_next = gnodepnt->gn_vnode;  /*Single vnode per gnode for us!*/
871     gnodepnt->gn_vnode = &tvc->v;
872 #endif
873 #ifdef  AFS_DEC_ENV
874     tvc->v.g_dev = ((struct mount *)afs_globalVFS->vfs_data)->m_dev;
875 #endif
876 #if     defined(AFS_DUX40_ENV)
877     insmntque(tvc, afs_globalVFS, &afs_ubcops);
878 #else
879 #ifdef  AFS_OSF_ENV
880     /* Is this needed??? */
881     insmntque(tvc, afs_globalVFS);
882 #endif  /* AFS_OSF_ENV */
883 #endif  /* AFS_DUX40_ENV */
884 #if defined(AFS_SGI_ENV)
885     VN_SET_DPAGES(&(tvc->v), (struct pfdat*)NULL);
886     osi_Assert((tvc->v.v_flag & VINACT) == 0);
887     tvc->v.v_flag = 0;
888     osi_Assert(VN_GET_PGCNT(&(tvc->v)) == 0);
889     osi_Assert(tvc->mapcnt == 0 && tvc->vc_locktrips == 0);
890     osi_Assert(tvc->vc_rwlockid == OSI_NO_LOCKID);
891     osi_Assert(tvc->v.v_filocks == NULL);
892 #if !defined(AFS_SGI65_ENV)
893     osi_Assert(tvc->v.v_filocksem == NULL);
894 #endif
895     osi_Assert(tvc->cred == NULL);
896 #ifdef AFS_SGI64_ENV
897     vnode_pcache_reinit(&tvc->v);
898     tvc->v.v_rdev = NODEV;
899 #endif
900     vn_initlist((struct vnlist *)&tvc->v);
901     tvc->lastr = 0;
902 #endif /* AFS_SGI_ENV */
903 #if defined(AFS_LINUX22_ENV)
904     {
905         struct inode *ip = (struct inode*)tvc;
906         sema_init(&ip->i_sem, 1);
907         sema_init(&ip->i_atomic_write, 1);
908         init_waitqueue(&ip->i_wait);
909         INIT_LIST_HEAD(&ip->i_hash);
910         INIT_LIST_HEAD(&ip->i_dentry);
911         if (afs_globalVFS) {
912             ip->i_dev = afs_globalVFS->s_dev;
913             ip->i_sb = afs_globalVFS;
914         }
915      }
916 #endif
917     tvc->h1.dchint = 0;
918     osi_dnlc_purgedp(tvc);  /* this may be overkill */
919     bzero((char *)&(tvc->quick),sizeof(struct vtodc));
920     bzero((char *)&(tvc->callsort),sizeof(struct afs_q));
921     tvc->slocks = (struct SimpleLocks *)0;
922     i = VCHash(afid);
923
924     tvc->hnext = afs_vhashT[i];
925     afs_vhashT[i] = tvc;
926     if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
927        refpanic ("NewVCache VLRU inconsistent");
928     }
929     QAdd(&VLRU, &tvc->vlruq);                           /* put in lruq */
930     if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
931        refpanic ("NewVCache VLRU inconsistent2");
932     }
933     if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
934        refpanic ("NewVCache VLRU inconsistent3");
935     }
936     if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
937        refpanic ("NewVCache VLRU inconsistent4");
938     }
939     vcachegen++;
940
941     return tvc;
942
943 } /*afs_NewVCache*/
944
945
946 /*
947  * afs_FlushActiveVcaches
948  *
949  * Description:
950  *      ???
951  *
952  * Parameters:
953  *      doflocks : Do we handle flocks?
954  */
955 /* LOCK: afs_FlushActiveVcaches afs_xvcache N */
956 void
957 afs_FlushActiveVcaches(doflocks)
958     register afs_int32 doflocks;
959
960 { /*afs_FlushActiveVcaches*/
961
962     register struct vcache *tvc;
963     register int i;
964     register struct conn *tc;
965     register afs_int32 code;
966     register struct AFS_UCRED *cred;
967     struct vrequest treq, ureq;
968     struct AFSVolSync tsync;
969     int didCore;
970     XSTATS_DECLS
971
972     AFS_STATCNT(afs_FlushActiveVcaches);
973     ObtainReadLock(&afs_xvcache);
974     for(i=0;i<VCSIZE;i++) {
975         for(tvc = afs_vhashT[i]; tvc; tvc=tvc->hnext) {
976             if (doflocks && tvc->flockCount != 0) {
977                 /* if this entry has an flock, send a keep-alive call out */
978                 osi_vnhold(tvc, 0);
979                 ReleaseReadLock(&afs_xvcache);
980                 ObtainWriteLock(&tvc->lock,51);
981                 do {
982                     afs_InitReq(&treq, &afs_osi_cred);
983                     treq.flags |= O_NONBLOCK;
984
985                     tc = afs_Conn(&tvc->fid, &treq, SHARED_LOCK);
986                     if (tc) {
987                       XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_EXTENDLOCK);
988 #ifdef RX_ENABLE_LOCKS
989                       AFS_GUNLOCK();
990 #endif /* RX_ENABLE_LOCKS */
991                       code =
992                             RXAFS_ExtendLock(tc->id,
993                                              (struct AFSFid *) &tvc->fid.Fid,
994                                              &tsync);
995 #ifdef RX_ENABLE_LOCKS
996                       AFS_GLOCK();
997 #endif /* RX_ENABLE_LOCKS */
998                       XSTATS_END_TIME;
999                     }
1000                     else code = -1;
1001                 } while
1002                     (afs_Analyze(tc, code, &tvc->fid, &treq,
1003                                  AFS_STATS_FS_RPCIDX_EXTENDLOCK,
1004                                  SHARED_LOCK, (struct cell *)0));
1005
1006                 ReleaseWriteLock(&tvc->lock);
1007                 ObtainReadLock(&afs_xvcache);
1008                 AFS_FAST_RELE(tvc);
1009             }
1010             didCore = 0;
1011             if ((tvc->states & CCore) || (tvc->states & CUnlinkedDel)) {
1012                 /*
1013                  * Don't let it evaporate in case someone else is in
1014                  * this code.  Also, drop the afs_xvcache lock while
1015                  * getting vcache locks.
1016                  */
1017                 osi_vnhold(tvc,0);
1018                 ReleaseReadLock(&afs_xvcache);
1019 #if defined(AFS_SUN_ENV) || defined(AFS_ALPHA_ENV) 
1020                 afs_BozonLock(&tvc->pvnLock, tvc);
1021 #endif
1022 #if defined(AFS_SGI_ENV)
1023                 /*
1024                  * That's because if we come in via the CUnlinkedDel bit state path we'll be have 0 refcnt
1025                  */
1026                 osi_Assert(tvc->vrefCount > 0);
1027                 AFS_RWLOCK((vnode_t *)tvc, VRWLOCK_WRITE);
1028 #endif
1029                 ObtainWriteLock(&tvc->lock,52);
1030                 if (tvc->states & CCore) {
1031                     tvc->states &= ~CCore;
1032                     /* XXXX Find better place-holder for cred XXXX */
1033                     cred = (struct AFS_UCRED *) tvc->linkData;
1034                     tvc->linkData = (char *) 0; /* XXX */
1035                     afs_InitReq(&ureq, cred);
1036                     afs_Trace2(afs_iclSetp, CM_TRACE_ACTCCORE,
1037                                ICL_TYPE_POINTER, tvc,
1038                                ICL_TYPE_INT32, tvc->execsOrWriters);
1039                     code = afs_StoreOnLastReference(tvc, &ureq);
1040                     ReleaseWriteLock(&tvc->lock);
1041 #if defined(AFS_SUN_ENV) || defined(AFS_ALPHA_ENV) 
1042                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1043 #endif
1044                     hzero(tvc->flushDV);
1045                     osi_FlushText(tvc);
1046                     didCore = 1;
1047                     if (code && code != VNOVNODE) {
1048                         afs_StoreWarn(code, tvc->fid.Fid.Volume,
1049                                       /* /dev/console */ 1);
1050                     }
1051                 } else if (tvc->states & CUnlinkedDel) {
1052                     /*
1053                      * Ignore errors 
1054                      */
1055                     ReleaseWriteLock(&tvc->lock);
1056 #if defined(AFS_SUN_ENV) || defined(AFS_ALPHA_ENV) 
1057                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1058 #endif
1059 #if defined(AFS_SGI_ENV)
1060                     AFS_RWUNLOCK((vnode_t *)tvc, VRWLOCK_WRITE);
1061 #endif
1062                     afs_remunlink(tvc, 0);
1063 #if defined(AFS_SGI_ENV)
1064                     AFS_RWLOCK((vnode_t *)tvc, VRWLOCK_WRITE);
1065 #endif
1066                 }
1067                 else {
1068                     /* lost (or won, perhaps) the race condition */
1069                     ReleaseWriteLock(&tvc->lock);
1070 #if defined(AFS_SUN_ENV) || defined(AFS_ALPHA_ENV)
1071                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1072 #endif
1073                 }
1074 #if defined(AFS_SGI_ENV)
1075                 AFS_RWUNLOCK((vnode_t *)tvc, VRWLOCK_WRITE);
1076 #endif
1077                 ObtainReadLock(&afs_xvcache);
1078                 AFS_FAST_RELE(tvc);
1079                 if (didCore) {
1080 #ifdef  AFS_GFS_ENV
1081                     tvc->vrefCount--;
1082 #else
1083                     AFS_RELE((struct vnode *)tvc);
1084 #endif
1085                     /* Matches write code setting CCore flag */
1086                     crfree(cred);
1087                 }
1088             }          
1089         }
1090     }
1091     ReleaseReadLock(&afs_xvcache);
1092
1093 } /*afs_FlushActiveVcaches*/
1094
1095
1096 /*
1097  * afs_VerifyVCache
1098  *
1099  * Description:
1100  *      Make sure a cache entry is up-to-date status-wise.
1101  * 
1102  * NOTE: everywhere that calls this can potentially be sped up
1103  *       by checking CStatd first, and avoiding doing the InitReq
1104  *       if this is up-to-date.
1105  *
1106  *  Anymore, the only places that call this KNOW already that the 
1107  *  vcache is not up-to-date, so we don't screw around.
1108  *
1109  * Parameters:
1110  *      avc  : Ptr to vcache entry to verify.
1111  *      areq : ???
1112  */
1113
1114 int afs_VerifyVCache2(struct vcache *avc, struct vrequest *areq)
1115 {
1116     register struct vcache *tvc;
1117
1118     AFS_STATCNT(afs_VerifyVCache);
1119
1120 #if defined(AFS_OSF_ENV)
1121     ObtainReadLock(&avc->lock);
1122     if (afs_IsWired(avc)) {
1123         ReleaseReadLock(&avc->lock);
1124         return 0;
1125     }
1126     ReleaseReadLock(&avc->lock);
1127 #endif /* AFS_OSF_ENV */
1128     /* otherwise we must fetch the status info */
1129
1130     ObtainWriteLock(&avc->lock,53);
1131     if (avc->states & CStatd) {
1132         ReleaseWriteLock(&avc->lock);
1133         return 0;
1134     }
1135     ObtainWriteLock(&afs_xcbhash, 461);
1136     avc->states &= ~( CStatd | CUnique );   
1137     avc->callback = (struct server *)0;
1138     afs_DequeueCallback(avc);
1139     ReleaseWriteLock(&afs_xcbhash);
1140     ReleaseWriteLock(&avc->lock);
1141
1142     /* since we've been called back, or the callback has expired, 
1143      * it's possible that the contents of this directory, or this 
1144      * file's name have changed, thus invalidating the dnlc contents.
1145      */
1146     if ((avc->states & CForeign) || (avc->fid.Fid.Vnode & 1)) 
1147       osi_dnlc_purgedp (avc);
1148     else
1149       osi_dnlc_purgevp (avc);
1150     
1151     /* fetch the status info */
1152     tvc = afs_GetVCache(&avc->fid, areq, (afs_int32*)0, avc, READ_LOCK);
1153     if (!tvc) return ENOENT;
1154     /* Put it back; caller has already incremented vrefCount */
1155     afs_PutVCache(tvc, READ_LOCK);
1156     return 0;
1157
1158 } /*afs_VerifyVCache*/
1159
1160
1161 /*
1162  * afs_SimpleVStat
1163  *
1164  * Description:
1165  *      Simple copy of stat info into cache.
1166  *
1167  * Parameters:
1168  *      avc   : Ptr to vcache entry involved.
1169  *      astat : Ptr to stat info to copy.
1170  *
1171  * Environment:
1172  *      Nothing interesting.
1173  *
1174  * Callers:  as of 1992-04-29, only called by WriteVCache
1175  */
1176 static void
1177 afs_SimpleVStat(avc, astat, areq)
1178     register struct vcache *avc;
1179     register struct AFSFetchStatus *astat;
1180     struct vrequest *areq;
1181 { /*afs_SimpleVStat*/
1182
1183     AFS_STATCNT(afs_SimpleVStat);
1184
1185 #ifdef AFS_SGI_ENV
1186     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)
1187         && !AFS_VN_MAPPED((vnode_t*)avc))
1188 #else
1189     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc))
1190 #endif
1191
1192         {
1193 #if defined(AFS_SGI_ENV)
1194             osi_Assert((valusema(&avc->vc_rwlock) <= 0) &&
1195                    (OSI_GET_LOCKID() == avc->vc_rwlockid));
1196             if (astat->Length < avc->m.Length) {
1197                 vnode_t *vp = (vnode_t *)avc;
1198                 
1199                 osi_Assert(WriteLocked(&avc->lock));
1200                 ReleaseWriteLock(&avc->lock);
1201                 AFS_GUNLOCK();
1202                 PTOSSVP(vp, (off_t)astat->Length, (off_t)MAXLONG);
1203                 AFS_GLOCK();
1204                 ObtainWriteLock(&avc->lock,67);
1205             }
1206 #endif
1207             /* if writing the file, don't fetch over this value */
1208             afs_Trace3(afs_iclSetp, CM_TRACE_SIMPLEVSTAT,
1209                        ICL_TYPE_POINTER, avc,
1210                        ICL_TYPE_INT32, avc->m.Length,
1211                        ICL_TYPE_INT32, astat->Length);
1212             avc->m.Length = astat->Length;
1213             avc->m.Date = astat->ClientModTime;
1214         }
1215     avc->m.Owner = astat->Owner;
1216     avc->m.Group = astat->Group;
1217     avc->m.Mode = astat->UnixModeBits;
1218     if (vType(avc) == VREG) {
1219         avc->m.Mode |= S_IFREG;
1220     }
1221     else if (vType(avc) == VDIR) {
1222         avc->m.Mode |= S_IFDIR;
1223     }
1224     else if (vType(avc) == VLNK) {
1225
1226
1227
1228         avc->m.Mode |= S_IFLNK;
1229         if ((avc->m.Mode & 0111) == 0) avc->mvstat = 1;
1230     }
1231     if (avc->states & CForeign) {
1232       struct axscache *ac;
1233         avc->anyAccess = astat->AnonymousAccess;
1234 #ifdef badidea
1235         if ((astat->CallerAccess & ~astat->AnonymousAccess)) 
1236          /*   USED TO SAY : 
1237           * Caller has at least one bit not covered by anonymous, and
1238           * thus may have interesting rights.
1239           *
1240           * HOWEVER, this is a really bad idea, because any access query
1241           * for bits which aren't covered by anonymous, on behalf of a user
1242           * who doesn't have any special rights, will result in an answer of 
1243           * the form "I don't know, lets make a FetchStatus RPC and find out!"
1244           * It's an especially bad idea under Ultrix, since (due to the lack of
1245           * a proper access() call) it must perform several afs_access() calls 
1246           * in order to create magic mode bits that vary according to who makes
1247           * the call.  In other words, _every_ stat() generates a test for 
1248           * writeability...
1249           */
1250 #endif /* badidea */
1251           if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
1252             ac->axess =  astat->CallerAccess;
1253           else  /* not found, add a new one if possible */
1254             afs_AddAxs(avc->Access, areq->uid, astat->CallerAccess);
1255     }
1256
1257
1258 } /*afs_SimpleVStat*/
1259
1260
1261 /*
1262  * afs_WriteVCache
1263  *
1264  * Description:
1265  *      Store the status info *only* back to the server for a
1266  *      fid/vrequest.
1267  *
1268  * Parameters:
1269  *      avc     : Ptr to the vcache entry.
1270  *      astatus : Ptr to the status info to store.
1271  *      areq    : Ptr to the associated vrequest.
1272  *
1273  * Environment:
1274  *      Must be called with a shared lock held on the vnode.
1275  */
1276
1277 afs_WriteVCache(avc, astatus, areq)
1278     register struct vcache *avc;
1279     register struct AFSStoreStatus *astatus;
1280     struct vrequest *areq;
1281
1282 { /*afs_WriteVCache*/
1283   afs_int32 code;
1284   struct conn *tc;
1285     struct AFSFetchStatus OutStatus;
1286     struct AFSVolSync tsync;
1287     XSTATS_DECLS
1288
1289     AFS_STATCNT(afs_WriteVCache);
1290     afs_Trace2(afs_iclSetp, CM_TRACE_WVCACHE, ICL_TYPE_POINTER, avc,
1291                ICL_TYPE_INT32, avc->m.Length);
1292
1293     do {
1294         tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
1295         if (tc) {
1296           XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_STORESTATUS);
1297 #ifdef RX_ENABLE_LOCKS
1298           AFS_GUNLOCK();
1299 #endif /* RX_ENABLE_LOCKS */
1300           code = RXAFS_StoreStatus(tc->id,
1301                                    (struct AFSFid *) &avc->fid.Fid,
1302                                    astatus, &OutStatus, &tsync);
1303 #ifdef RX_ENABLE_LOCKS
1304           AFS_GLOCK();
1305 #endif /* RX_ENABLE_LOCKS */
1306           XSTATS_END_TIME;
1307         }
1308         else code = -1;
1309     } while
1310         (afs_Analyze(tc, code, &avc->fid, areq,
1311                      AFS_STATS_FS_RPCIDX_STORESTATUS,
1312                      SHARED_LOCK, (struct cell *)0));
1313
1314     UpgradeSToWLock(&avc->lock,20);
1315     if (code == 0) {
1316         /* success, do the changes locally */
1317         afs_SimpleVStat(avc, &OutStatus, areq);
1318         /*
1319          * Update the date, too.  SimpleVStat didn't do this, since
1320          * it thought we were doing this after fetching new status
1321          * over a file being written.
1322          */
1323         avc->m.Date = OutStatus.ClientModTime;
1324     }
1325     else {
1326         /* failure, set up to check with server next time */
1327         ObtainWriteLock(&afs_xcbhash, 462);
1328         afs_DequeueCallback(avc);
1329         avc->states &= ~( CStatd | CUnique);  /* turn off stat valid flag */
1330         ReleaseWriteLock(&afs_xcbhash);
1331         if ((avc->states & CForeign) || (avc->fid.Fid.Vnode & 1)) 
1332           osi_dnlc_purgedp (avc);  /* if it (could be) a directory */
1333     }
1334     ConvertWToSLock(&avc->lock);
1335     return code;
1336
1337 } /*afs_WriteVCache*/
1338
1339 /*
1340  * afs_ProcessFS
1341  *
1342  * Description:
1343  *      Copy astat block into vcache info
1344  *
1345  * Parameters:
1346  *      avc   : Ptr to vcache entry.
1347  *      astat : Ptr to stat block to copy in.
1348  *      areq  : Ptr to associated request.
1349  *
1350  * Environment:
1351  *      Must be called under a write lock
1352  *
1353  * Note: this code may get dataversion and length out of sync if the file has
1354  *       been modified.  This is less than ideal.  I haven't thought about
1355  *       it sufficiently to be certain that it is adequate.
1356  */
1357 void
1358 afs_ProcessFS(avc, astat, areq)
1359     register struct vcache *avc;
1360     struct vrequest *areq;
1361     register struct AFSFetchStatus *astat;
1362
1363 { /*afs_ProcessFS*/
1364
1365     register int i;
1366     AFS_STATCNT(afs_ProcessFS);
1367
1368     /* WARNING: afs_DoBulkStat uses the Length field to store a sequence
1369      * number for each bulk status request. Under no circumstances
1370      * should afs_DoBulkStat store a sequence number if the new
1371      * length will be ignored when afs_ProcessFS is called with
1372      * new stats. If you change the following conditional then you
1373      * also need to change the conditional in afs_DoBulkStat.  */
1374 #ifdef AFS_SGI_ENV
1375     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)
1376         && !AFS_VN_MAPPED((vnode_t*)avc))
1377 #else
1378     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc))
1379 #endif
1380         {
1381             /* if we're writing or mapping this file, don't fetch over these
1382              *  values.
1383              */
1384             afs_Trace3(afs_iclSetp, CM_TRACE_PROCESSFS, ICL_TYPE_POINTER, avc,
1385                        ICL_TYPE_INT32, avc->m.Length,
1386                        ICL_TYPE_INT32, astat->Length);
1387             avc->m.Length = astat->Length;
1388             avc->m.Date = astat->ClientModTime;
1389         }
1390     hset64(avc->m.DataVersion, astat->dataVersionHigh, astat->DataVersion);
1391     avc->m.Owner = astat->Owner;
1392     avc->m.Mode = astat->UnixModeBits;
1393     avc->m.Group = astat->Group;
1394     avc->m.LinkCount = astat->LinkCount;
1395     if (astat->FileType == File) {
1396         vSetType(avc, VREG);
1397         avc->m.Mode |= S_IFREG;
1398     }
1399     else if (astat->FileType == Directory) {
1400         vSetType(avc, VDIR);
1401         avc->m.Mode |= S_IFDIR;
1402     }
1403     else if (astat->FileType == SymbolicLink) {
1404         vSetType(avc, VLNK);
1405         avc->m.Mode |= S_IFLNK;
1406         if ((avc->m.Mode & 0111) == 0) avc->mvstat = 1;
1407     }
1408     avc->anyAccess = astat->AnonymousAccess;
1409 #ifdef badidea
1410     if ((astat->CallerAccess & ~astat->AnonymousAccess)) 
1411       /*   USED TO SAY : 
1412        * Caller has at least one bit not covered by anonymous, and
1413        * thus may have interesting rights.
1414        *
1415        * HOWEVER, this is a really bad idea, because any access query
1416        * for bits which aren't covered by anonymous, on behalf of a user
1417        * who doesn't have any special rights, will result in an answer of 
1418        * the form "I don't know, lets make a FetchStatus RPC and find out!"
1419        * It's an especially bad idea under Ultrix, since (due to the lack of
1420        * a proper access() call) it must perform several afs_access() calls 
1421        * in order to create magic mode bits that vary according to who makes
1422        * the call.  In other words, _every_ stat() generates a test for 
1423        * writeability...
1424        */
1425 #endif /* badidea */
1426       {
1427         struct axscache *ac;
1428         if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
1429           ac->axess =  astat->CallerAccess;
1430         else  /* not found, add a new one if possible */
1431           afs_AddAxs(avc->Access, areq->uid, astat->CallerAccess);
1432       }
1433
1434 #ifdef AFS_LINUX22_ENV
1435     vcache2inode(avc);    /* Set the inode attr cache */
1436 #endif
1437
1438 } /*afs_ProcessFS*/
1439
1440
1441 afs_RemoteLookup(afid, areq, name, nfid, OutStatusp, CallBackp, serverp, tsyncp)
1442     register struct VenusFid *afid;
1443     struct vrequest *areq;
1444     char *name;
1445     struct VenusFid *nfid;
1446     struct AFSFetchStatus *OutStatusp;
1447     struct AFSCallBack *CallBackp;
1448     struct server **serverp;
1449     struct AFSVolSync *tsyncp;
1450 {
1451     afs_int32 code, i;
1452     register struct vcache *tvc;
1453     struct volume *tvp;
1454     afs_uint32 start;
1455     register struct conn *tc;
1456     struct AFSFetchStatus OutDirStatus;
1457     XSTATS_DECLS
1458
1459     if (!name) name = "";       /* XXX */
1460     do {
1461         tc = afs_Conn(afid, areq, SHARED_LOCK);
1462         if (tc) {
1463             if (serverp) *serverp = tc->srvr->server;
1464             start = osi_Time();
1465             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_XLOOKUP);
1466 #ifdef RX_ENABLE_LOCKS
1467             AFS_GUNLOCK();
1468 #endif /* RX_ENABLE_LOCKS */
1469             code = RXAFS_Lookup(tc->id, (struct AFSFid *) &afid->Fid, name,
1470                                 (struct AFSFid *) &nfid->Fid, 
1471                                 OutStatusp, &OutDirStatus, CallBackp, tsyncp);
1472 #ifdef RX_ENABLE_LOCKS
1473             AFS_GLOCK();
1474 #endif /* RX_ENABLE_LOCKS */
1475             XSTATS_END_TIME;
1476         } else 
1477             code = -1;
1478     } while
1479         (afs_Analyze(tc, code, afid, areq,
1480                      AFS_STATS_FS_RPCIDX_XLOOKUP,
1481                      SHARED_LOCK, (struct cell *)0));
1482
1483     return code;
1484 }
1485
1486
1487 /*
1488  * afs_GetVCache
1489  *
1490  * Description:
1491  *      Given a file id and a vrequest structure, fetch the status
1492  *      information associated with the file.
1493  *
1494  * Parameters:
1495  *      afid : File ID.
1496  *      areq : Ptr to associated vrequest structure, specifying the
1497  *              user whose authentication tokens will be used.
1498  *      avc  : caller may already have a vcache for this file, which is 
1499  *             already held.
1500  *
1501  * Environment:
1502  *      The cache entry is returned with an increased vrefCount field.
1503  *      The entry must be discarded by calling afs_PutVCache when you
1504  *      are through using the pointer to the cache entry.
1505  *
1506  *      You should not hold any locks when calling this function, except
1507  *      locks on other vcache entries.  If you lock more than one vcache
1508  *      entry simultaneously, you should lock them in this order:
1509  *
1510  *          1. Lock all files first, then directories.
1511  *          2.  Within a particular type, lock entries in Fid.Vnode order.
1512  *  
1513  *      This locking hierarchy is convenient because it allows locking
1514  *      of a parent dir cache entry, given a file (to check its access
1515  *      control list).  It also allows renames to be handled easily by
1516  *      locking directories in a constant order.
1517  * NB.  NewVCache -> FlushVCache presently (4/10/95) drops the xvcache lock.
1518  */
1519 struct vcache *afs_GetVCache(afid, areq, cached, avc, locktype)
1520     register struct VenusFid *afid;
1521     struct vrequest *areq;
1522     afs_int32 *cached;
1523     afs_int32 locktype;
1524     struct vcache *avc; /* might have a vcache structure already, which must
1525                          * already be held by the caller */
1526 { /*afs_GetVCache*/
1527
1528     afs_int32 code, i, newvcache=0;
1529     register struct vcache *tvc;
1530     struct volume *tvp;
1531     afs_int32 retry;
1532
1533     AFS_STATCNT(afs_GetVCache);
1534
1535     if (cached) *cached = 0;            /* Init just in case */
1536
1537 loop:
1538     ObtainSharedLock(&afs_xvcache,5); 
1539
1540     tvc = afs_FindVCache(afid, 0, 0, &retry, DO_STATS | DO_VLRU );
1541     if (tvc && retry) {
1542 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
1543         ReleaseSharedLock(&afs_xvcache);
1544         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
1545         goto loop;
1546 #endif
1547    }
1548    
1549     if (tvc) {
1550       if (cached) 
1551         *cached = 1;
1552       if (tvc->states & CStatd) {               
1553         ReleaseSharedLock(&afs_xvcache);
1554         return tvc;
1555       }
1556     }
1557     else {      
1558         UpgradeSToWLock(&afs_xvcache,21);
1559
1560         /* no cache entry, better grab one */
1561         tvc = afs_NewVCache(afid, (struct server *)0, 1, WRITE_LOCK);
1562         newvcache = 1;
1563
1564         ConvertWToSLock(&afs_xvcache);
1565         afs_stats_cmperf.vcacheMisses++;
1566     }
1567
1568     ReleaseSharedLock(&afs_xvcache);
1569
1570     ObtainWriteLock(&tvc->lock,54);
1571
1572     if (tvc->states & CStatd) {
1573 #ifdef AFS_LINUX22_ENV
1574         vcache2inode(tvc);
1575 #endif
1576         ReleaseWriteLock(&tvc->lock);
1577         return tvc;
1578     }
1579
1580 #if defined(AFS_OSF_ENV)
1581       if (afs_IsWired(tvc)) {
1582           ReleaseWriteLock(&tvc->lock);
1583           return tvc;
1584       }
1585 #endif /* AFS_OSF_ENV */
1586
1587     ObtainWriteLock(&afs_xcbhash, 464);
1588     tvc->states &= ~CUnique;   
1589     tvc->callback = 0;
1590     afs_DequeueCallback(tvc);
1591     ReleaseWriteLock(&afs_xcbhash);
1592
1593     /* It is always appropriate to throw away all the access rights? */
1594     afs_FreeAllAxs(&(tvc->Access));
1595     tvp = afs_GetVolume(afid, areq, READ_LOCK);   /* copy useful per-volume info */
1596     if (tvp) {
1597         if ((tvp->states & VForeign)) {
1598             if (newvcache) tvc->states |= CForeign;
1599             if (newvcache && (tvp->rootVnode == afid->Fid.Vnode) 
1600                 && (tvp->rootUnique == afid->Fid.Unique)) {
1601                 tvc->mvstat = 2;
1602               }
1603         }
1604         if (tvp->states & VRO) tvc->states |= CRO;
1605         if (tvp->states & VBackup) tvc->states |= CBackup;
1606         /* now copy ".." entry back out of volume structure, if necessary */
1607         if (tvc->mvstat == 2  && tvp->dotdot.Fid.Volume != 0) {
1608             if (!tvc->mvid)
1609                 tvc->mvid = (struct VenusFid *)
1610                     osi_AllocSmallSpace(sizeof(struct VenusFid));
1611             *tvc->mvid = tvp->dotdot;
1612         }
1613         afs_PutVolume(tvp, READ_LOCK);
1614     }
1615
1616     /* stat the file */
1617     afs_RemoveVCB(afid);
1618     {
1619     struct AFSFetchStatus OutStatus;
1620     code = afs_FetchStatus(tvc, afid, areq, &OutStatus);
1621     }
1622
1623     if (code) {
1624         ReleaseWriteLock(&tvc->lock);
1625
1626         ObtainReadLock(&afs_xvcache);
1627         AFS_FAST_RELE(tvc);
1628         ReleaseReadLock(&afs_xvcache);
1629         return (struct vcache *) 0;
1630     }
1631
1632     ReleaseWriteLock(&tvc->lock);
1633     return tvc;
1634
1635 } /*afs_GetVCache*/
1636
1637
1638
1639 struct vcache *afs_LookupVCache(struct VenusFid *afid, struct vrequest *areq,
1640                                 afs_int32 *cached, afs_int32 locktype,
1641                                 struct vcache *adp, char *aname)
1642 {
1643     afs_int32 code, now, newvcache=0, hash;
1644     struct VenusFid nfid;
1645     register struct vcache *tvc;
1646     struct volume *tvp;
1647     struct AFSFetchStatus OutStatus;
1648     struct AFSCallBack CallBack;
1649     struct AFSVolSync tsync;
1650     struct server *serverp = 0;
1651     afs_int32 origCBs;
1652     afs_int32 retry;
1653
1654     AFS_STATCNT(afs_GetVCache);
1655     if (cached) *cached = 0;            /* Init just in case */
1656
1657   loop1:
1658     ObtainReadLock(&afs_xvcache);
1659     tvc = afs_FindVCache(afid, 0, 0, &retry, DO_STATS /* no vlru */);
1660
1661     if (tvc) {
1662       ReleaseReadLock(&afs_xvcache);
1663       if (retry) {
1664 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
1665         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
1666         goto loop1;
1667 #endif
1668       }
1669       ObtainReadLock(&tvc->lock);
1670
1671       if (tvc->states & CStatd) {
1672         if (cached) {
1673           *cached = 1;
1674         }
1675         ReleaseReadLock(&tvc->lock);
1676         return tvc;
1677       } 
1678       tvc->states &= ~CUnique;   
1679
1680         ReleaseReadLock(&tvc->lock);
1681         ObtainReadLock(&afs_xvcache);
1682         AFS_FAST_RELE(tvc);
1683     }  /* if (tvc) */
1684
1685     ReleaseReadLock(&afs_xvcache);
1686
1687     /* lookup the file */
1688     nfid = *afid;
1689     now = osi_Time();
1690     origCBs = afs_allCBs;       /* if anything changes, we don't have a cb */
1691     code = afs_RemoteLookup(&adp->fid, areq, aname, &nfid, &OutStatus, &CallBack,
1692                             &serverp, &tsync);  
1693
1694   loop2:
1695     ObtainSharedLock(&afs_xvcache,6);
1696     tvc = afs_FindVCache(&nfid, 0, 0, &retry, DO_VLRU /* no xstats now*/);
1697     if (tvc && retry) {
1698 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
1699       ReleaseSharedLock(&afs_xvcache);
1700       spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
1701       goto loop2;
1702 #endif
1703     }
1704
1705     if (!tvc) {
1706         /* no cache entry, better grab one */
1707         UpgradeSToWLock(&afs_xvcache,22);
1708         tvc = afs_NewVCache(&nfid, (struct server *)0, 1, WRITE_LOCK);
1709         newvcache = 1;
1710         ConvertWToSLock(&afs_xvcache);
1711     }
1712
1713     ReleaseSharedLock(&afs_xvcache);
1714     ObtainWriteLock(&tvc->lock,55);
1715  
1716     /* It is always appropriate to throw away all the access rights? */
1717     afs_FreeAllAxs(&(tvc->Access));
1718     tvp = afs_GetVolume(afid, areq, READ_LOCK); /* copy useful per-vol info */
1719     if (tvp) {
1720         if ((tvp->states & VForeign)) {
1721             if (newvcache) tvc->states |= CForeign;
1722             if (newvcache && (tvp->rootVnode == afid->Fid.Vnode)
1723                 && (tvp->rootUnique == afid->Fid.Unique))
1724                 tvc->mvstat = 2;
1725         }
1726         if (tvp->states & VRO) tvc->states |= CRO;
1727         if (tvp->states & VBackup) tvc->states |= CBackup;
1728         /* now copy ".." entry back out of volume structure, if necessary */
1729         if (tvc->mvstat == 2  && tvp->dotdot.Fid.Volume != 0) {
1730             if (!tvc->mvid)
1731                 tvc->mvid = (struct VenusFid *)
1732                     osi_AllocSmallSpace(sizeof(struct VenusFid));
1733             *tvc->mvid = tvp->dotdot;
1734         }
1735     }
1736
1737     if (code) {
1738         ObtainWriteLock(&afs_xcbhash, 465);
1739         afs_DequeueCallback(tvc);
1740         tvc->states &= ~( CStatd | CUnique );
1741         ReleaseWriteLock(&afs_xcbhash);
1742         if ((tvc->states & CForeign) || (tvc->fid.Fid.Vnode & 1)) 
1743           osi_dnlc_purgedp (tvc);  /* if it (could be) a directory */
1744         if ( tvp )
1745                 afs_PutVolume(tvp, READ_LOCK);
1746         ReleaseWriteLock(&tvc->lock);
1747         ObtainReadLock(&afs_xvcache);
1748         AFS_FAST_RELE(tvc);
1749         ReleaseReadLock(&afs_xvcache);
1750         return (struct vcache *) 0;
1751     }
1752
1753     ObtainWriteLock(&afs_xcbhash, 466);
1754     if (origCBs == afs_allCBs) {
1755         if (CallBack.ExpirationTime) {
1756             tvc->callback = serverp;
1757             tvc->cbExpires = CallBack.ExpirationTime+now;
1758             tvc->states |= CStatd | CUnique;
1759             tvc->states &= ~CBulkFetching;
1760             afs_QueueCallback(tvc, CBHash(CallBack.ExpirationTime), tvp);
1761         } else if (tvc->states & CRO) {
1762             /* adapt gives us an hour. */
1763             tvc->cbExpires = 3600+osi_Time(); /*XXX*/
1764             tvc->states |= CStatd | CUnique;
1765             tvc->states &= ~CBulkFetching;
1766             afs_QueueCallback(tvc, CBHash(3600), tvp); 
1767         } else {
1768             tvc->callback = (struct server *)0;
1769             afs_DequeueCallback(tvc);
1770             tvc->states &= ~(CStatd | CUnique);   
1771             if ((tvc->states & CForeign) || (tvc->fid.Fid.Vnode & 1)) 
1772               osi_dnlc_purgedp (tvc);  /* if it (could be) a directory */
1773         }
1774     } else {
1775         afs_DequeueCallback(tvc);
1776         tvc->states &= ~CStatd; 
1777         tvc->states &= ~CUnique;   
1778         tvc->callback = (struct server *)0;
1779         if ((tvc->states & CForeign) || (tvc->fid.Fid.Vnode & 1)) 
1780           osi_dnlc_purgedp (tvc);  /* if it (could be) a directory */
1781     }   
1782     ReleaseWriteLock(&afs_xcbhash);
1783     if ( tvp )
1784         afs_PutVolume(tvp, READ_LOCK);
1785     afs_ProcessFS(tvc, &OutStatus, areq);
1786
1787     ReleaseWriteLock(&tvc->lock);
1788     return tvc;
1789
1790 }
1791
1792 struct vcache *afs_GetRootVCache(struct VenusFid *afid,
1793                                  struct vrequest *areq, afs_int32 *cached,
1794                                  struct volume *tvolp, afs_int32 locktype)
1795 {
1796     afs_int32 code, i, newvcache = 0, haveStatus = 0;
1797     afs_int32 getNewFid = 0;
1798     afs_uint32 start;
1799     struct VenusFid nfid;
1800     register struct vcache *tvc;
1801     struct server *serverp = 0;
1802     struct AFSFetchStatus OutStatus;
1803     struct AFSCallBack CallBack;
1804     struct AFSVolSync tsync;
1805     int origCBs;
1806
1807     start = osi_Time();
1808
1809  newmtpt:
1810     if (!tvolp->rootVnode || getNewFid) {
1811         struct VenusFid tfid;
1812
1813         tfid = *afid;
1814         tfid.Fid.Vnode = 0;     /* Means get rootfid of volume */
1815         origCBs = afs_allCBs; /* ignore InitCallBackState */
1816         code = afs_RemoteLookup(&tfid, areq, (char *)0, &nfid, 
1817                                 &OutStatus, &CallBack, &serverp, &tsync);
1818         if (code) {
1819             return (struct vcache *)0;
1820         }
1821 /*      ReleaseReadLock(&tvolp->lock);           */
1822         ObtainWriteLock(&tvolp->lock,56);
1823         tvolp->rootVnode = afid->Fid.Vnode = nfid.Fid.Vnode;
1824         tvolp->rootUnique = afid->Fid.Unique = nfid.Fid.Unique;
1825         ReleaseWriteLock(&tvolp->lock); 
1826 /*      ObtainReadLock(&tvolp->lock);*/
1827         haveStatus = 1;
1828     } else {
1829         afid->Fid.Vnode = tvolp->rootVnode;
1830         afid->Fid.Unique = tvolp->rootUnique;
1831     }   
1832     
1833     ObtainSharedLock(&afs_xvcache,7);
1834     i = VCHash(afid);
1835     for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
1836         if (!FidCmp(&(tvc->fid), afid)) {
1837 #ifdef  AFS_OSF_ENV
1838             /* Grab this vnode, possibly reactivating from the free list */
1839             /* for the present (95.05.25) everything on the hash table is 
1840              * definitively NOT in the free list -- at least until afs_reclaim
1841              * can be safely implemented */
1842             int vg;
1843             AFS_GUNLOCK();
1844             vg = vget((struct vnode *)tvc);   /* this bumps ref count */
1845             AFS_GLOCK();
1846             if (vg)
1847                 continue;
1848 #endif  /* AFS_OSF_ENV */
1849             break;
1850         }
1851     }
1852
1853     if (!haveStatus && (!tvc || !(tvc->states & CStatd))) {
1854         /* Mount point no longer stat'd or unknown. FID may have changed. */
1855 #ifdef AFS_OSF_ENV
1856         if (tvc)
1857             AFS_RELE(tvc);
1858 #endif
1859         tvc = (struct vcache*)0;
1860         getNewFid = 1;
1861         ReleaseSharedLock(&afs_xvcache);
1862         goto newmtpt;
1863     }
1864
1865     if (!tvc) {
1866         UpgradeSToWLock(&afs_xvcache,23);
1867         /* no cache entry, better grab one */
1868         tvc = afs_NewVCache(afid, (struct server *)0, 1, WRITE_LOCK);
1869         newvcache = 1;
1870         afs_stats_cmperf.vcacheMisses++;
1871     }
1872     else {
1873         if (cached) *cached = 1;
1874         afs_stats_cmperf.vcacheHits++;
1875 #ifdef  AFS_OSF_ENV
1876         /* we already bumped the ref count in the for loop above */
1877 #else   /* AFS_OSF_ENV */
1878         osi_vnhold(tvc,0);
1879 #endif
1880         UpgradeSToWLock(&afs_xvcache,24);
1881         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
1882            refpanic ("GRVC VLRU inconsistent0");
1883         }
1884         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
1885            refpanic ("GRVC VLRU inconsistent1");
1886         }
1887         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
1888            refpanic ("GRVC VLRU inconsistent2");
1889         }
1890         QRemove(&tvc->vlruq);           /* move to lruq head */
1891         QAdd(&VLRU, &tvc->vlruq);
1892         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
1893            refpanic ("GRVC VLRU inconsistent3");
1894         }
1895         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
1896            refpanic ("GRVC VLRU inconsistent4");
1897         }
1898         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
1899            refpanic ("GRVC VLRU inconsistent5");
1900         }
1901         vcachegen++;
1902     }
1903
1904     ReleaseWriteLock(&afs_xvcache);
1905
1906     if (tvc->states & CStatd) {
1907         return tvc;
1908     } else {  
1909
1910       ObtainReadLock(&tvc->lock);
1911       tvc->states &= ~CUnique;   
1912       tvc->callback = (struct server *)0;              /* redundant, perhaps */
1913       ReleaseReadLock(&tvc->lock);
1914     }
1915
1916     ObtainWriteLock(&tvc->lock,57);
1917
1918     /* It is always appropriate to throw away all the access rights? */
1919     afs_FreeAllAxs(&(tvc->Access));
1920
1921     if (newvcache) tvc->states |= CForeign;
1922     if (tvolp->states & VRO) tvc->states |= CRO;
1923     if (tvolp->states & VBackup) tvc->states |= CBackup;
1924     /* now copy ".." entry back out of volume structure, if necessary */
1925     if (newvcache && (tvolp->rootVnode == afid->Fid.Vnode) 
1926         && (tvolp->rootUnique == afid->Fid.Unique)) {
1927         tvc->mvstat = 2;
1928     }
1929     if (tvc->mvstat == 2  && tvolp->dotdot.Fid.Volume != 0) {
1930         if (!tvc->mvid)
1931             tvc->mvid = (struct VenusFid *)osi_AllocSmallSpace(sizeof(struct VenusFid));
1932         *tvc->mvid = tvolp->dotdot;
1933     }
1934
1935     /* stat the file */
1936     afs_RemoveVCB(afid);
1937
1938     if (!haveStatus) {
1939         struct VenusFid tfid;
1940
1941         tfid = *afid;
1942         tfid.Fid.Vnode = 0;     /* Means get rootfid of volume */
1943         origCBs = afs_allCBs; /* ignore InitCallBackState */
1944         code = afs_RemoteLookup(&tfid, areq, (char *)0, &nfid, &OutStatus,
1945                                 &CallBack, &serverp, &tsync);
1946     }
1947
1948     if (code) {
1949         ObtainWriteLock(&afs_xcbhash, 467);
1950         afs_DequeueCallback(tvc);
1951         tvc->callback = (struct server *)0;
1952         tvc->states &= ~(CStatd|CUnique);  
1953         ReleaseWriteLock(&afs_xcbhash);
1954         if ((tvc->states & CForeign) || (tvc->fid.Fid.Vnode & 1)) 
1955           osi_dnlc_purgedp (tvc);  /* if it (could be) a directory */
1956         ReleaseWriteLock(&tvc->lock);
1957         ObtainReadLock(&afs_xvcache);
1958         AFS_FAST_RELE(tvc);
1959         ReleaseReadLock(&afs_xvcache);
1960         return (struct vcache *) 0;
1961     }
1962         
1963     ObtainWriteLock(&afs_xcbhash, 468);
1964     if (origCBs == afs_allCBs) {
1965         tvc->states |= CTruth;
1966         tvc->callback = serverp;
1967         if (CallBack.ExpirationTime != 0) {  
1968             tvc->cbExpires = CallBack.ExpirationTime+start;
1969             tvc->states |= CStatd;
1970             tvc->states &= ~CBulkFetching;
1971             afs_QueueCallback(tvc, CBHash(CallBack.ExpirationTime), tvolp);
1972         } else if (tvc->states & CRO) {
1973             /* adapt gives us an hour. */
1974             tvc->cbExpires = 3600+osi_Time(); /*XXX*/
1975             tvc->states |= CStatd;
1976             tvc->states &= ~CBulkFetching;
1977             afs_QueueCallback(tvc, CBHash(3600), tvolp);
1978         }
1979     } else {
1980         afs_DequeueCallback(tvc);
1981         tvc->callback = (struct server *)0;
1982         tvc->states &= ~(CStatd | CUnique);
1983         if ((tvc->states & CForeign) || (tvc->fid.Fid.Vnode & 1)) 
1984           osi_dnlc_purgedp (tvc);  /* if it (could be) a directory */
1985     }
1986     ReleaseWriteLock(&afs_xcbhash);
1987     afs_ProcessFS(tvc, &OutStatus, areq);
1988     
1989     ReleaseWriteLock(&tvc->lock);
1990     return tvc;
1991 }
1992
1993
1994
1995 /*
1996  * must be called with avc write-locked 
1997  * don't absolutely have to invalidate the hint unless the dv has 
1998  * changed, but be sure to get it right else there will be consistency bugs.
1999  */
2000 afs_int32 afs_FetchStatus(struct vcache *avc, struct VenusFid *afid,
2001                       struct vrequest *areq, struct AFSFetchStatus *Outsp)
2002 {
2003   int code;
2004   afs_uint32 start;
2005   register struct conn *tc;
2006   struct AFSCallBack CallBack;
2007   struct AFSVolSync tsync;
2008   struct volume*    volp;
2009   XSTATS_DECLS
2010
2011     do {
2012         tc = afs_Conn(afid, areq, SHARED_LOCK);
2013         avc->quick.stamp = 0; avc->h1.dchint = NULL; /* invalidate hints */
2014         if (tc) {
2015             avc->callback = tc->srvr->server;
2016             start = osi_Time();
2017             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHSTATUS);
2018 #ifdef RX_ENABLE_LOCKS
2019             AFS_GUNLOCK();
2020 #endif /* RX_ENABLE_LOCKS */
2021             code = RXAFS_FetchStatus(tc->id,
2022                                      (struct AFSFid *) &afid->Fid,
2023                                      Outsp, &CallBack, &tsync);
2024 #ifdef RX_ENABLE_LOCKS
2025             AFS_GLOCK();
2026 #endif /* RX_ENABLE_LOCKS */
2027
2028             XSTATS_END_TIME;
2029
2030         }
2031         else code = -1;
2032     } while
2033         (afs_Analyze(tc, code, afid, areq,
2034                      AFS_STATS_FS_RPCIDX_FETCHSTATUS,
2035                      SHARED_LOCK, (struct cell *)0));
2036
2037 if (!code) {
2038   afs_ProcessFS(avc, Outsp, areq);
2039   volp = afs_GetVolume(afid, areq, READ_LOCK);
2040   ObtainWriteLock(&afs_xcbhash, 469);
2041   avc->states |= CTruth;
2042   if (avc->callback /* check for race */) {
2043     if (CallBack.ExpirationTime != 0) {  
2044       avc->cbExpires = CallBack.ExpirationTime+start;
2045       avc->states |= CStatd;
2046       avc->states &= ~CBulkFetching;
2047       afs_QueueCallback(avc, CBHash(CallBack.ExpirationTime), volp);
2048     }
2049     else if (avc->states & CRO) 
2050       { /* ordinary callback on a read-only volume -- AFS 3.2 style */
2051         avc->cbExpires = 3600+start;
2052         avc->states |= CStatd;
2053         avc->states &= ~CBulkFetching;
2054         afs_QueueCallback(avc, CBHash(3600), volp);
2055        }
2056     else {
2057       afs_DequeueCallback(avc);
2058       avc->callback = (struct server *)0;
2059       avc->states &= ~(CStatd|CUnique);  
2060       if ((avc->states & CForeign) || (avc->fid.Fid.Vnode & 1)) 
2061         osi_dnlc_purgedp (avc);  /* if it (could be) a directory */
2062     }
2063   }
2064   else {
2065     afs_DequeueCallback(avc);
2066     avc->callback = (struct server *)0;
2067     avc->states &= ~(CStatd|CUnique);  
2068     if ((avc->states & CForeign) || (avc->fid.Fid.Vnode & 1)) 
2069       osi_dnlc_purgedp (avc);  /* if it (could be) a directory */
2070   }
2071   ReleaseWriteLock(&afs_xcbhash);
2072   if ( volp )
2073     afs_PutVolume(volp, READ_LOCK);
2074 }
2075 else {     /* used to undo the local callback, but that's too extreme. 
2076             * There are plenty of good reasons that fetchstatus might return 
2077             * an error, such as EPERM.  If we have the vnode cached, statd, 
2078             * with callback, might as well keep track of the fact that we 
2079             * don't have access...
2080             */
2081      if (code == EPERM || code == EACCES) {
2082        struct axscache *ac;
2083        if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
2084          ac->axess = 0;
2085        else  /* not found, add a new one if possible */
2086          afs_AddAxs(avc->Access, areq->uid, 0);
2087      }
2088 }
2089 return code;
2090 }
2091
2092 /*
2093  * afs_StuffVcache
2094  *
2095  * Description:
2096  *      Stuff some information into the vcache for the given file.
2097  *
2098  * Parameters:
2099  *      afid      : File in question.
2100  *      OutStatus : Fetch status on the file.
2101  *      CallBack  : Callback info.
2102  *      tc        : RPC connection involved.
2103  *      areq      : vrequest involved.
2104  *
2105  * Environment:
2106  *      Nothing interesting.
2107  */
2108 void
2109 afs_StuffVcache(afid, OutStatus, CallBack, tc, areq)
2110     register struct VenusFid *afid;
2111     struct AFSFetchStatus *OutStatus;
2112     struct AFSCallBack *CallBack;
2113     register struct conn *tc;
2114     struct vrequest *areq;
2115
2116 { /*afs_StuffVcache*/
2117
2118     register afs_int32 code, i, newvcache=0;
2119     register struct vcache *tvc;
2120     struct AFSVolSync tsync;
2121     struct volume *tvp;
2122     struct axscache *ac;
2123     afs_int32 retry;
2124
2125     AFS_STATCNT(afs_StuffVcache);
2126 #ifdef IFS_VCACHECOUNT
2127     ifs_gvcachecall++;
2128 #endif
2129
2130   loop:
2131     ObtainSharedLock(&afs_xvcache,8);
2132
2133     tvc = afs_FindVCache(afid, 0, 0, &retry, DO_VLRU /* no stats */);
2134     if (tvc && retry) {
2135 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2136         ReleaseSharedLock(&afs_xvcache);
2137         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
2138         goto loop;
2139 #endif
2140    }
2141
2142     if (!tvc) {
2143         /* no cache entry, better grab one */
2144         UpgradeSToWLock(&afs_xvcache,25);
2145         tvc = afs_NewVCache(afid, (struct server *)0, 1, WRITE_LOCK);
2146         newvcache = 1;
2147         ConvertWToSLock(&afs_xvcache);
2148     }
2149
2150     ReleaseSharedLock(&afs_xvcache);
2151     ObtainWriteLock(&tvc->lock,58);
2152
2153     tvc->states &= ~CStatd;
2154     if ((tvc->states & CForeign) || (tvc->fid.Fid.Vnode & 1)) 
2155       osi_dnlc_purgedp (tvc);  /* if it (could be) a directory */
2156
2157     /* Is it always appropriate to throw away all the access rights? */
2158     afs_FreeAllAxs(&(tvc->Access));
2159
2160     /*Copy useful per-volume info*/
2161     tvp = afs_GetVolume(afid, areq, READ_LOCK);
2162     if (tvp) {
2163         if (newvcache && (tvp->states & VForeign)) tvc->states |= CForeign;
2164         if (tvp->states & VRO) tvc->states |= CRO;
2165         if (tvp->states & VBackup) tvc->states |= CBackup;
2166         /*
2167          * Now, copy ".." entry back out of volume structure, if
2168          * necessary
2169          */
2170         if (tvc->mvstat == 2  && tvp->dotdot.Fid.Volume != 0) {
2171             if (!tvc->mvid) tvc->mvid =
2172                 (struct VenusFid *) osi_AllocSmallSpace(sizeof(struct VenusFid));
2173             *tvc->mvid = tvp->dotdot;
2174         }
2175     }
2176     /* store the stat on the file */
2177     afs_RemoveVCB(afid);
2178     afs_ProcessFS(tvc, OutStatus, areq);
2179     tvc->callback = tc->srvr->server;
2180
2181     /* we use osi_Time twice below.  Ideally, we would use the time at which 
2182      * the FetchStatus call began, instead, but we don't have it here.  So we
2183      * make do with "now".  In the CRO case, it doesn't really matter. In 
2184      * the other case, we hope that the difference between "now" and when the 
2185      * call actually began execution on the server won't be larger than the
2186      * padding which the server keeps.  Subtract 1 second anyway, to be on 
2187      * the safe side.  Can't subtract more because we don't know how big
2188      * ExpirationTime is.  Possible consistency problems may arise if the call
2189      * timeout period becomes longer than the server's expiration padding.  */
2190     ObtainWriteLock(&afs_xcbhash, 470);
2191     if (CallBack->ExpirationTime != 0) {
2192         tvc->cbExpires = CallBack->ExpirationTime+osi_Time()-1; 
2193         tvc->states |= CStatd;
2194         tvc->states &= ~CBulkFetching;
2195         afs_QueueCallback(tvc, CBHash(CallBack->ExpirationTime), tvp);
2196         }
2197     else if (tvc->states & CRO) {
2198        /* old-fashioned AFS 3.2 style */
2199        tvc->cbExpires = 3600+osi_Time(); /*XXX*/
2200        tvc->states |= CStatd;
2201        tvc->states &= ~CBulkFetching;
2202        afs_QueueCallback(tvc, CBHash(3600), tvp); 
2203      }
2204     else {
2205       afs_DequeueCallback(tvc);
2206       tvc->callback = (struct server *)0;
2207       tvc->states &= ~(CStatd|CUnique);  
2208       if ((tvc->states & CForeign) || (tvc->fid.Fid.Vnode & 1)) 
2209         osi_dnlc_purgedp (tvc);  /* if it (could be) a directory */
2210     }
2211     ReleaseWriteLock(&afs_xcbhash);
2212     if ( tvp )
2213         afs_PutVolume(tvp, READ_LOCK);
2214         
2215     /* look in per-pag cache */
2216       if (tvc->Access && (ac = afs_FindAxs(tvc->Access, areq->uid)))
2217           ac->axess = OutStatus->CallerAccess;   /* substitute pags */
2218       else  /* not found, add a new one if possible */
2219           afs_AddAxs(tvc->Access, areq->uid, OutStatus->CallerAccess);
2220
2221     ReleaseWriteLock(&tvc->lock);
2222     afs_Trace4(afs_iclSetp, CM_TRACE_STUFFVCACHE, ICL_TYPE_POINTER, tvc,
2223                ICL_TYPE_POINTER, tvc->callback, ICL_TYPE_INT32, tvc->cbExpires,
2224                ICL_TYPE_INT32, tvc->cbExpires-osi_Time());
2225     /*
2226      * Release ref count... hope this guy stays around...
2227      */
2228     afs_PutVCache(tvc, WRITE_LOCK);
2229 } /*afs_StuffVcache*/
2230
2231 /*
2232  * afs_PutVCache
2233  *
2234  * Description:
2235  *      Decrements the reference count on a cache entry.
2236  *
2237  * Parameters:
2238  *      avc : Pointer to the cache entry to decrement.
2239  *
2240  * Environment:
2241  *      Nothing interesting.
2242  */
2243 void
2244 afs_PutVCache(avc, locktype)
2245     register struct vcache *avc;
2246     afs_int32 locktype;
2247 { /*afs_PutVCache*/
2248
2249     AFS_STATCNT(afs_PutVCache);
2250     /*
2251      * Can we use a read lock here?
2252      */
2253     ObtainReadLock(&afs_xvcache);
2254     AFS_FAST_RELE(avc);
2255     ReleaseReadLock(&afs_xvcache);
2256 } /*afs_PutVCache*/
2257
2258 /*
2259  * afs_FindVCache
2260  *
2261  * Description:
2262  *      Find a vcache entry given a fid.
2263  *
2264  * Parameters:
2265  *      afid : Pointer to the fid whose cache entry we desire.
2266  *      retry: (SGI-specific) tell the caller to drop the lock on xvcache, 
2267  *             unlock the vnode, and try again.
2268  *      flags: bit 1 to specify whether to compute hit statistics.  Not
2269  *             set if FindVCache is called as part of internal bookkeeping.
2270  *
2271  * Environment:
2272  *      Must be called with the afs_xvcache lock at least held at
2273  *      the read level.  In order to do the VLRU adjustment, the xvcache lock
2274  *      must be shared-- we upgrade it here.
2275  */
2276
2277 struct vcache *afs_FindVCache(struct VenusFid *afid, afs_int32 lockit,
2278                               afs_int32 locktype, afs_int32 *retry, afs_int32 flag)
2279 {
2280
2281     register struct vcache *tvc;
2282     afs_int32 i;
2283
2284     AFS_STATCNT(afs_FindVCache);
2285
2286     i = VCHash(afid);
2287     for(tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2288         if (FidMatches(afid, tvc)) {
2289 #ifdef  AFS_OSF_ENV
2290             /* Grab this vnode, possibly reactivating from the free list */
2291             int vg;
2292             AFS_GUNLOCK();
2293             vg = vget((struct vnode *)tvc);
2294             AFS_GLOCK();
2295             if (vg)
2296                 continue;
2297 #endif  /* AFS_OSF_ENV */
2298             break;
2299         }
2300     }
2301
2302     /* should I have a read lock on the vnode here? */
2303     if (tvc) {
2304         if (retry) *retry = 0;
2305 #if !defined(AFS_OSF_ENV)
2306         osi_vnhold(tvc, retry);  /* already held, above */
2307         if (retry && *retry) 
2308           return 0;
2309 #endif
2310         /*
2311          * only move to front of vlru if we have proper vcache locking)
2312          */
2313         if (flag & DO_VLRU) {
2314            if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2315               refpanic ("FindVC VLRU inconsistent1");
2316            }
2317            if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2318               refpanic ("FindVC VLRU inconsistent1");
2319            }
2320            if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2321               refpanic ("FindVC VLRU inconsistent2");
2322            }
2323             UpgradeSToWLock(&afs_xvcache,26);
2324             QRemove(&tvc->vlruq);
2325             QAdd(&VLRU, &tvc->vlruq);
2326             ConvertWToSLock(&afs_xvcache);
2327            if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2328               refpanic ("FindVC VLRU inconsistent1");
2329            }
2330            if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2331               refpanic ("FindVC VLRU inconsistent2");
2332            }
2333            if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2334               refpanic ("FindVC VLRU inconsistent3");
2335            }
2336         }
2337         vcachegen++;
2338     } 
2339
2340     if (flag & DO_STATS) {
2341       if (tvc)  afs_stats_cmperf.vcacheHits++;
2342       else      afs_stats_cmperf.vcacheMisses++;
2343       if (afid->Cell == LOCALCELL)
2344         afs_stats_cmperf.vlocalAccesses++;
2345       else
2346         afs_stats_cmperf.vremoteAccesses++;
2347     }
2348
2349 #ifdef AFS_LINUX22_ENV
2350     if (tvc && (tvc->states & CStatd))
2351         vcache2inode(tvc); /* mainly to reset i_nlink */
2352 #endif
2353     return tvc;
2354 } /*afs_FindVCache*/
2355
2356 /*
2357  * afs_NFSFindVCache
2358  *
2359  * Description:
2360  *      Find a vcache entry given a fid. Does a wildcard match on what we
2361  *      have for the fid. If more than one entry, don't return anything.
2362  *
2363  * Parameters:
2364  *      avcp : Fill in pointer if we found one and only one.
2365  *      afid : Pointer to the fid whose cache entry we desire.
2366  *      retry: (SGI-specific) tell the caller to drop the lock on xvcache, 
2367  *             unlock the vnode, and try again.
2368  *      flags: bit 1 to specify whether to compute hit statistics.  Not
2369  *             set if FindVCache is called as part of internal bookkeeping.
2370  *
2371  * Environment:
2372  *      Must be called with the afs_xvcache lock at least held at
2373  *      the read level.  In order to do the VLRU adjustment, the xvcache lock
2374  *      must be shared-- we upgrade it here.
2375  *
2376  * Return value:
2377  *      number of matches found.
2378  */
2379
2380 int afs_duplicate_nfs_fids=0;
2381
2382 afs_int32 afs_NFSFindVCache(avcp, afid, lockit)
2383      struct vcache **avcp;
2384     struct VenusFid *afid;
2385     afs_int32 lockit;
2386 { /*afs_FindVCache*/
2387
2388     register struct vcache *tvc;
2389     afs_int32 i;
2390     afs_int32 retry = 0;
2391     afs_int32 count = 0;
2392     struct vcache *found_tvc = NULL;
2393
2394     AFS_STATCNT(afs_FindVCache);
2395
2396  loop:
2397
2398     ObtainSharedLock(&afs_xvcache,331); 
2399
2400     i = VCHash(afid);
2401     for(tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2402         /* Match only on what we have.... */
2403         if (((tvc->fid.Fid.Vnode & 0xffff) == afid->Fid.Vnode)
2404             && (tvc->fid.Fid.Volume == afid->Fid.Volume)
2405             && ((tvc->fid.Fid.Unique & 0xffffff) == afid->Fid.Unique)
2406             && (tvc->fid.Cell == afid->Cell)) {
2407 #ifdef  AFS_OSF_ENV
2408             /* Grab this vnode, possibly reactivating from the free list */
2409             int vg;
2410             AFS_GUNLOCK();
2411             vg = vget((struct vnode *)tvc);
2412             AFS_GLOCK();
2413             if (vg) {
2414                 /* This vnode no longer exists. */
2415                 continue;
2416             }
2417 #endif  /* AFS_OSF_ENV */
2418             count ++;
2419             if (found_tvc) {
2420                 /* Duplicates */
2421 #ifdef AFS_OSF_ENV
2422                 /* Drop our reference counts. */
2423                 vrele((struct vnode *)tvc);
2424                 vrele((struct vnode *)found_tvc);
2425 #endif
2426                 afs_duplicate_nfs_fids++;
2427                 ReleaseSharedLock(&afs_xvcache);
2428                 return count;
2429             }
2430             found_tvc = tvc;
2431         }
2432     }
2433
2434     tvc = found_tvc;
2435     /* should I have a read lock on the vnode here? */
2436     if (tvc) {
2437 #if defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2438         osi_vnhold(tvc, &retry); 
2439         if (retry) {
2440             count = 0;
2441             found_tvc = (struct vcache*)0;
2442             ReleaseSharedLock(&afs_xvcache);
2443             spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
2444             goto loop;
2445         }
2446 #else
2447 #if !defined(AFS_OSF_ENV)
2448         osi_vnhold(tvc, (int*)0);  /* already held, above */
2449 #endif
2450 #endif
2451         /*
2452          * We obtained the xvcache lock above.
2453          */
2454         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2455             refpanic ("FindVC VLRU inconsistent1");
2456         }
2457         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2458             refpanic ("FindVC VLRU inconsistent1");
2459         }
2460         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2461             refpanic ("FindVC VLRU inconsistent2");
2462         }
2463         UpgradeSToWLock(&afs_xvcache,568);
2464         QRemove(&tvc->vlruq);
2465         QAdd(&VLRU, &tvc->vlruq);
2466         ConvertWToSLock(&afs_xvcache);
2467         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2468             refpanic ("FindVC VLRU inconsistent1");
2469         }
2470         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2471             refpanic ("FindVC VLRU inconsistent2");
2472         }
2473         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2474             refpanic ("FindVC VLRU inconsistent3");
2475         }
2476     }
2477     vcachegen++;
2478
2479     if (tvc)    afs_stats_cmperf.vcacheHits++;
2480     else        afs_stats_cmperf.vcacheMisses++;
2481     if (afid->Cell == LOCALCELL)
2482         afs_stats_cmperf.vlocalAccesses++;
2483     else
2484         afs_stats_cmperf.vremoteAccesses++;
2485
2486     *avcp = tvc; /* May be null */
2487
2488     ReleaseSharedLock(&afs_xvcache);
2489     return (tvc ? 1 : 0);
2490
2491 } /*afs_NFSFindVCache*/
2492
2493
2494
2495
2496 /*
2497  * afs_vcacheInit
2498  *
2499  * Initialize vcache related variables
2500  */
2501 void afs_vcacheInit(int astatSize)
2502 {
2503     register struct vcache *tvp;
2504     int i;
2505 #if     defined(AFS_OSF_ENV)
2506     if (!afs_maxvcount) {
2507 #if     defined(AFS_OSF30_ENV)
2508         afs_maxvcount = max_vnodes/2;  /* limit ourselves to half the total */
2509 #else
2510         afs_maxvcount = nvnode/2;  /* limit ourselves to half the total */  
2511 #endif 
2512         if (astatSize < afs_maxvcount) {
2513             afs_maxvcount = astatSize;
2514         }
2515     }
2516 #else   /* AFS_OSF_ENV */
2517     freeVCList = (struct vcache *)0;
2518 #endif
2519
2520     RWLOCK_INIT(&afs_xvcache, "afs_xvcache");
2521     LOCK_INIT(&afs_xvcb, "afs_xvcb");
2522
2523 #if     !defined(AFS_OSF_ENV)
2524     /* Allocate and thread the struct vcache entries */
2525     tvp = (struct vcache *) afs_osi_Alloc(astatSize * sizeof(struct vcache));
2526     bzero((char *)tvp, sizeof(struct vcache)*astatSize);
2527
2528     Initial_freeVCList = tvp;
2529     freeVCList = &(tvp[0]);
2530     for(i=0; i < astatSize-1; i++) {
2531        tvp[i].nextfree = &(tvp[i+1]);
2532     }   
2533     tvp[astatSize-1].nextfree = (struct vcache *) 0;
2534 #ifdef  AFS_AIX32_ENV
2535     pin((char *)tvp, astatSize * sizeof(struct vcache));        /* XXX */    
2536 #endif
2537 #endif
2538
2539
2540 #if defined(AFS_SGI_ENV)
2541     for(i=0; i < astatSize; i++) {
2542         char name[METER_NAMSZ];
2543         struct vcache *tvc = &tvp[i];
2544
2545         tvc->v.v_number = ++afsvnumbers;
2546         tvc->vc_rwlockid = OSI_NO_LOCKID;
2547         initnsema(&tvc->vc_rwlock, 1, makesname(name, "vrw", tvc->v.v_number));
2548 #ifndef AFS_SGI53_ENV
2549         initnsema(&tvc->v.v_sync, 0, makesname(name, "vsy", tvc->v.v_number));
2550 #endif
2551 #ifndef AFS_SGI62_ENV
2552         initnlock(&tvc->v.v_lock, makesname(name, "vlk", tvc->v.v_number));
2553 #endif /* AFS_SGI62_ENV */
2554     }
2555 #endif
2556
2557     QInit(&VLRU);
2558
2559
2560 }
2561
2562 /*
2563  * shutdown_vcache
2564  *
2565  */
2566 void shutdown_vcache(void)
2567 {
2568     int i;
2569     struct afs_cbr *tsp, *nsp;
2570     /*
2571      * XXX We may potentially miss some of the vcaches because if when there're no
2572      * free vcache entries and all the vcache entries are active ones then we allocate
2573      * an additional one - admittedly we almost never had that occur.
2574      */
2575 #if     !defined(AFS_OSF_ENV)
2576     afs_osi_Free(Initial_freeVCList, afs_cacheStats * sizeof(struct vcache));
2577 #endif
2578 #ifdef  AFS_AIX32_ENV
2579     unpin(Initial_freeVCList, afs_cacheStats * sizeof(struct vcache));
2580 #endif
2581
2582     {
2583         register struct afs_q *tq, *uq;
2584         register struct vcache *tvc;
2585         for (tq = VLRU.prev; tq != &VLRU; tq = uq) {
2586             tvc = QTOV(tq);
2587             uq = QPrev(tq);
2588             if (tvc->mvid) {
2589                 osi_FreeSmallSpace(tvc->mvid);
2590                 tvc->mvid = (struct VenusFid*)0;
2591             }
2592 #ifdef  AFS_AIX_ENV
2593             aix_gnode_rele((struct vnode *)tvc);
2594 #endif
2595             if (tvc->linkData) {
2596                 afs_osi_Free(tvc->linkData, strlen(tvc->linkData)+1);
2597                 tvc->linkData = 0;
2598             }
2599         }
2600         /* 
2601          * Also free the remaining ones in the Cache 
2602          */
2603         for (i=0; i < VCSIZE; i++) {
2604             for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2605                 if (tvc->mvid) {
2606                     osi_FreeSmallSpace(tvc->mvid);
2607                     tvc->mvid = (struct VenusFid*)0;
2608                 }
2609 #ifdef  AFS_AIX_ENV
2610                 if (tvc->v.v_gnode)
2611                     afs_osi_Free(tvc->v.v_gnode, sizeof(struct gnode));
2612 #ifdef  AFS_AIX32_ENV
2613                 if (tvc->segid) {
2614                     AFS_GUNLOCK();
2615                     vms_delete(tvc->segid);
2616                     AFS_GLOCK();
2617                     tvc->segid = tvc->vmh = NULL;
2618                     if (tvc->vrefCount) osi_Panic("flushVcache: vm race");
2619                 }
2620                 if (tvc->credp) {
2621                     crfree(tvc->credp);
2622                     tvc->credp = NULL;
2623                 }
2624 #endif
2625 #endif
2626 #if     defined(AFS_SUN5_ENV)
2627                 if (tvc->credp) {
2628                     crfree(tvc->credp);
2629                     tvc->credp = NULL;
2630                 }
2631 #endif
2632                 if (tvc->linkData) {
2633                     afs_osi_Free(tvc->linkData, strlen(tvc->linkData)+1);
2634                     tvc->linkData = 0;
2635                 }
2636
2637                 afs_FreeAllAxs(&(tvc->Access));
2638             }
2639             afs_vhashT[i] = 0;
2640         }
2641     }
2642     /*
2643      * Free any leftover callback queue
2644      */
2645     for (tsp = afs_cbrSpace; tsp; tsp = nsp ) {
2646         nsp = tsp->next;
2647         afs_osi_Free((char *)tsp, AFS_NCBRS * sizeof(struct afs_cbr));
2648     }
2649     afs_cbrSpace = 0;
2650
2651 #if     !defined(AFS_OSF_ENV)
2652     freeVCList = Initial_freeVCList = 0;
2653 #endif
2654     RWLOCK_INIT(&afs_xvcache, "afs_xvcache");
2655     LOCK_INIT(&afs_xvcb, "afs_xvcb");
2656     QInit(&VLRU);
2657
2658 }