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