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