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