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