cm: address race condition in afs_QueueVCB
[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_WriteVCacheDiscon
23  * afs_SimpleVStat
24  * afs_ProcessFS
25  * TellALittleWhiteLie
26  * afs_RemoteLookup
27  * afs_GetVCache
28  * afs_LookupVCache
29  * afs_GetRootVCache
30  * afs_UpdateStatus
31  * afs_FetchStatus
32  * afs_StuffVcache
33  * afs_PutVCache
34  * afs_FindVCache
35  * afs_NFSFindVCache
36  * afs_vcacheInit
37  * shutdown_vcache
38  *
39  */
40 #include <afsconfig.h>
41 #include "afs/param.h"
42
43
44 #include "afs/sysincludes.h"    /*Standard vendor system headers */
45 #include "afsincludes.h"        /*AFS-based standard headers */
46 #include "afs/afs_stats.h"
47 #include "afs/afs_cbqueue.h"
48 #include "afs/afs_osidnlc.h"
49
50 #if defined(AFS_LINUX22_ENV)
51 afs_int32 afs_maxvcount = 0;    /* max number of vcache entries */
52 afs_int32 afs_vcount = 0;       /* number of vcache in use now */
53 #endif /* AFS_LINUX22_ENV */
54
55 #ifdef AFS_SGI_ENV
56 int afsvnumbers = 0;
57 #endif
58
59 #ifdef AFS_SGI64_ENV
60 char *makesname();
61 #endif /* AFS_SGI64_ENV */
62
63 /* Exported variables */
64 #ifdef AFS_DISCON_ENV
65 afs_rwlock_t afs_xvcdirty;      /*Lock: discon vcache dirty list mgmt */
66 #endif
67 afs_rwlock_t afs_xvcache;       /*Lock: alloc new stat cache entries */
68 afs_rwlock_t afs_xvreclaim;     /*Lock: entries reclaimed, not on free list */
69 afs_lock_t afs_xvcb;            /*Lock: fids on which there are callbacks */
70 #if !defined(AFS_LINUX22_ENV)
71 static struct vcache *freeVCList;       /*Free list for stat cache entries */
72 struct vcache *ReclaimedVCList; /*Reclaimed list for stat entries */
73 static struct vcache *Initial_freeVCList;       /*Initial list for above */
74 #endif
75 struct afs_q VLRU;              /*vcache LRU */
76 afs_int32 vcachegen = 0;
77 unsigned int afs_paniconwarn = 0;
78 struct vcache *afs_vhashT[VCSIZE];
79 struct afs_q afs_vhashTV[VCSIZE];
80 static struct afs_cbr *afs_cbrHashT[CBRSIZE];
81 afs_int32 afs_bulkStatsLost;
82 int afs_norefpanic = 0;
83
84
85 /* Disk backed vcache definitions 
86  * Both protected by xvcache */
87 #ifdef AFS_DISCON_ENV
88 static int afs_nextVcacheSlot = 0;
89 static struct afs_slotlist *afs_freeSlotList = NULL;
90 #endif
91
92 /* Forward declarations */
93 static afs_int32 afs_QueueVCB(struct vcache *avc);
94
95 /*!
96  * Generate an index into the hash table for a given Fid.
97  * \param fid 
98  * \return The hash value.
99  */
100 static int
101 afs_HashCBRFid(struct AFSFid *fid)
102 {
103     return (fid->Volume + fid->Vnode + fid->Unique) % CBRSIZE;
104 }
105
106 /*!
107  * Insert a CBR entry into the hash table.
108  * Must be called with afs_xvcb held.
109  * \param cbr
110  * \return
111  */
112 static void
113 afs_InsertHashCBR(struct afs_cbr *cbr)
114 {
115     int slot = afs_HashCBRFid(&cbr->fid);
116
117     cbr->hash_next = afs_cbrHashT[slot];
118     if (afs_cbrHashT[slot])
119         afs_cbrHashT[slot]->hash_pprev = &cbr->hash_next;
120
121     cbr->hash_pprev = &afs_cbrHashT[slot];
122     afs_cbrHashT[slot] = cbr;
123 }
124
125 /*!
126  *
127  * Flush the given vcache entry.
128  *
129  * Environment:
130  *      afs_xvcache lock must be held for writing upon entry to
131  *      prevent people from changing the vrefCount field, and to
132  *      protect the lruq and hnext fields.
133  * LOCK: afs_FlushVCache afs_xvcache W
134  * REFCNT: vcache ref count must be zero on entry except for osf1
135  * RACE: lock is dropped and reobtained, permitting race in caller
136  *
137  * \param avc Pointer to vcache entry to flush.
138  * \param slept Pointer to int to set 1 if we sleep/drop locks, 0 if we don't.
139  *
140  */
141 int
142 afs_FlushVCache(struct vcache *avc, int *slept)
143 {                               /*afs_FlushVCache */
144
145     afs_int32 i, code;
146     struct vcache **uvc, *wvc;
147
148     *slept = 0;
149     AFS_STATCNT(afs_FlushVCache);
150     afs_Trace2(afs_iclSetp, CM_TRACE_FLUSHV, ICL_TYPE_POINTER, avc,
151                ICL_TYPE_INT32, avc->f.states);
152
153     code = osi_VM_FlushVCache(avc, slept);
154     if (code)
155         goto bad;
156
157     if (avc->f.states & CVFlushed) {
158         code = EBUSY;
159         goto bad;
160     }
161 #if !defined(AFS_LINUX22_ENV)
162     if (avc->nextfree || !avc->vlruq.prev || !avc->vlruq.next) {        /* qv afs.h */
163         refpanic("LRU vs. Free inconsistency");
164     }
165 #endif
166     avc->f.states |= CVFlushed;
167     /* pull the entry out of the lruq and put it on the free list */
168     QRemove(&avc->vlruq);
169
170     /* keep track of # of files that we bulk stat'd, but never used
171      * before they got recycled.
172      */
173     if (avc->f.states & CBulkStat)
174         afs_bulkStatsLost++;
175     vcachegen++;
176     /* remove entry from the hash chain */
177     i = VCHash(&avc->f.fid);
178     uvc = &afs_vhashT[i];
179     for (wvc = *uvc; wvc; uvc = &wvc->hnext, wvc = *uvc) {
180         if (avc == wvc) {
181             *uvc = avc->hnext;
182             avc->hnext = (struct vcache *)NULL;
183             break;
184         }
185     }
186
187     /* remove entry from the volume hash table */
188     QRemove(&avc->vhashq);
189
190     if (avc->mvid)
191         osi_FreeSmallSpace(avc->mvid);
192     avc->mvid = (struct VenusFid *)0;
193     if (avc->linkData) {
194         afs_osi_Free(avc->linkData, strlen(avc->linkData) + 1);
195         avc->linkData = NULL;
196     }
197 #if defined(AFS_XBSD_ENV) || defined(AFS_DARWIN_ENV)
198     /* OK, there are no internal vrefCounts, so there shouldn't
199      * be any more refs here. */
200     if (avc->v) {
201 #ifdef AFS_DARWIN80_ENV
202         vnode_clearfsnode(AFSTOV(avc));
203         vnode_removefsref(AFSTOV(avc));
204 #else
205         avc->v->v_data = NULL;  /* remove from vnode */
206 #endif
207         AFSTOV(avc) = NULL;             /* also drop the ptr to vnode */
208     }
209 #endif
210 #ifdef AFS_SUN510_ENV
211     /* As we use private vnodes, cleanup is up to us */
212     vn_reinit(AFSTOV(avc));
213 #endif
214     afs_FreeAllAxs(&(avc->Access));
215     afs_QueueVCB(avc);
216     ObtainWriteLock(&afs_xcbhash, 460);
217     afs_DequeueCallback(avc);   /* remove it from queued callbacks list */
218     avc->f.states &= ~(CStatd | CUnique);
219     ReleaseWriteLock(&afs_xcbhash);
220     if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
221         osi_dnlc_purgedp(avc);  /* if it (could be) a directory */
222     else
223         osi_dnlc_purgevp(avc);
224
225     /*
226      * Next, keep track of which vnodes we've deleted for create's
227      * optimistic synchronization algorithm
228      */
229     afs_allZaps++;
230     if (avc->f.fid.Fid.Vnode & 1)
231         afs_oddZaps++;
232     else
233         afs_evenZaps++;
234
235 #if !defined(AFS_LINUX22_ENV)
236     /* put the entry in the free list */
237     avc->nextfree = freeVCList;
238     freeVCList = avc;
239     if (avc->vlruq.prev || avc->vlruq.next) {
240         refpanic("LRU vs. Free inconsistency");
241     }
242     avc->f.states |= CVFlushed;
243 #else
244     /* This should put it back on the vnode free list since usecount is 1 */
245     afs_vcount--;
246     vSetType(avc, VREG);
247     if (VREFCOUNT_GT(avc,0)) {
248         AFS_RELE(AFSTOV(avc));
249         afs_stats_cmperf.vcacheXAllocs--;
250     } else {
251         if (afs_norefpanic) {
252             printf("flush vc refcnt < 1");
253             afs_norefpanic++;
254         } else
255             osi_Panic("flush vc refcnt < 1");
256     }
257 #endif /* AFS_LINUX22_ENV */
258     return 0;
259
260   bad:
261     return code;
262 }                               /*afs_FlushVCache */
263
264 #ifndef AFS_SGI_ENV
265 /*!
266  *  The core of the inactive vnode op for all but IRIX.
267  *
268  * \param avc 
269  * \param acred
270  */
271 void
272 afs_InactiveVCache(struct vcache *avc, afs_ucred_t *acred)
273 {
274     AFS_STATCNT(afs_inactive);
275     if (avc->f.states & CDirty) {
276         /* we can't keep trying to push back dirty data forever.  Give up. */
277         afs_InvalidateAllSegments(avc); /* turns off dirty bit */
278     }
279     avc->f.states &= ~CMAPPED;  /* mainly used by SunOS 4.0.x */
280     avc->f.states &= ~CDirty;   /* Turn it off */
281     if (avc->f.states & CUnlinked) {
282         if (CheckLock(&afs_xvcache) || CheckLock(&afs_xdcache)) {
283             avc->f.states |= CUnlinkedDel;
284             return;
285         }
286         afs_remunlink(avc, 1);  /* ignore any return code */
287     }
288
289 }
290 #endif
291
292 /*!
293  *   Allocate a callback return structure from the
294  * free list and return it.
295  *
296  * Environment: The alloc and free routines are both called with the afs_xvcb lock
297  * held, so we don't have to worry about blocking in osi_Alloc.
298  *
299  * \return The allocated afs_cbr.
300  */
301 static struct afs_cbr *afs_cbrSpace = 0;
302 /* if alloc limit below changes, fix me! */
303 static struct afs_cbr *afs_cbrHeads[2];
304 struct afs_cbr *
305 afs_AllocCBR(void)
306 {
307     register struct afs_cbr *tsp;
308     int i;
309
310     while (!afs_cbrSpace) {
311         if (afs_stats_cmperf.CallBackAlloced >= 2) {
312             /* don't allocate more than 2 * AFS_NCBRS for now */
313             afs_FlushVCBs(0);
314             afs_stats_cmperf.CallBackFlushes++;
315         } else {
316             /* try allocating */
317             tsp =
318                 (struct afs_cbr *)afs_osi_Alloc(AFS_NCBRS *
319                                                 sizeof(struct afs_cbr));
320             for (i = 0; i < AFS_NCBRS - 1; i++) {
321                 tsp[i].next = &tsp[i + 1];
322             }
323             tsp[AFS_NCBRS - 1].next = 0;
324             afs_cbrSpace = tsp;
325             afs_cbrHeads[afs_stats_cmperf.CallBackAlloced] = tsp;
326             afs_stats_cmperf.CallBackAlloced++;
327         }
328     }
329     tsp = afs_cbrSpace;
330     afs_cbrSpace = tsp->next;
331     return tsp;
332 }
333
334 /*!
335  * Free a callback return structure, removing it from all lists.
336  *
337  * Environment: the xvcb lock is held over these calls.
338  *
339  * \param asp The address of the structure to free.
340  *
341  * \rerurn 0
342  */
343 int
344 afs_FreeCBR(register struct afs_cbr *asp)
345 {
346     *(asp->pprev) = asp->next;
347     if (asp->next)
348         asp->next->pprev = asp->pprev;
349
350     *(asp->hash_pprev) = asp->hash_next;
351     if (asp->hash_next)
352         asp->hash_next->hash_pprev = asp->hash_pprev;
353
354     asp->next = afs_cbrSpace;
355     afs_cbrSpace = asp;
356     return 0;
357 }
358
359 /*!
360  *   Flush all queued callbacks to all servers.
361  *
362  * Environment: holds xvcb lock over RPC to guard against race conditions
363  *      when a new callback is granted for the same file later on.
364  *
365  * \return 0 for success.
366  */
367 afs_int32
368 afs_FlushVCBs(afs_int32 lockit)
369 {
370     struct AFSFid *tfids;
371     struct AFSCallBack callBacks[1];
372     struct AFSCBFids fidArray;
373     struct AFSCBs cbArray;
374     afs_int32 code;
375     struct afs_cbr *tcbrp;
376     int tcount;
377     struct server *tsp;
378     int i;
379     struct vrequest treq;
380     struct afs_conn *tc;
381     int safety1, safety2, safety3;
382     XSTATS_DECLS;
383     if ((code = afs_InitReq(&treq, afs_osi_credp)))
384         return code;
385     treq.flags |= O_NONBLOCK;
386     tfids = afs_osi_Alloc(sizeof(struct AFSFid) * AFS_MAXCBRSCALL);
387
388     if (lockit)
389         MObtainWriteLock(&afs_xvcb, 273);
390     ObtainReadLock(&afs_xserver);
391     for (i = 0; i < NSERVERS; i++) {
392         for (safety1 = 0, tsp = afs_servers[i];
393              tsp && safety1 < afs_totalServers + 10;
394              tsp = tsp->next, safety1++) {
395             /* don't have any */
396             if (tsp->cbrs == (struct afs_cbr *)0)
397                 continue;
398
399             /* otherwise, grab a block of AFS_MAXCBRSCALL from the list
400              * and make an RPC, over and over again.
401              */
402             tcount = 0;         /* number found so far */
403             for (safety2 = 0; safety2 < afs_cacheStats; safety2++) {
404                 if (tcount >= AFS_MAXCBRSCALL || !tsp->cbrs) {
405                     /* if buffer is full, or we've queued all we're going
406                      * to from this server, we should flush out the
407                      * callbacks.
408                      */
409                     fidArray.AFSCBFids_len = tcount;
410                     fidArray.AFSCBFids_val = (struct AFSFid *)tfids;
411                     cbArray.AFSCBs_len = 1;
412                     cbArray.AFSCBs_val = callBacks;
413                     memset(&callBacks[0], 0, sizeof(callBacks[0]));
414                     callBacks[0].CallBackType = CB_EXCLUSIVE;
415                     for (safety3 = 0; safety3 < MAXHOSTS * 2; safety3++) {
416                         tc = afs_ConnByHost(tsp, tsp->cell->fsport,
417                                             tsp->cell->cellNum, &treq, 0,
418                                             SHARED_LOCK);
419                         if (tc) {
420                             XSTATS_START_TIME
421                                 (AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS);
422                             RX_AFS_GUNLOCK();
423                             code =
424                                 RXAFS_GiveUpCallBacks(tc->id, &fidArray,
425                                                       &cbArray);
426                             RX_AFS_GLOCK();
427                             XSTATS_END_TIME;
428                         } else
429                             code = -1;
430                         if (!afs_Analyze
431                             (tc, code, 0, &treq,
432                              AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS, SHARED_LOCK,
433                              tsp->cell)) {
434                             break;
435                         }
436                     }
437                     /* ignore return code, since callbacks may have
438                      * been returned anyway, we shouldn't leave them
439                      * around to be returned again.
440                      *
441                      * Next, see if we are done with this server, and if so,
442                      * break to deal with the next one.
443                      */
444                     if (!tsp->cbrs)
445                         break;
446                     tcount = 0;
447                 }
448                 /* if to flush full buffer */
449                 /* if we make it here, we have an entry at the head of cbrs,
450                  * which we should copy to the file ID array and then free.
451                  */
452                 tcbrp = tsp->cbrs;
453                 tfids[tcount++] = tcbrp->fid;
454
455                 /* Freeing the CBR will unlink it from the server's CBR list */
456                 afs_FreeCBR(tcbrp);
457             }                   /* while loop for this one server */
458             if (safety2 > afs_cacheStats) {
459                 afs_warn("possible internal error afs_flushVCBs (%d)\n",
460                          safety2);
461             }
462         }                       /* for loop for this hash chain */
463     }                           /* loop through all hash chains */
464     if (safety1 > afs_totalServers + 2) {
465         afs_warn
466             ("AFS internal error (afs_flushVCBs) (%d > %d), continuing...\n",
467              safety1, afs_totalServers + 2);
468         if (afs_paniconwarn)
469             osi_Panic("afs_flushVCBS safety1");
470     }
471
472     ReleaseReadLock(&afs_xserver);
473     if (lockit)
474         MReleaseWriteLock(&afs_xvcb);
475     afs_osi_Free(tfids, sizeof(struct AFSFid) * AFS_MAXCBRSCALL);
476     return 0;
477 }
478
479 /*!
480  *  Queue a callback on the given fid.
481  *
482  * Environment:
483  *      Locks the xvcb lock.
484  *      Called when the xvcache lock is already held.
485  *
486  * \param avc vcache entry
487  * \return 1 if queued, 0 otherwise
488  */
489
490 static afs_int32
491 afs_QueueVCB(struct vcache *avc)
492 {
493     int queued = 0;
494     struct server *tsp;
495     struct afs_cbr *tcbp;
496
497     AFS_STATCNT(afs_QueueVCB);
498
499     MObtainWriteLock(&afs_xvcb, 274);
500
501     /* we can't really give back callbacks on RO files, since the
502      * server only tracks them on a per-volume basis, and we don't
503      * know whether we still have some other files from the same
504      * volume. */
505     if (!((avc->f.states & CRO) == 0 && avc->callback)) {
506         goto done;
507     }
508
509     /* The callback is really just a struct server ptr. */
510     tsp = (struct server *)(avc->callback);
511
512     /* we now have a pointer to the server, so we just allocate
513      * a queue entry and queue it.
514      */
515     tcbp = afs_AllocCBR();
516     tcbp->fid = avc->f.fid.Fid;
517
518     tcbp->next = tsp->cbrs;
519     if (tsp->cbrs)
520         tsp->cbrs->pprev = &tcbp->next;
521
522     tsp->cbrs = tcbp;
523     tcbp->pprev = &tsp->cbrs;
524
525     afs_InsertHashCBR(tcbp);
526     queued = 1;
527
528  done:
529     /* now release locks and return */
530     MReleaseWriteLock(&afs_xvcb);
531     return queued;
532 }
533
534
535 /*!
536  *   Remove a queued callback for a given Fid.
537  *
538  * Environment:
539  *      Locks xvcb and xserver locks.
540  *      Typically called with xdcache, xvcache and/or individual vcache
541  *      entries locked.
542  *
543  * \param afid The fid we want cleansed of queued callbacks.
544  *
545  */
546
547 void
548 afs_RemoveVCB(struct VenusFid *afid)
549 {
550     int slot;
551     struct afs_cbr *cbr, *ncbr;
552
553     AFS_STATCNT(afs_RemoveVCB);
554     MObtainWriteLock(&afs_xvcb, 275);
555
556     slot = afs_HashCBRFid(&afid->Fid);
557     ncbr = afs_cbrHashT[slot];
558
559     while (ncbr) {
560         cbr = ncbr;
561         ncbr = cbr->hash_next;
562
563         if (afid->Fid.Volume == cbr->fid.Volume &&
564             afid->Fid.Vnode == cbr->fid.Vnode &&
565             afid->Fid.Unique == cbr->fid.Unique) {
566             afs_FreeCBR(cbr);
567         }
568     }
569
570     MReleaseWriteLock(&afs_xvcb);
571 }
572
573 void 
574 afs_FlushReclaimedVcaches(void)
575 {
576 #if !defined(AFS_LINUX22_ENV)
577     struct vcache *tvc;
578     int code, fv_slept;
579     struct vcache *tmpReclaimedVCList = NULL;   
580
581     ObtainWriteLock(&afs_xvreclaim, 76);
582     while (ReclaimedVCList) {
583         tvc = ReclaimedVCList;  /* take from free list */
584         ReclaimedVCList = tvc->nextfree;
585         tvc->nextfree = NULL;
586         code = afs_FlushVCache(tvc, &fv_slept);
587         if (code) {
588             /* Ok, so, if we got code != 0, uh, wtf do we do? */
589             /* Probably, build a temporary list and then put all back when we
590                get to the end of the list */
591             /* This is actually really crappy, but we need to not leak these.
592                We probably need a way to be smarter about this. */
593             tvc->nextfree = tmpReclaimedVCList;
594             tmpReclaimedVCList = tvc;
595             printf("Reclaim list flush %lx failed: %d\n", (unsigned long) tvc, code);
596         }
597         if (tvc->f.states & (CVInit
598 #ifdef AFS_DARWIN80_ENV
599                           | CDeadVnode
600 #endif
601            )) {
602            tvc->f.states &= ~(CVInit
603 #ifdef AFS_DARWIN80_ENV
604                             | CDeadVnode
605 #endif
606            );
607            afs_osi_Wakeup(&tvc->f.states);
608         }
609     }
610     if (tmpReclaimedVCList) 
611         ReclaimedVCList = tmpReclaimedVCList;
612
613     ReleaseWriteLock(&afs_xvreclaim);
614 #endif
615 }
616
617 int
618 afs_ShakeLooseVCaches(afs_int32 anumber)
619 {
620 #if defined(AFS_LINUX22_ENV)
621     afs_int32 i;
622     struct vcache *tvc;
623     struct afs_q *tq, *uq;
624     int code, fv_slept;
625     afs_int32 target = anumber;
626
627     if (afsd_dynamic_vcaches || afs_vcount >= afs_maxvcount) {
628         i = 0;
629         for (tq = VLRU.prev; tq != &VLRU && anumber > 0; tq = uq) {
630             tvc = QTOV(tq);
631             uq = QPrev(tq);
632             if (tvc->f.states & CVFlushed) {
633                 refpanic("CVFlushed on VLRU");
634             } else if (!afsd_dynamic_vcaches && i++ > afs_maxvcount) {
635                 refpanic("Exceeded pool of AFS vnodes(VLRU cycle?)");
636             } else if (QNext(uq) != tq) {
637                 refpanic("VLRU inconsistent");
638             } else if (!VREFCOUNT_GT(tvc,0)) {
639                 refpanic("refcnt 0 on VLRU");
640             }
641
642 #if defined(AFS_LINUX22_ENV)
643             if (tvc != afs_globalVp && VREFCOUNT(tvc) > 1 && tvc->opens == 0) {
644                 struct dentry *dentry;
645                 struct list_head *cur, *head;
646                 AFS_GUNLOCK();
647 #if defined(AFS_LINUX24_ENV)
648                 spin_lock(&dcache_lock);
649 #endif /* AFS_LINUX24_ENV */
650                 head = &(AFSTOV(tvc))->i_dentry;
651
652 restart:
653                 cur = head;
654                 while ((cur = cur->next) != head) {
655                     dentry = list_entry(cur, struct dentry, d_alias);
656
657                     if (d_unhashed(dentry))
658                         continue;
659
660                     dget_locked(dentry);
661
662 #if defined(AFS_LINUX24_ENV)
663                     spin_unlock(&dcache_lock);
664 #endif /* AFS_LINUX24_ENV */
665                     if (d_invalidate(dentry) == -EBUSY) {
666                         dput(dentry);
667                         /* perhaps lock and try to continue? (use cur as head?) */
668                         goto inuse;
669                     }
670                     dput(dentry);
671 #if defined(AFS_LINUX24_ENV)
672                     spin_lock(&dcache_lock);
673 #endif /* AFS_LINUX24_ENV */
674                     goto restart;
675                 }                   
676 #if defined(AFS_LINUX24_ENV)
677                 spin_unlock(&dcache_lock);
678 #endif /* AFS_LINUX24_ENV */
679             inuse:
680                 AFS_GLOCK();
681             }
682 #endif /* AFS_LINUX22_ENV */
683
684             if (VREFCOUNT_GT(tvc,0) && !VREFCOUNT_GT(tvc,1) &&
685                 tvc->opens == 0
686                 && (tvc->f.states & CUnlinkedDel) == 0) {
687                 code = afs_FlushVCache(tvc, &fv_slept);
688                 if (code == 0) {
689                     anumber--;
690                 }
691                 if (fv_slept) {
692                     uq = VLRU.prev;
693                     i = 0;
694                     continue;   /* start over - may have raced. */
695                 }
696             }
697             if (tq == uq)
698                 break;
699         }
700         if (!afsd_dynamic_vcaches && anumber == target) {
701             printf("afs_ShakeLooseVCaches: warning none freed, using %d of %d\n",
702                    afs_vcount, afs_maxvcount);
703         }
704     } /* finished freeing up space */
705 /*
706     printf("recycled %d entries\n", target-anumber);
707 */
708 #endif
709     return 0;
710 }
711
712 /* Alloc new vnode. */
713
714 static struct vcache *
715 afs_AllocVCache(void) 
716 {
717     struct vcache *tvc;
718 #if defined(AFS_LINUX22_ENV)
719     struct inode *ip;
720
721     AFS_GUNLOCK();
722     ip = new_inode(afs_globalVFS);
723     if (!ip)
724         osi_Panic("afs_AllocVCache: no more inodes");
725     AFS_GLOCK();
726 #if defined(STRUCT_SUPER_HAS_ALLOC_INODE)
727     tvc = VTOAFS(ip);
728 #else
729     tvc = afs_osi_Alloc(sizeof(struct vcache));
730     ip->u.generic_ip = tvc;
731     tvc->v = ip;
732 #endif
733
734     afs_vcount++;
735
736     /* track the peak */
737     if (afsd_dynamic_vcaches && afs_maxvcount < afs_vcount) {
738         afs_maxvcount = afs_vcount;
739         /*printf("peak vnodes: %d\n", afs_maxvcount);*/
740     }
741
742     afs_stats_cmperf.vcacheXAllocs++;   /* count in case we have a leak */
743 #else
744     /* none free, making one is better than a panic */
745     afs_stats_cmperf.vcacheXAllocs++;   /* count in case we have a leak */
746     tvc = (struct vcache *)afs_osi_Alloc(sizeof(struct vcache));
747 #if defined(AFS_DARWIN_ENV) && !defined(UKERNEL)
748     tvc->v = NULL; /* important to clean this, or use memset 0 */
749 #endif
750 #ifdef  KERNEL_HAVE_PIN
751     pin((char *)tvc, sizeof(struct vcache));    /* XXX */
752 #endif
753 #if defined(AFS_SGI_ENV)
754     {
755         char name[METER_NAMSZ];
756         memset(tvc, 0, sizeof(struct vcache));
757         tvc->v.v_number = ++afsvnumbers;
758         tvc->vc_rwlockid = OSI_NO_LOCKID;
759         initnsema(&tvc->vc_rwlock, 1,
760                   makesname(name, "vrw", tvc->v.v_number));
761 #ifndef AFS_SGI53_ENV
762         initnsema(&tvc->v.v_sync, 0,
763                   makesname(name, "vsy", tvc->v.v_number));
764 #endif
765 #ifndef AFS_SGI62_ENV
766         initnlock(&tvc->v.v_lock,
767                   makesname(name, "vlk", tvc->v.v_number));
768 #endif
769     }
770 #endif /* AFS_SGI_ENV */
771 #endif
772 #ifdef AFS_DISCON_ENV
773     /* If we create a new inode, we either give it a new slot number,
774      * or if one's available, use a slot number from the slot free list
775      */
776     if (afs_freeSlotList != NULL) {
777        struct afs_slotlist *tmp;
778    
779        tvc->diskSlot = afs_freeSlotList->slot;
780        tmp = afs_freeSlotList;
781        afs_freeSlotList = tmp->next;
782        afs_osi_Free(tmp, sizeof(struct afs_slotlist));
783     }  else {
784        tvc->diskSlot = afs_nextVcacheSlot++;
785     }
786 #endif
787
788     return tvc;
789 }
790
791 /*!
792  *   This routine is responsible for allocating a new cache entry
793  * from the free list.  It formats the cache entry and inserts it
794  * into the appropriate hash tables.  It must be called with
795  * afs_xvcache write-locked so as to prevent several processes from
796  * trying to create a new cache entry simultaneously.
797  *
798  * LOCK: afs_NewVCache  afs_xvcache W
799  *
800  * \param afid The file id of the file whose cache entry is being created.
801  *
802  * \return The new vcache struct.
803  */
804 struct vcache *
805 afs_NewVCache(struct VenusFid *afid, struct server *serverp)
806 {
807     struct vcache *tvc;
808     afs_int32 i, j;
809     afs_int32 anumber = VCACHE_FREE;
810 #ifdef  AFS_AIX_ENV
811     struct gnode *gnodepnt;
812 #endif
813 #if !defined(AFS_LINUX22_ENV)
814     struct afs_q *tq, *uq;
815     int code, fv_slept;
816 #endif
817
818     AFS_STATCNT(afs_NewVCache);
819
820     afs_FlushReclaimedVcaches();
821
822 #if defined(AFS_LINUX22_ENV)
823     if(!afsd_dynamic_vcaches) {
824         afs_ShakeLooseVCaches(anumber);
825         if (afs_vcount >= afs_maxvcount) {
826             printf("afs_NewVCache - none freed\n");
827             return NULL;
828         }
829     }
830     tvc = afs_AllocVCache();
831 #else /* AFS_LINUX22_ENV */
832     /* pull out a free cache entry */
833     if (!freeVCList) {
834         int loop = 0;
835         i = 0;
836         for (tq = VLRU.prev; (anumber > 0) && (tq != &VLRU); tq = uq) {
837             tvc = QTOV(tq);
838             uq = QPrev(tq);
839
840             if (tvc->f.states & CVFlushed) {
841                 refpanic("CVFlushed on VLRU");
842             } else if (i++ > 2 * afs_cacheStats) {      /* even allowing for a few xallocs... */
843                 refpanic("Increase -stat parameter of afsd(VLRU cycle?)");
844             } else if (QNext(uq) != tq) {
845                 refpanic("VLRU inconsistent");
846             } else if (tvc->f.states & CVInit) {
847                 continue;
848             }
849
850            if (!VREFCOUNT_GT(tvc,0)
851 #if defined(AFS_DARWIN_ENV) && !defined(UKERNEL) && !defined(AFS_DARWIN80_ENV)
852                || ((VREFCOUNT(tvc) == 1) && 
853                    (UBCINFOEXISTS(AFSTOV(tvc))))
854 #endif
855                && tvc->opens == 0 && (tvc->f.states & CUnlinkedDel) == 0) {
856 #if defined (AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
857 #ifdef AFS_DARWIN80_ENV
858                 vnode_t tvp = AFSTOV(tvc);
859                 /* VREFCOUNT_GT only sees usecounts, not iocounts */
860                 /* so this may fail to actually recycle the vnode now */
861                 /* must call vnode_get to avoid races. */
862                 fv_slept = 0;
863                 if (vnode_get(tvp) == 0) {
864                     fv_slept=1;
865                     /* must release lock, since vnode_put will immediately
866                        reclaim if there are no other users */
867                     ReleaseWriteLock(&afs_xvcache);
868                     AFS_GUNLOCK();
869                     vnode_recycle(tvp);
870                     vnode_put(tvp);
871                     AFS_GLOCK();
872                     ObtainWriteLock(&afs_xvcache, 336);
873                 }
874                 /* we can't use the vnode_recycle return value to figure
875                  * this out, since the iocount we have to hold makes it
876                  * always "fail" */
877                 if (AFSTOV(tvc) == tvp) {
878                     if (anumber > 0 && fv_slept) {
879                        QRemove(&tvc->vlruq);
880                        QAdd(&VLRU, &tvc->vlruq);
881                     }
882                     code = EBUSY;
883                 } else
884                     code = 0;
885 #else /* AFS_DARWIN80_ENV */
886                 /*
887                  * vgone() reclaims the vnode, which calls afs_FlushVCache(),
888                  * then it puts the vnode on the free list.
889                  * If we don't do this we end up with a cleaned vnode that's
890                  * not on the free list.
891                  * XXX assume FreeBSD is the same for now.
892                  */
893                 AFS_GUNLOCK();
894                 vgone(AFSTOV(tvc));
895                 fv_slept = 0;
896                 code = 0;
897                 AFS_GLOCK();
898 #endif
899 #else /* AFS_DARWIN80_ENV || AFS_XBSD_ENV */
900                 code = afs_FlushVCache(tvc, &fv_slept);
901 #endif /* AFS_DARWIN80_ENV || AFS_XBSD_ENV */
902                 if (code == 0) {
903                     anumber--;
904                 }
905                 if (fv_slept) {
906                     if (loop++ > 100)
907                        break;
908                     uq = VLRU.prev;
909                     i = 0;
910                     continue;   /* start over - may have raced. */
911                 }
912             }
913             if (tq == uq)
914                 break;
915         }
916     } /* end of if (!freeVCList) */
917
918     if (!freeVCList) {
919         tvc = afs_AllocVCache();
920     } else {
921         tvc = freeVCList;       /* take from free list */
922         freeVCList = tvc->nextfree;
923         tvc->nextfree = NULL;
924     } /* end of if (!freeVCList) */
925
926 #endif /* AFS_LINUX22_ENV */
927
928 #if defined(AFS_XBSD_ENV) || defined(AFS_DARWIN_ENV)
929     if (tvc->v)
930         panic("afs_NewVCache(): free vcache with vnode attached");
931 #endif
932
933 #if !defined(AFS_SGI_ENV) && !defined(AFS_LINUX22_ENV)
934
935 #if defined(AFS_DISCON_ENV)
936     /* We need to preserve the slot that we're being stored into on
937      * disk */
938     { 
939         afs_uint32 slot;
940         slot = tvc->diskSlot;
941         memset(tvc, 0, sizeof(struct vcache));
942         tvc->diskSlot = slot;
943     }
944 #else
945     memset(tvc, 0, sizeof(struct vcache));
946 #endif
947
948 #else
949     tvc->uncred = 0;
950     memset(&(tvc->f), 0, sizeof(struct fvcache));
951 #endif
952
953     AFS_RWLOCK_INIT(&tvc->lock, "vcache lock");
954 #if     defined(AFS_SUN5_ENV)
955     AFS_RWLOCK_INIT(&tvc->vlock, "vcache vlock");
956 #endif /* defined(AFS_SUN5_ENV) */
957
958     tvc->mvid = NULL;
959     tvc->linkData = NULL;
960     tvc->cbExpires = 0;
961     tvc->opens = 0;
962     tvc->execsOrWriters = 0;
963     tvc->flockCount = 0;
964     tvc->f.states = CVInit;
965     tvc->last_looker = 0;
966     tvc->f.fid = *afid;
967     tvc->asynchrony = -1;
968     tvc->vc_error = 0;
969 #if defined(AFS_LINUX26_ENV)
970     tvc->cred = NULL;
971 #endif
972 #ifdef AFS_TEXT_ENV
973     tvc->flushDV.low = tvc->flushDV.high = AFS_MAXDV;
974 #endif
975     hzero(tvc->mapDV);
976     tvc->f.truncPos = AFS_NOTRUNC;        /* don't truncate until we need to */
977     hzero(tvc->f.m.DataVersion);  /* in case we copy it into flushDV */
978     tvc->Access = NULL;
979     tvc->callback = serverp;    /* to minimize chance that clear
980                                  * request is lost */
981 #if defined(AFS_DISCON_ENV)
982     QZero(&tvc->metadirty);
983 #endif
984
985     i = VCHash(afid);
986     j = VCHashV(afid);
987
988     tvc->hnext = afs_vhashT[i];
989     afs_vhashT[i] = tvc;
990     QAdd(&afs_vhashTV[j], &tvc->vhashq);
991     
992     if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
993         refpanic("NewVCache VLRU inconsistent");
994     }
995     QAdd(&VLRU, &tvc->vlruq);   /* put in lruq */
996     if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
997         refpanic("NewVCache VLRU inconsistent2");
998     }
999     if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
1000         refpanic("NewVCache VLRU inconsistent3");
1001     }
1002     if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
1003         refpanic("NewVCache VLRU inconsistent4");
1004     }
1005     vcachegen++;
1006     /* it should now be safe to drop the xvcache lock */
1007 #ifdef AFS_OBSD_ENV
1008     ReleaseWriteLock(&afs_xvcache);
1009     AFS_GUNLOCK();
1010     afs_nbsd_getnewvnode(tvc);  /* includes one refcount */
1011     AFS_GLOCK();
1012     ObtainWriteLock(&afs_xvcache,337);
1013     lockinit(&tvc->rwlock, PINOD, "vcache", 0, 0);
1014 #endif
1015 #ifdef AFS_DARWIN_ENV
1016     ReleaseWriteLock(&afs_xvcache);
1017     AFS_GUNLOCK();
1018     afs_darwin_getnewvnode(tvc);        /* includes one refcount */
1019     AFS_GLOCK();
1020     ObtainWriteLock(&afs_xvcache,338);
1021 #ifdef AFS_DARWIN80_ENV
1022     LOCKINIT(tvc->rwlock);
1023 #else
1024     lockinit(&tvc->rwlock, PINOD, "vcache", 0, 0);
1025 #endif
1026 #endif
1027 #ifdef AFS_FBSD_ENV
1028     {
1029         struct vnode *vp;
1030
1031         ReleaseWriteLock(&afs_xvcache);
1032         AFS_GUNLOCK();
1033 #if defined(AFS_FBSD60_ENV)
1034         if (getnewvnode(MOUNT_AFS, afs_globalVFS, &afs_vnodeops, &vp))
1035 #elif defined(AFS_FBSD50_ENV)
1036         if (getnewvnode(MOUNT_AFS, afs_globalVFS, afs_vnodeop_p, &vp))
1037 #else
1038         if (getnewvnode(VT_AFS, afs_globalVFS, afs_vnodeop_p, &vp))
1039 #endif
1040             panic("afs getnewvnode");   /* can't happen */
1041         AFS_GLOCK();
1042         ObtainWriteLock(&afs_xvcache,339);
1043         if (tvc->v != NULL) {
1044             /* I'd like to know if this ever happens...
1045              * We don't drop global for the rest of this function,
1046              * so if we do lose the race, the other thread should
1047              * have found the same vnode and finished initializing
1048              * the vcache entry.  Is it conceivable that this vcache
1049              * entry could be recycled during this interval?  If so,
1050              * then there probably needs to be some sort of additional
1051              * mutual exclusion (an Embryonic flag would suffice).
1052              * -GAW */
1053             printf("afs_NewVCache: lost the race\n");
1054             return (tvc);
1055         }
1056         tvc->v = vp;
1057         tvc->v->v_data = tvc;
1058         lockinit(&tvc->rwlock, PINOD, "vcache", 0, 0);
1059     }
1060 #endif
1061
1062 #if defined(AFS_LINUX22_ENV)
1063     /* Hold it for the LRU (should make count 2) */
1064     VN_HOLD(AFSTOV(tvc));
1065 #elif !(defined (AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV))
1066     VREFCOUNT_SET(tvc, 1);      /* us */
1067 #endif
1068
1069 #ifdef  AFS_AIX32_ENV
1070     LOCK_INIT(&tvc->pvmlock, "vcache pvmlock");
1071     tvc->vmh = tvc->segid = NULL;
1072     tvc->credp = NULL;
1073 #endif
1074
1075 #if defined(AFS_CACHE_BYPASS)
1076     tvc->cachingStates = 0;
1077     tvc->cachingTransitions = 0;
1078 #endif
1079
1080 #ifdef AFS_BOZONLOCK_ENV
1081 #if     defined(AFS_SUN5_ENV)
1082     rw_init(&tvc->rwlock, "vcache rwlock", RW_DEFAULT, NULL);
1083
1084 #if     defined(AFS_SUN55_ENV)
1085     /* This is required if the kaio (kernel aynchronous io)
1086      ** module is installed. Inside the kernel, the function
1087      ** check_vp( common/os/aio.c) checks to see if the kernel has
1088      ** to provide asynchronous io for this vnode. This
1089      ** function extracts the device number by following the
1090      ** v_data field of the vnode. If we do not set this field
1091      ** then the system panics. The  value of the v_data field
1092      ** is not really important for AFS vnodes because the kernel
1093      ** does not do asynchronous io for regular files. Hence,
1094      ** for the time being, we fill up the v_data field with the
1095      ** vnode pointer itself. */
1096     tvc->v.v_data = (char *)tvc;
1097 #endif /* AFS_SUN55_ENV */
1098 #endif
1099     afs_BozonInit(&tvc->pvnLock, tvc);
1100 #endif
1101
1102     /* initialize vnode data, note vrefCount is v.v_count */
1103 #ifdef  AFS_AIX_ENV
1104     /* Don't forget to free the gnode space */
1105     tvc->v.v_gnode = gnodepnt =
1106         (struct gnode *)osi_AllocSmallSpace(sizeof(struct gnode));
1107     memset(gnodepnt, 0, sizeof(struct gnode));
1108 #endif
1109 #ifdef AFS_SGI64_ENV
1110     memset((void *)&(tvc->vc_bhv_desc), 0, sizeof(tvc->vc_bhv_desc));
1111     bhv_desc_init(&(tvc->vc_bhv_desc), tvc, tvc, &Afs_vnodeops);
1112 #ifdef AFS_SGI65_ENV
1113     vn_bhv_head_init(&(tvc->v.v_bh), "afsvp");
1114     vn_bhv_insert_initial(&(tvc->v.v_bh), &(tvc->vc_bhv_desc));
1115 #else
1116     bhv_head_init(&(tvc->v.v_bh));
1117     bhv_insert_initial(&(tvc->v.v_bh), &(tvc->vc_bhv_desc));
1118 #endif
1119 #ifdef AFS_SGI65_ENV
1120     tvc->v.v_mreg = tvc->v.v_mregb = (struct pregion *)tvc;
1121 #ifdef VNODE_TRACING
1122     tvc->v.v_trace = ktrace_alloc(VNODE_TRACE_SIZE, 0);
1123 #endif
1124     init_bitlock(&tvc->v.v_pcacheflag, VNODE_PCACHE_LOCKBIT, "afs_pcache",
1125                  tvc->v.v_number);
1126     init_mutex(&tvc->v.v_filocksem, MUTEX_DEFAULT, "afsvfl", (long)tvc);
1127     init_mutex(&tvc->v.v_buf_lock, MUTEX_DEFAULT, "afsvnbuf", (long)tvc);
1128 #endif
1129     vnode_pcache_init(&tvc->v);
1130 #if defined(DEBUG) && defined(VNODE_INIT_BITLOCK)
1131     /* Above define is never true execpt in SGI test kernels. */
1132     init_bitlock(&(tvc->v.v_flag, VLOCK, "vnode", tvc->v.v_number);
1133 #endif
1134 #ifdef INTR_KTHREADS
1135                  AFS_VN_INIT_BUF_LOCK(&(tvc->v));
1136 #endif
1137 #else
1138     SetAfsVnode(AFSTOV(tvc));
1139 #endif /* AFS_SGI64_ENV */
1140     /*
1141      * The proper value for mvstat (for root fids) is setup by the caller.
1142      */
1143     tvc->mvstat = 0;
1144     if (afid->Fid.Vnode == 1 && afid->Fid.Unique == 1)
1145         tvc->mvstat = 2;
1146     if (afs_globalVFS == 0)
1147         osi_Panic("afs globalvfs");
1148 #if !defined(AFS_LINUX22_ENV)
1149     vSetVfsp(tvc, afs_globalVFS);
1150 #endif
1151     vSetType(tvc, VREG);
1152 #ifdef  AFS_AIX_ENV
1153     tvc->v.v_vfsnext = afs_globalVFS->vfs_vnodes;       /* link off vfs */
1154     tvc->v.v_vfsprev = NULL;
1155     afs_globalVFS->vfs_vnodes = &tvc->v;
1156     if (tvc->v.v_vfsnext != NULL)
1157         tvc->v.v_vfsnext->v_vfsprev = &tvc->v;
1158     tvc->v.v_next = gnodepnt->gn_vnode; /*Single vnode per gnode for us! */
1159     gnodepnt->gn_vnode = &tvc->v;
1160 #endif
1161 #ifdef AFS_FBSD70_ENV
1162 #ifndef AFS_FBSD80_ENV /* yup.  they put it back. */
1163     insmntque(AFSTOV(tvc), afs_globalVFS);
1164 #endif
1165 #endif
1166 #if defined(AFS_SGI_ENV)
1167     VN_SET_DPAGES(&(tvc->v), (struct pfdat *)NULL);
1168     osi_Assert((tvc->v.v_flag & VINACT) == 0);
1169     tvc->v.v_flag = 0;
1170     osi_Assert(VN_GET_PGCNT(&(tvc->v)) == 0);
1171     osi_Assert(tvc->mapcnt == 0 && tvc->vc_locktrips == 0);
1172     osi_Assert(tvc->vc_rwlockid == OSI_NO_LOCKID);
1173     osi_Assert(tvc->v.v_filocks == NULL);
1174 #if !defined(AFS_SGI65_ENV)
1175     osi_Assert(tvc->v.v_filocksem == NULL);
1176 #endif
1177     osi_Assert(tvc->cred == NULL);
1178 #ifdef AFS_SGI64_ENV
1179     vnode_pcache_reinit(&tvc->v);
1180     tvc->v.v_rdev = NODEV;
1181 #endif
1182     vn_initlist((struct vnlist *)&tvc->v);
1183     tvc->lastr = 0;
1184 #endif /* AFS_SGI_ENV */
1185     tvc->dchint = NULL;
1186     osi_dnlc_purgedp(tvc);      /* this may be overkill */
1187     memset(&(tvc->callsort), 0, sizeof(struct afs_q));
1188     tvc->slocks = NULL;
1189     tvc->f.states &=~ CVInit;
1190     afs_osi_Wakeup(&tvc->f.states);
1191
1192     return tvc;
1193
1194 }                               /*afs_NewVCache */
1195
1196
1197 /*!
1198  * ???
1199  *
1200  * LOCK: afs_FlushActiveVcaches afs_xvcache N
1201  *
1202  * \param doflocks : Do we handle flocks?
1203  */
1204 void
1205 afs_FlushActiveVcaches(register afs_int32 doflocks)
1206 {
1207     register struct vcache *tvc;
1208     register int i;
1209     register struct afs_conn *tc;
1210     register afs_int32 code;
1211     afs_ucred_t *cred = NULL;
1212     struct vrequest treq, ureq;
1213     struct AFSVolSync tsync;
1214     int didCore;
1215     XSTATS_DECLS;
1216     AFS_STATCNT(afs_FlushActiveVcaches);
1217     ObtainReadLock(&afs_xvcache);
1218     for (i = 0; i < VCSIZE; i++) {
1219         for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
1220             if (tvc->f.states & CVInit) continue;
1221 #ifdef AFS_DARWIN80_ENV
1222             if (tvc->f.states & CDeadVnode &&
1223                 (tvc->f.states & (CCore|CUnlinkedDel) ||
1224                  tvc->flockCount)) panic("Dead vnode has core/unlinkedel/flock");
1225 #endif
1226             if (doflocks && tvc->flockCount != 0) {
1227                 /* if this entry has an flock, send a keep-alive call out */
1228                 osi_vnhold(tvc, 0);
1229                 ReleaseReadLock(&afs_xvcache);
1230                 ObtainWriteLock(&tvc->lock, 51);
1231                 do {
1232                     afs_InitReq(&treq, afs_osi_credp);
1233                     treq.flags |= O_NONBLOCK;
1234
1235                     tc = afs_Conn(&tvc->f.fid, &treq, SHARED_LOCK);
1236                     if (tc) {
1237                         XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_EXTENDLOCK);
1238                         RX_AFS_GUNLOCK();
1239                         code =
1240                             RXAFS_ExtendLock(tc->id,
1241                                              (struct AFSFid *)&tvc->f.fid.Fid,
1242                                              &tsync);
1243                         RX_AFS_GLOCK();
1244                         XSTATS_END_TIME;
1245                     } else
1246                         code = -1;
1247                 } while (afs_Analyze
1248                          (tc, code, &tvc->f.fid, &treq,
1249                           AFS_STATS_FS_RPCIDX_EXTENDLOCK, SHARED_LOCK, NULL));
1250
1251                 ReleaseWriteLock(&tvc->lock);
1252 #ifdef AFS_DARWIN80_ENV
1253                 AFS_FAST_RELE(tvc);
1254                 ObtainReadLock(&afs_xvcache);
1255 #else
1256                 ObtainReadLock(&afs_xvcache);
1257                 AFS_FAST_RELE(tvc);
1258 #endif
1259             }
1260             didCore = 0;
1261             if ((tvc->f.states & CCore) || (tvc->f.states & CUnlinkedDel)) {
1262                 /*
1263                  * Don't let it evaporate in case someone else is in
1264                  * this code.  Also, drop the afs_xvcache lock while
1265                  * getting vcache locks.
1266                  */
1267                 osi_vnhold(tvc, 0);
1268                 ReleaseReadLock(&afs_xvcache);
1269 #ifdef AFS_BOZONLOCK_ENV
1270                 afs_BozonLock(&tvc->pvnLock, tvc);
1271 #endif
1272 #if defined(AFS_SGI_ENV)
1273                 /*
1274                  * That's because if we come in via the CUnlinkedDel bit state path we'll be have 0 refcnt
1275                  */
1276                 osi_Assert(VREFCOUNT_GT(tvc,0));
1277                 AFS_RWLOCK((vnode_t *) tvc, VRWLOCK_WRITE);
1278 #endif
1279                 ObtainWriteLock(&tvc->lock, 52);
1280                 if (tvc->f.states & CCore) {
1281                     tvc->f.states &= ~CCore;
1282                     /* XXXX Find better place-holder for cred XXXX */
1283                     cred = (afs_ucred_t *)tvc->linkData;
1284                     tvc->linkData = NULL;       /* XXX */
1285                     afs_InitReq(&ureq, cred);
1286                     afs_Trace2(afs_iclSetp, CM_TRACE_ACTCCORE,
1287                                ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32,
1288                                tvc->execsOrWriters);
1289                     code = afs_StoreOnLastReference(tvc, &ureq);
1290                     ReleaseWriteLock(&tvc->lock);
1291 #ifdef AFS_BOZONLOCK_ENV
1292                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1293 #endif
1294                     hzero(tvc->flushDV);
1295                     osi_FlushText(tvc);
1296                     didCore = 1;
1297                     if (code && code != VNOVNODE) {
1298                         afs_StoreWarn(code, tvc->f.fid.Fid.Volume,
1299                                       /* /dev/console */ 1);
1300                     }
1301                 } else if (tvc->f.states & CUnlinkedDel) {
1302                     /*
1303                      * Ignore errors
1304                      */
1305                     ReleaseWriteLock(&tvc->lock);
1306 #ifdef AFS_BOZONLOCK_ENV
1307                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1308 #endif
1309 #if defined(AFS_SGI_ENV)
1310                     AFS_RWUNLOCK((vnode_t *) tvc, VRWLOCK_WRITE);
1311 #endif
1312                     afs_remunlink(tvc, 0);
1313 #if defined(AFS_SGI_ENV)
1314                     AFS_RWLOCK((vnode_t *) tvc, VRWLOCK_WRITE);
1315 #endif
1316                 } else {
1317                     /* lost (or won, perhaps) the race condition */
1318                     ReleaseWriteLock(&tvc->lock);
1319 #ifdef AFS_BOZONLOCK_ENV
1320                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1321 #endif
1322                 }
1323 #if defined(AFS_SGI_ENV)
1324                 AFS_RWUNLOCK((vnode_t *) tvc, VRWLOCK_WRITE);
1325 #endif
1326 #ifdef AFS_DARWIN80_ENV
1327                 AFS_FAST_RELE(tvc);
1328                 if (didCore) {
1329                     AFS_RELE(AFSTOV(tvc));
1330                     /* Matches write code setting CCore flag */
1331                     crfree(cred);
1332                 }
1333                 ObtainReadLock(&afs_xvcache);
1334 #else
1335                 ObtainReadLock(&afs_xvcache);
1336                 AFS_FAST_RELE(tvc);
1337                 if (didCore) {
1338                     AFS_RELE(AFSTOV(tvc));
1339                     /* Matches write code setting CCore flag */
1340                     crfree(cred);
1341                 }
1342 #endif
1343             }
1344         }
1345     }
1346     ReleaseReadLock(&afs_xvcache);
1347 }
1348
1349
1350
1351 /*!
1352  *   Make sure a cache entry is up-to-date status-wise.
1353  *
1354  * NOTE: everywhere that calls this can potentially be sped up
1355  *       by checking CStatd first, and avoiding doing the InitReq
1356  *       if this is up-to-date.
1357  *
1358  *  Anymore, the only places that call this KNOW already that the
1359  *  vcache is not up-to-date, so we don't screw around.
1360  *
1361  * \param avc  : Ptr to vcache entry to verify.
1362  * \param areq : ???
1363  */
1364
1365 /*!
1366  * 
1367  *   Make sure a cache entry is up-to-date status-wise.
1368  *   
1369  *   NOTE: everywhere that calls this can potentially be sped up
1370  *       by checking CStatd first, and avoiding doing the InitReq
1371  *       if this is up-to-date.
1372  *
1373  *   Anymore, the only places that call this KNOW already that the
1374  * vcache is not up-to-date, so we don't screw around.
1375  *
1376  * \param avc Pointer to vcache entry to verify.
1377  * \param areq
1378  *
1379  * \return 0 for success or other error codes.
1380  */
1381 int
1382 afs_VerifyVCache2(struct vcache *avc, struct vrequest *areq)
1383 {
1384     register struct vcache *tvc;
1385
1386     AFS_STATCNT(afs_VerifyVCache);
1387
1388     /* otherwise we must fetch the status info */
1389
1390     ObtainWriteLock(&avc->lock, 53);
1391     if (avc->f.states & CStatd) {
1392         ReleaseWriteLock(&avc->lock);
1393         return 0;
1394     }
1395     ObtainWriteLock(&afs_xcbhash, 461);
1396     avc->f.states &= ~(CStatd | CUnique);
1397     avc->callback = NULL;
1398     afs_DequeueCallback(avc);
1399     ReleaseWriteLock(&afs_xcbhash);
1400     ReleaseWriteLock(&avc->lock);
1401
1402     /* since we've been called back, or the callback has expired,
1403      * it's possible that the contents of this directory, or this
1404      * file's name have changed, thus invalidating the dnlc contents.
1405      */
1406     if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
1407         osi_dnlc_purgedp(avc);
1408     else
1409         osi_dnlc_purgevp(avc);
1410
1411     /* fetch the status info */
1412     tvc = afs_GetVCache(&avc->f.fid, areq, NULL, avc);
1413     if (!tvc)
1414         return ENOENT;
1415     /* Put it back; caller has already incremented vrefCount */
1416     afs_PutVCache(tvc);
1417     return 0;
1418
1419 }                               /*afs_VerifyVCache */
1420
1421
1422 /*!
1423  * Simple copy of stat info into cache.
1424  *
1425  * Callers:as of 1992-04-29, only called by WriteVCache
1426  *
1427  * \param avc   Ptr to vcache entry involved.
1428  * \param astat Ptr to stat info to copy.
1429  *
1430  */
1431 static void
1432 afs_SimpleVStat(register struct vcache *avc,
1433                 register struct AFSFetchStatus *astat, struct vrequest *areq)
1434 {
1435     afs_size_t length;
1436     AFS_STATCNT(afs_SimpleVStat);
1437
1438 #ifdef AFS_SGI_ENV
1439     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)
1440         && !AFS_VN_MAPPED((vnode_t *) avc)) {
1441 #else
1442     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)) {
1443 #endif
1444 #ifdef AFS_64BIT_CLIENT
1445         FillInt64(length, astat->Length_hi, astat->Length);
1446 #else /* AFS_64BIT_CLIENT */
1447         length = astat->Length;
1448 #endif /* AFS_64BIT_CLIENT */
1449 #if defined(AFS_SGI_ENV)
1450         osi_Assert((valusema(&avc->vc_rwlock) <= 0)
1451                    && (OSI_GET_LOCKID() == avc->vc_rwlockid));
1452         if (length < avc->f.m.Length) {
1453             vnode_t *vp = (vnode_t *) avc;
1454
1455             osi_Assert(WriteLocked(&avc->lock));
1456             ReleaseWriteLock(&avc->lock);
1457             AFS_GUNLOCK();
1458             PTOSSVP(vp, (off_t) length, (off_t) MAXLONG);
1459             AFS_GLOCK();
1460             ObtainWriteLock(&avc->lock, 67);
1461         }
1462 #endif
1463         /* if writing the file, don't fetch over this value */
1464         afs_Trace3(afs_iclSetp, CM_TRACE_SIMPLEVSTAT, ICL_TYPE_POINTER, avc,
1465                    ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length),
1466                    ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(length));
1467         avc->f.m.Length = length;
1468         avc->f.m.Date = astat->ClientModTime;
1469     }
1470     avc->f.m.Owner = astat->Owner;
1471     avc->f.m.Group = astat->Group;
1472     avc->f.m.Mode = astat->UnixModeBits;
1473     if (vType(avc) == VREG) {
1474         avc->f.m.Mode |= S_IFREG;
1475     } else if (vType(avc) == VDIR) {
1476         avc->f.m.Mode |= S_IFDIR;
1477     } else if (vType(avc) == VLNK) {
1478         avc->f.m.Mode |= S_IFLNK;
1479         if ((avc->f.m.Mode & 0111) == 0)
1480             avc->mvstat = 1;
1481     }
1482     if (avc->f.states & CForeign) {
1483         struct axscache *ac;
1484         avc->f.anyAccess = astat->AnonymousAccess;
1485 #ifdef badidea
1486         if ((astat->CallerAccess & ~astat->AnonymousAccess))
1487             /*   USED TO SAY :
1488              * Caller has at least one bit not covered by anonymous, and
1489              * thus may have interesting rights.
1490              *
1491              * HOWEVER, this is a really bad idea, because any access query
1492              * for bits which aren't covered by anonymous, on behalf of a user
1493              * who doesn't have any special rights, will result in an answer of
1494              * the form "I don't know, lets make a FetchStatus RPC and find out!"
1495              * It's an especially bad idea under Ultrix, since (due to the lack of
1496              * a proper access() call) it must perform several afs_access() calls
1497              * in order to create magic mode bits that vary according to who makes
1498              * the call.  In other words, _every_ stat() generates a test for
1499              * writeability...
1500              */
1501 #endif /* badidea */
1502             if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
1503                 ac->axess = astat->CallerAccess;
1504             else                /* not found, add a new one if possible */
1505                 afs_AddAxs(avc->Access, areq->uid, astat->CallerAccess);
1506     }
1507
1508 }                               /*afs_SimpleVStat */
1509
1510
1511 /*!
1512  * Store the status info *only* back to the server for a
1513  * fid/vrequest.
1514  *
1515  * Environment: Must be called with a shared lock held on the vnode.
1516  *
1517  * \param avc Ptr to the vcache entry.
1518  * \param astatus Ptr to the status info to store.
1519  * \param areq Ptr to the associated vrequest.
1520  *
1521  * \return Operation status.
1522  */
1523
1524 int
1525 afs_WriteVCache(register struct vcache *avc,
1526                 register struct AFSStoreStatus *astatus,
1527                 struct vrequest *areq)
1528 {
1529     afs_int32 code;
1530     struct afs_conn *tc;
1531     struct AFSFetchStatus OutStatus;
1532     struct AFSVolSync tsync;
1533     XSTATS_DECLS;
1534     AFS_STATCNT(afs_WriteVCache);
1535     afs_Trace2(afs_iclSetp, CM_TRACE_WVCACHE, ICL_TYPE_POINTER, avc,
1536                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1537     do {
1538         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
1539         if (tc) {
1540             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_STORESTATUS);
1541             RX_AFS_GUNLOCK();
1542             code =
1543                 RXAFS_StoreStatus(tc->id, (struct AFSFid *)&avc->f.fid.Fid,
1544                                   astatus, &OutStatus, &tsync);
1545             RX_AFS_GLOCK();
1546             XSTATS_END_TIME;
1547         } else
1548             code = -1;
1549     } while (afs_Analyze
1550              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_STORESTATUS,
1551               SHARED_LOCK, NULL));
1552
1553     UpgradeSToWLock(&avc->lock, 20);
1554     if (code == 0) {
1555         /* success, do the changes locally */
1556         afs_SimpleVStat(avc, &OutStatus, areq);
1557         /*
1558          * Update the date, too.  SimpleVStat didn't do this, since
1559          * it thought we were doing this after fetching new status
1560          * over a file being written.
1561          */
1562         avc->f.m.Date = OutStatus.ClientModTime;
1563     } else {
1564         /* failure, set up to check with server next time */
1565         ObtainWriteLock(&afs_xcbhash, 462);
1566         afs_DequeueCallback(avc);
1567         avc->f.states &= ~(CStatd | CUnique);   /* turn off stat valid flag */
1568         ReleaseWriteLock(&afs_xcbhash);
1569         if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
1570             osi_dnlc_purgedp(avc);      /* if it (could be) a directory */
1571     }
1572     ConvertWToSLock(&avc->lock);
1573     return code;
1574
1575 }                               /*afs_WriteVCache */
1576 #if defined(AFS_DISCON_ENV)
1577
1578 /*!
1579  * Store status info only locally, set the proper disconnection flags
1580  * and add to dirty list.
1581  *
1582  * \param avc The vcache to be written locally.
1583  * \param astatus Get attr fields from local store.
1584  * \param attrs This one is only of the vs_size.
1585  *
1586  * \note Must be called with a shared lock on the vnode
1587  */
1588 int afs_WriteVCacheDiscon(register struct vcache *avc,
1589                                 register struct AFSStoreStatus *astatus,
1590                                 struct vattr *attrs)
1591 {
1592     afs_int32 code = 0;
1593     afs_int32 flags = 0;
1594
1595     UpgradeSToWLock(&avc->lock, 700);
1596
1597     if (!astatus->Mask) {
1598
1599         return code;
1600
1601     } else {
1602
1603         /* Set attributes. */
1604         if (astatus->Mask & AFS_SETMODTIME) {
1605                 avc->f.m.Date = astatus->ClientModTime;
1606                 flags |= VDisconSetTime;
1607         }
1608
1609         if (astatus->Mask & AFS_SETOWNER) {
1610                 printf("Not allowed yet. \n");
1611                 /*avc->f.m.Owner = astatus->Owner;*/
1612         }
1613
1614         if (astatus->Mask & AFS_SETGROUP) {
1615                 printf("Not allowed yet. \n");
1616                 /*avc->f.m.Group =  astatus->Group;*/
1617         }
1618
1619         if (astatus->Mask & AFS_SETMODE) {
1620                 avc->f.m.Mode = astatus->UnixModeBits;
1621
1622 #if 0   /* XXX: Leaving this out, so it doesn't mess up the file type flag.*/
1623
1624                 if (vType(avc) == VREG) {
1625                         avc->f.m.Mode |= S_IFREG;
1626                 } else if (vType(avc) == VDIR) {
1627                         avc->f.m.Mode |= S_IFDIR;
1628                 } else if (vType(avc) == VLNK) {
1629                         avc->f.m.Mode |= S_IFLNK;
1630                         if ((avc->f.m.Mode & 0111) == 0)
1631                                 avc->mvstat = 1;
1632                 }
1633 #endif
1634                 flags |= VDisconSetMode;
1635          }              /* if(astatus.Mask & AFS_SETMODE) */
1636
1637      }                  /* if (!astatus->Mask) */
1638
1639      if (attrs->va_size > 0) {
1640         /* XXX: Do I need more checks? */
1641         /* Truncation operation. */
1642         flags |= VDisconTrunc;
1643      }
1644
1645     if (flags)
1646         afs_DisconAddDirty(avc, flags, 1);
1647
1648     /* XXX: How about the rest of the fields? */
1649
1650     ConvertWToSLock(&avc->lock);
1651
1652     return code;
1653 }
1654
1655 #endif
1656
1657 /*!
1658  * Copy astat block into vcache info
1659  *
1660  * \note This code may get dataversion and length out of sync if the file has
1661  * been modified.  This is less than ideal.  I haven't thought about it sufficiently 
1662  * to be certain that it is adequate.
1663  *
1664  * \note Environment: Must be called under a write lock
1665  *
1666  * \param avc  Ptr to vcache entry.
1667  * \param astat Ptr to stat block to copy in.
1668  * \param areq Ptr to associated request.
1669  */
1670 void
1671 afs_ProcessFS(register struct vcache *avc,
1672               register struct AFSFetchStatus *astat, struct vrequest *areq)
1673 {
1674     afs_size_t length;
1675     AFS_STATCNT(afs_ProcessFS);
1676
1677 #ifdef AFS_64BIT_CLIENT
1678     FillInt64(length, astat->Length_hi, astat->Length);
1679 #else /* AFS_64BIT_CLIENT */
1680     length = astat->Length;
1681 #endif /* AFS_64BIT_CLIENT */
1682     /* WARNING: afs_DoBulkStat uses the Length field to store a sequence
1683      * number for each bulk status request. Under no circumstances
1684      * should afs_DoBulkStat store a sequence number if the new
1685      * length will be ignored when afs_ProcessFS is called with
1686      * new stats. If you change the following conditional then you
1687      * also need to change the conditional in afs_DoBulkStat.  */
1688 #ifdef AFS_SGI_ENV
1689     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)
1690         && !AFS_VN_MAPPED((vnode_t *) avc)) {
1691 #else
1692     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)) {
1693 #endif
1694         /* if we're writing or mapping this file, don't fetch over these
1695          *  values.
1696          */
1697         afs_Trace3(afs_iclSetp, CM_TRACE_PROCESSFS, ICL_TYPE_POINTER, avc,
1698                    ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length),
1699                    ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(length));
1700         avc->f.m.Length = length;
1701         avc->f.m.Date = astat->ClientModTime;
1702     }
1703     hset64(avc->f.m.DataVersion, astat->dataVersionHigh, astat->DataVersion);
1704     avc->f.m.Owner = astat->Owner;
1705     avc->f.m.Mode = astat->UnixModeBits;
1706     avc->f.m.Group = astat->Group;
1707     avc->f.m.LinkCount = astat->LinkCount;
1708     if (astat->FileType == File) {
1709         vSetType(avc, VREG);
1710         avc->f.m.Mode |= S_IFREG;
1711     } else if (astat->FileType == Directory) {
1712         vSetType(avc, VDIR);
1713         avc->f.m.Mode |= S_IFDIR;
1714     } else if (astat->FileType == SymbolicLink) {
1715         if (afs_fakestat_enable && (avc->f.m.Mode & 0111) == 0) {
1716             vSetType(avc, VDIR);
1717             avc->f.m.Mode |= S_IFDIR;
1718         } else {
1719             vSetType(avc, VLNK);
1720             avc->f.m.Mode |= S_IFLNK;
1721         }
1722         if ((avc->f.m.Mode & 0111) == 0) {
1723             avc->mvstat = 1;
1724         }
1725     }
1726     avc->f.anyAccess = astat->AnonymousAccess;
1727 #ifdef badidea
1728     if ((astat->CallerAccess & ~astat->AnonymousAccess))
1729         /*   USED TO SAY :
1730          * Caller has at least one bit not covered by anonymous, and
1731          * thus may have interesting rights.
1732          *
1733          * HOWEVER, this is a really bad idea, because any access query
1734          * for bits which aren't covered by anonymous, on behalf of a user
1735          * who doesn't have any special rights, will result in an answer of
1736          * the form "I don't know, lets make a FetchStatus RPC and find out!"
1737          * It's an especially bad idea under Ultrix, since (due to the lack of
1738          * a proper access() call) it must perform several afs_access() calls
1739          * in order to create magic mode bits that vary according to who makes
1740          * the call.  In other words, _every_ stat() generates a test for
1741          * writeability...
1742          */
1743 #endif /* badidea */
1744     {
1745         struct axscache *ac;
1746         if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
1747             ac->axess = astat->CallerAccess;
1748         else                    /* not found, add a new one if possible */
1749             afs_AddAxs(avc->Access, areq->uid, astat->CallerAccess);
1750     }
1751 }                               /*afs_ProcessFS */
1752
1753
1754 /*!
1755  * Get fid from server.
1756  *
1757  * \param afid 
1758  * \param areq Request to be passed on.
1759  * \param name Name of ?? to lookup.
1760  * \param OutStatus Fetch status.
1761  * \param CallBackp 
1762  * \param serverp
1763  * \param tsyncp
1764  *
1765  * \return Success status of operation.
1766  */
1767 int
1768 afs_RemoteLookup(register struct VenusFid *afid, struct vrequest *areq,
1769                  char *name, struct VenusFid *nfid,
1770                  struct AFSFetchStatus *OutStatusp,
1771                  struct AFSCallBack *CallBackp, struct server **serverp,
1772                  struct AFSVolSync *tsyncp)
1773 {
1774     afs_int32 code;
1775     afs_uint32 start;
1776     register struct afs_conn *tc;
1777     struct AFSFetchStatus OutDirStatus;
1778     XSTATS_DECLS;
1779     if (!name)
1780         name = "";              /* XXX */    
1781     do {
1782         tc = afs_Conn(afid, areq, SHARED_LOCK);
1783         if (tc) {
1784             if (serverp)
1785                 *serverp = tc->srvr->server;
1786             start = osi_Time();
1787             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_XLOOKUP);
1788             RX_AFS_GUNLOCK();
1789             code =
1790                 RXAFS_Lookup(tc->id, (struct AFSFid *)&afid->Fid, name,
1791                              (struct AFSFid *)&nfid->Fid, OutStatusp,
1792                              &OutDirStatus, CallBackp, tsyncp);
1793             RX_AFS_GLOCK();
1794             XSTATS_END_TIME;
1795         } else
1796             code = -1;
1797     } while (afs_Analyze
1798              (tc, code, afid, areq, AFS_STATS_FS_RPCIDX_XLOOKUP, SHARED_LOCK,
1799               NULL));
1800
1801     return code;
1802 }
1803
1804
1805 /*!
1806  * afs_GetVCache
1807  *
1808  * Given a file id and a vrequest structure, fetch the status
1809  * information associated with the file.
1810  *
1811  * \param afid File ID.
1812  * \param areq Ptr to associated vrequest structure, specifying the
1813  *  user whose authentication tokens will be used.
1814  * \param avc Caller may already have a vcache for this file, which is
1815  *  already held.
1816  *
1817  * \note Environment:
1818  *      The cache entry is returned with an increased vrefCount field.
1819  *      The entry must be discarded by calling afs_PutVCache when you
1820  *      are through using the pointer to the cache entry.
1821  *
1822  *      You should not hold any locks when calling this function, except
1823  *      locks on other vcache entries.  If you lock more than one vcache
1824  *      entry simultaneously, you should lock them in this order:
1825  *
1826  *          1. Lock all files first, then directories.
1827  *          2.  Within a particular type, lock entries in Fid.Vnode order.
1828  *
1829  *      This locking hierarchy is convenient because it allows locking
1830  *      of a parent dir cache entry, given a file (to check its access
1831  *      control list).  It also allows renames to be handled easily by
1832  *      locking directories in a constant order.
1833  * 
1834  * \note NB.  NewVCache -> FlushVCache presently (4/10/95) drops the xvcache lock.
1835  *
1836  * \note Might have a vcache structure already, which must
1837  *  already be held by the caller 
1838  */
1839 struct vcache *
1840 afs_GetVCache(register struct VenusFid *afid, struct vrequest *areq,
1841               afs_int32 * cached, struct vcache *avc)
1842 {
1843
1844     afs_int32 code, newvcache = 0;
1845     register struct vcache *tvc;
1846     struct volume *tvp;
1847     afs_int32 retry;
1848
1849     AFS_STATCNT(afs_GetVCache);
1850
1851     if (cached)
1852         *cached = 0;            /* Init just in case */
1853
1854 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
1855   loop:
1856 #endif
1857
1858     ObtainSharedLock(&afs_xvcache, 5);
1859
1860     tvc = afs_FindVCache(afid, &retry, DO_STATS | DO_VLRU | IS_SLOCK);
1861     if (tvc && retry) {
1862 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
1863         ReleaseSharedLock(&afs_xvcache);
1864         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
1865         goto loop;
1866 #endif
1867     }
1868
1869     if (tvc) {
1870         if (cached)
1871             *cached = 1;
1872         osi_Assert((tvc->f.states & CVInit) == 0);
1873         /* If we are in readdir, return the vnode even if not statd */
1874         if ((tvc->f.states & CStatd) || afs_InReadDir(tvc)) {
1875             ReleaseSharedLock(&afs_xvcache);
1876             return tvc;
1877         }
1878     } else {
1879         UpgradeSToWLock(&afs_xvcache, 21);
1880
1881         /* no cache entry, better grab one */
1882         tvc = afs_NewVCache(afid, NULL);
1883         newvcache = 1;
1884
1885         ConvertWToSLock(&afs_xvcache);
1886         if (tvc == NULL)
1887         {
1888                 ReleaseSharedLock(&afs_xvcache);
1889                 return NULL;
1890         }
1891
1892         afs_stats_cmperf.vcacheMisses++;
1893     }
1894
1895     ReleaseSharedLock(&afs_xvcache);
1896
1897     ObtainWriteLock(&tvc->lock, 54);
1898
1899     if (tvc->f.states & CStatd) {
1900         ReleaseWriteLock(&tvc->lock);
1901         return tvc;
1902     }
1903 #ifdef AFS_DARWIN80_ENV
1904 /* Darwin 8.0 only has bufs in nfs, so we shouldn't have to worry about them.
1905    What about ubc? */
1906 #else
1907 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
1908     /*
1909      * XXX - I really don't like this.  Should try to understand better.
1910      * It seems that sometimes, when we get called, we already hold the
1911      * lock on the vnode (e.g., from afs_getattr via afs_VerifyVCache).
1912      * We can't drop the vnode lock, because that could result in a race.
1913      * Sometimes, though, we get here and don't hold the vnode lock.
1914      * I hate code paths that sometimes hold locks and sometimes don't.
1915      * In any event, the dodge we use here is to check whether the vnode
1916      * is locked, and if it isn't, then we gain and drop it around the call
1917      * to vinvalbuf; otherwise, we leave it alone.
1918      */
1919     {
1920         struct vnode *vp = AFSTOV(tvc);
1921         int iheldthelock;
1922
1923 #if defined(AFS_DARWIN_ENV)
1924         iheldthelock = VOP_ISLOCKED(vp);
1925         if (!iheldthelock)
1926             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, current_proc());
1927         /* this is messy. we can call fsync which will try to reobtain this */
1928         if (VTOAFS(vp) == tvc) 
1929           ReleaseWriteLock(&tvc->lock);
1930         if (UBCINFOEXISTS(vp)) {
1931           vinvalbuf(vp, V_SAVE, &afs_osi_cred, current_proc(), PINOD, 0);
1932         }
1933         if (VTOAFS(vp) == tvc) 
1934           ObtainWriteLock(&tvc->lock, 954);
1935         if (!iheldthelock)
1936             VOP_UNLOCK(vp, LK_EXCLUSIVE, current_proc());
1937 #elif defined(AFS_FBSD80_ENV)
1938         iheldthelock = VOP_ISLOCKED(vp);
1939         if (!iheldthelock) {
1940             /* nosleep/sleep lock order reversal */
1941             int glocked = ISAFS_GLOCK();
1942             if (glocked)
1943                 AFS_GUNLOCK();
1944             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1945             if (glocked)
1946                 AFS_GLOCK();
1947         }
1948         vinvalbuf(vp, V_SAVE, curthread, PINOD, 0);
1949         if (!iheldthelock)
1950             VOP_UNLOCK(vp, 0);
1951 #elif defined(AFS_FBSD60_ENV)
1952         iheldthelock = VOP_ISLOCKED(vp, curthread);
1953         if (!iheldthelock)
1954             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
1955         vinvalbuf(vp, V_SAVE, curthread, PINOD, 0);
1956         if (!iheldthelock)
1957             VOP_UNLOCK(vp, LK_EXCLUSIVE, curthread);
1958 #elif defined(AFS_FBSD50_ENV)
1959         iheldthelock = VOP_ISLOCKED(vp, curthread);
1960         if (!iheldthelock)
1961             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
1962         vinvalbuf(vp, V_SAVE, osi_curcred(), curthread, PINOD, 0);
1963         if (!iheldthelock)
1964             VOP_UNLOCK(vp, LK_EXCLUSIVE, curthread);
1965 #elif defined(AFS_FBSD40_ENV)
1966         iheldthelock = VOP_ISLOCKED(vp, curproc);
1967         if (!iheldthelock)
1968             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curproc);
1969         vinvalbuf(vp, V_SAVE, osi_curcred(), curproc, PINOD, 0);
1970         if (!iheldthelock)
1971             VOP_UNLOCK(vp, LK_EXCLUSIVE, curproc);
1972 #elif defined(AFS_OBSD_ENV)
1973         iheldthelock = VOP_ISLOCKED(vp, curproc);
1974         if (!iheldthelock)
1975             VOP_LOCK(vp, LK_EXCLUSIVE | LK_RETRY, curproc);
1976         uvm_vnp_uncache(vp);
1977         if (!iheldthelock)
1978             VOP_UNLOCK(vp, 0, curproc);
1979 #endif
1980     }
1981 #endif
1982 #endif
1983
1984     ObtainWriteLock(&afs_xcbhash, 464);
1985     tvc->f.states &= ~CUnique;
1986     tvc->callback = 0;
1987     afs_DequeueCallback(tvc);
1988     ReleaseWriteLock(&afs_xcbhash);
1989
1990     /* It is always appropriate to throw away all the access rights? */
1991     afs_FreeAllAxs(&(tvc->Access));
1992     tvp = afs_GetVolume(afid, areq, READ_LOCK); /* copy useful per-volume info */
1993     if (tvp) {
1994         if ((tvp->states & VForeign)) {
1995             if (newvcache)
1996                 tvc->f.states |= CForeign;
1997             if (newvcache && (tvp->rootVnode == afid->Fid.Vnode)
1998                 && (tvp->rootUnique == afid->Fid.Unique)) {
1999                 tvc->mvstat = 2;
2000             }
2001         }
2002         if (tvp->states & VRO)
2003             tvc->f.states |= CRO;
2004         if (tvp->states & VBackup)
2005             tvc->f.states |= CBackup;
2006         /* now copy ".." entry back out of volume structure, if necessary */
2007         if (tvc->mvstat == 2 && tvp->dotdot.Fid.Volume != 0) {
2008             if (!tvc->mvid)
2009                 tvc->mvid = (struct VenusFid *)
2010                     osi_AllocSmallSpace(sizeof(struct VenusFid));
2011             *tvc->mvid = tvp->dotdot;
2012         }
2013         afs_PutVolume(tvp, READ_LOCK);
2014     }
2015
2016     /* stat the file */
2017     afs_RemoveVCB(afid);
2018     {
2019         struct AFSFetchStatus OutStatus;
2020
2021         if (afs_DynrootNewVnode(tvc, &OutStatus)) {
2022             afs_ProcessFS(tvc, &OutStatus, areq);
2023             tvc->f.states |= CStatd | CUnique;
2024             tvc->f.parent.vnode  = OutStatus.ParentVnode;
2025             tvc->f.parent.unique = OutStatus.ParentUnique;
2026             code = 0;
2027         } else {
2028
2029             if (AFS_IS_DISCONNECTED) {
2030                 /* Nothing to do otherwise...*/
2031                 code = ENETDOWN;
2032                 printf("Network is down in afs_GetCache");
2033             } else
2034                 code = afs_FetchStatus(tvc, afid, areq, &OutStatus);
2035
2036             /* For the NFS translator's benefit, make sure
2037              * non-directory vnodes always have their parent FID set
2038              * correctly, even when created as a result of decoding an
2039              * NFS filehandle.  It would be nice to also do this for
2040              * directories, but we can't because the fileserver fills
2041              * in the FID of the directory itself instead of that of
2042              * its parent.
2043              */
2044             if (!code && OutStatus.FileType != Directory &&
2045                 !tvc->f.parent.vnode) {
2046                 tvc->f.parent.vnode  = OutStatus.ParentVnode;
2047                 tvc->f.parent.unique = OutStatus.ParentUnique;
2048                 /* XXX - SXW - It's conceivable we should mark ourselves
2049                  *             as dirty again here, incase we've been raced
2050                  *             out of the FetchStatus call.
2051                  */
2052             }
2053         }
2054     }
2055
2056     if (code) {
2057         ReleaseWriteLock(&tvc->lock);
2058
2059         afs_PutVCache(tvc);
2060         return NULL;
2061     }
2062
2063     ReleaseWriteLock(&tvc->lock);
2064     return tvc;
2065
2066 }                               /*afs_GetVCache */
2067
2068
2069
2070 /*!
2071  * Lookup a vcache by fid. Look inside the cache first, if not
2072  * there, lookup the file on the server, and then get it's fresh
2073  * cache entry.
2074  * 
2075  * \param afid
2076  * \param areq 
2077  * \param cached Is element cached? If NULL, don't answer.
2078  * \param adp
2079  * \param aname
2080  *
2081  * \return The found element or NULL.
2082  */
2083 struct vcache *
2084 afs_LookupVCache(struct VenusFid *afid, struct vrequest *areq,
2085                  afs_int32 * cached, struct vcache *adp, char *aname)
2086 {
2087     afs_int32 code, now, newvcache = 0;
2088     struct VenusFid nfid;
2089     register struct vcache *tvc;
2090     struct volume *tvp;
2091     struct AFSFetchStatus OutStatus;
2092     struct AFSCallBack CallBack;
2093     struct AFSVolSync tsync;
2094     struct server *serverp = 0;
2095     afs_int32 origCBs;
2096     afs_int32 retry;
2097
2098     AFS_STATCNT(afs_GetVCache);
2099     if (cached)
2100         *cached = 0;            /* Init just in case */
2101
2102 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2103   loop1:
2104 #endif
2105
2106     ObtainReadLock(&afs_xvcache);
2107     tvc = afs_FindVCache(afid, &retry, DO_STATS /* no vlru */ );
2108
2109     if (tvc) {
2110         ReleaseReadLock(&afs_xvcache);
2111         if (retry) {
2112 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2113             spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
2114             goto loop1;
2115 #endif
2116         }
2117         ObtainReadLock(&tvc->lock);
2118
2119         if (tvc->f.states & CStatd) {
2120             if (cached) {
2121                 *cached = 1;
2122             }
2123             ReleaseReadLock(&tvc->lock);
2124             return tvc;
2125         }
2126         tvc->f.states &= ~CUnique;
2127
2128         ReleaseReadLock(&tvc->lock);
2129         afs_PutVCache(tvc);
2130         ObtainReadLock(&afs_xvcache);
2131     }
2132     /* if (tvc) */
2133     ReleaseReadLock(&afs_xvcache);
2134
2135     /* lookup the file */
2136     nfid = *afid;
2137     now = osi_Time();
2138     origCBs = afs_allCBs;       /* if anything changes, we don't have a cb */
2139     
2140     if (AFS_IS_DISCONNECTED) {
2141         printf("Network is down in afs_LookupVcache\n");
2142         code = ENETDOWN;
2143     } else 
2144         code =
2145             afs_RemoteLookup(&adp->f.fid, areq, aname, &nfid, &OutStatus, 
2146                              &CallBack, &serverp, &tsync);
2147
2148 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2149   loop2:
2150 #endif
2151
2152     ObtainSharedLock(&afs_xvcache, 6);
2153     tvc = afs_FindVCache(&nfid, &retry, DO_VLRU | IS_SLOCK/* no xstats now */ );
2154     if (tvc && retry) {
2155 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2156         ReleaseSharedLock(&afs_xvcache);
2157         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
2158         goto loop2;
2159 #endif
2160     }
2161
2162     if (!tvc) {
2163         /* no cache entry, better grab one */
2164         UpgradeSToWLock(&afs_xvcache, 22);
2165         tvc = afs_NewVCache(&nfid, serverp);
2166         newvcache = 1;
2167         ConvertWToSLock(&afs_xvcache);
2168         if (!tvc)
2169         {
2170                 ReleaseSharedLock(&afs_xvcache);
2171                 return NULL;
2172         }
2173     }
2174
2175     ReleaseSharedLock(&afs_xvcache);
2176     ObtainWriteLock(&tvc->lock, 55);
2177
2178     /* It is always appropriate to throw away all the access rights? */
2179     afs_FreeAllAxs(&(tvc->Access));
2180     tvp = afs_GetVolume(afid, areq, READ_LOCK); /* copy useful per-vol info */
2181     if (tvp) {
2182         if ((tvp->states & VForeign)) {
2183             if (newvcache)
2184                 tvc->f.states |= CForeign;
2185             if (newvcache && (tvp->rootVnode == afid->Fid.Vnode)
2186                 && (tvp->rootUnique == afid->Fid.Unique))
2187                 tvc->mvstat = 2;
2188         }
2189         if (tvp->states & VRO)
2190             tvc->f.states |= CRO;
2191         if (tvp->states & VBackup)
2192             tvc->f.states |= CBackup;
2193         /* now copy ".." entry back out of volume structure, if necessary */
2194         if (tvc->mvstat == 2 && tvp->dotdot.Fid.Volume != 0) {
2195             if (!tvc->mvid)
2196                 tvc->mvid = (struct VenusFid *)
2197                     osi_AllocSmallSpace(sizeof(struct VenusFid));
2198             *tvc->mvid = tvp->dotdot;
2199         }
2200     }
2201
2202     if (code) {
2203         ObtainWriteLock(&afs_xcbhash, 465);
2204         afs_DequeueCallback(tvc);
2205         tvc->f.states &= ~(CStatd | CUnique);
2206         ReleaseWriteLock(&afs_xcbhash);
2207         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2208             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2209         if (tvp)
2210             afs_PutVolume(tvp, READ_LOCK);
2211         ReleaseWriteLock(&tvc->lock);
2212         afs_PutVCache(tvc);
2213         return NULL;
2214     }
2215
2216     ObtainWriteLock(&afs_xcbhash, 466);
2217     if (origCBs == afs_allCBs) {
2218         if (CallBack.ExpirationTime) {
2219             tvc->callback = serverp;
2220             tvc->cbExpires = CallBack.ExpirationTime + now;
2221             tvc->f.states |= CStatd | CUnique;
2222             tvc->f.states &= ~CBulkFetching;
2223             afs_QueueCallback(tvc, CBHash(CallBack.ExpirationTime), tvp);
2224         } else if (tvc->f.states & CRO) {
2225             /* adapt gives us an hour. */
2226             tvc->cbExpires = 3600 + osi_Time();
2227              /*XXX*/ tvc->f.states |= CStatd | CUnique;
2228             tvc->f.states &= ~CBulkFetching;
2229             afs_QueueCallback(tvc, CBHash(3600), tvp);
2230         } else {
2231             tvc->callback = NULL;
2232             afs_DequeueCallback(tvc);
2233             tvc->f.states &= ~(CStatd | CUnique);
2234             if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2235                 osi_dnlc_purgedp(tvc);  /* if it (could be) a directory */
2236         }
2237     } else {
2238         afs_DequeueCallback(tvc);
2239         tvc->f.states &= ~CStatd;
2240         tvc->f.states &= ~CUnique;
2241         tvc->callback = NULL;
2242         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2243             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2244     }
2245     ReleaseWriteLock(&afs_xcbhash);
2246     if (tvp)
2247         afs_PutVolume(tvp, READ_LOCK);
2248     afs_ProcessFS(tvc, &OutStatus, areq);
2249
2250     ReleaseWriteLock(&tvc->lock);
2251     return tvc;
2252
2253 }
2254
2255 struct vcache *
2256 afs_GetRootVCache(struct VenusFid *afid, struct vrequest *areq,
2257                   afs_int32 * cached, struct volume *tvolp)
2258 {
2259     afs_int32 code = 0, i, newvcache = 0, haveStatus = 0;
2260     afs_int32 getNewFid = 0;
2261     afs_uint32 start;
2262     struct VenusFid nfid;
2263     register struct vcache *tvc;
2264     struct server *serverp = 0;
2265     struct AFSFetchStatus OutStatus;
2266     struct AFSCallBack CallBack;
2267     struct AFSVolSync tsync;
2268     int origCBs = 0;
2269 #ifdef AFS_DARWIN80_ENV
2270     vnode_t tvp;
2271 #endif
2272
2273     start = osi_Time();
2274
2275   newmtpt:
2276     if (!tvolp->rootVnode || getNewFid) {
2277         struct VenusFid tfid;
2278
2279         tfid = *afid;
2280         tfid.Fid.Vnode = 0;     /* Means get rootfid of volume */
2281         origCBs = afs_allCBs;   /* ignore InitCallBackState */
2282         code =
2283             afs_RemoteLookup(&tfid, areq, NULL, &nfid, &OutStatus, &CallBack,
2284                              &serverp, &tsync);
2285         if (code) {
2286             return NULL;
2287         }
2288 /*      ReleaseReadLock(&tvolp->lock);           */
2289         ObtainWriteLock(&tvolp->lock, 56);
2290         tvolp->rootVnode = afid->Fid.Vnode = nfid.Fid.Vnode;
2291         tvolp->rootUnique = afid->Fid.Unique = nfid.Fid.Unique;
2292         ReleaseWriteLock(&tvolp->lock);
2293 /*      ObtainReadLock(&tvolp->lock);*/
2294         haveStatus = 1;
2295     } else {
2296         afid->Fid.Vnode = tvolp->rootVnode;
2297         afid->Fid.Unique = tvolp->rootUnique;
2298     }
2299
2300  rootvc_loop:
2301     ObtainSharedLock(&afs_xvcache, 7);
2302     i = VCHash(afid);
2303     for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2304         if (!FidCmp(&(tvc->f.fid), afid)) {
2305             if (tvc->f.states & CVInit) {
2306                 ReleaseSharedLock(&afs_xvcache);
2307                 afs_osi_Sleep(&tvc->f.states);
2308                 goto rootvc_loop;
2309             }
2310 #ifdef AFS_DARWIN80_ENV
2311             if (tvc->f.states & CDeadVnode) {
2312                 ReleaseSharedLock(&afs_xvcache);
2313                 afs_osi_Sleep(&tvc->f.states);
2314                 goto rootvc_loop;
2315             }
2316             tvp = AFSTOV(tvc);
2317             if (vnode_get(tvp))       /* this bumps ref count */
2318                 continue;
2319             if (vnode_ref(tvp)) {
2320                 AFS_GUNLOCK();
2321                 /* AFSTOV(tvc) may be NULL */
2322                 vnode_put(tvp);
2323                 AFS_GLOCK();
2324                 continue;
2325             }
2326 #endif
2327             break;
2328         }
2329     }
2330
2331     if (!haveStatus && (!tvc || !(tvc->f.states & CStatd))) {
2332         /* Mount point no longer stat'd or unknown. FID may have changed. */
2333         getNewFid = 1;
2334         ReleaseSharedLock(&afs_xvcache);
2335 #ifdef AFS_DARWIN80_ENV
2336         if (tvc) {
2337             AFS_GUNLOCK();
2338             vnode_put(AFSTOV(tvc));
2339             vnode_rele(AFSTOV(tvc));
2340             AFS_GLOCK();
2341         }
2342 #endif
2343         tvc = NULL;
2344         goto newmtpt;
2345     }
2346
2347     if (!tvc) {
2348         UpgradeSToWLock(&afs_xvcache, 23);
2349         /* no cache entry, better grab one */
2350         tvc = afs_NewVCache(afid, NULL);
2351         if (!tvc)
2352         {
2353                 ReleaseWriteLock(&afs_xvcache);
2354                 return NULL;
2355         }
2356         newvcache = 1;
2357         afs_stats_cmperf.vcacheMisses++;
2358     } else {
2359         if (cached)
2360             *cached = 1;
2361         afs_stats_cmperf.vcacheHits++;
2362 #if     defined(AFS_DARWIN80_ENV)
2363         /* we already bumped the ref count in the for loop above */
2364 #else /* AFS_DARWIN80_ENV */
2365         osi_vnhold(tvc, 0);
2366 #endif
2367         UpgradeSToWLock(&afs_xvcache, 24);
2368         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2369             refpanic("GRVC VLRU inconsistent0");
2370         }
2371         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2372             refpanic("GRVC VLRU inconsistent1");
2373         }
2374         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2375             refpanic("GRVC VLRU inconsistent2");
2376         }
2377         QRemove(&tvc->vlruq);   /* move to lruq head */
2378         QAdd(&VLRU, &tvc->vlruq);
2379         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2380             refpanic("GRVC VLRU inconsistent3");
2381         }
2382         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2383             refpanic("GRVC VLRU inconsistent4");
2384         }
2385         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2386             refpanic("GRVC VLRU inconsistent5");
2387         }
2388         vcachegen++;
2389     }
2390
2391     ReleaseWriteLock(&afs_xvcache);
2392
2393     if (tvc->f.states & CStatd) {
2394         return tvc;
2395     } else {
2396
2397         ObtainReadLock(&tvc->lock);
2398         tvc->f.states &= ~CUnique;
2399         tvc->callback = NULL;   /* redundant, perhaps */
2400         ReleaseReadLock(&tvc->lock);
2401     }
2402
2403     ObtainWriteLock(&tvc->lock, 57);
2404
2405     /* It is always appropriate to throw away all the access rights? */
2406     afs_FreeAllAxs(&(tvc->Access));
2407
2408     if (newvcache)
2409         tvc->f.states |= CForeign;
2410     if (tvolp->states & VRO)
2411         tvc->f.states |= CRO;
2412     if (tvolp->states & VBackup)
2413         tvc->f.states |= CBackup;
2414     /* now copy ".." entry back out of volume structure, if necessary */
2415     if (newvcache && (tvolp->rootVnode == afid->Fid.Vnode)
2416         && (tvolp->rootUnique == afid->Fid.Unique)) {
2417         tvc->mvstat = 2;
2418     }
2419     if (tvc->mvstat == 2 && tvolp->dotdot.Fid.Volume != 0) {
2420         if (!tvc->mvid)
2421             tvc->mvid = (struct VenusFid *)
2422                 osi_AllocSmallSpace(sizeof(struct VenusFid));
2423         *tvc->mvid = tvolp->dotdot;
2424     }
2425
2426     /* stat the file */
2427     afs_RemoveVCB(afid);
2428
2429     if (!haveStatus) {
2430         struct VenusFid tfid;
2431
2432         tfid = *afid;
2433         tfid.Fid.Vnode = 0;     /* Means get rootfid of volume */
2434         origCBs = afs_allCBs;   /* ignore InitCallBackState */
2435         code =
2436             afs_RemoteLookup(&tfid, areq, NULL, &nfid, &OutStatus, &CallBack,
2437                              &serverp, &tsync);
2438     }
2439
2440     if (code) {
2441         ObtainWriteLock(&afs_xcbhash, 467);
2442         afs_DequeueCallback(tvc);
2443         tvc->callback = NULL;
2444         tvc->f.states &= ~(CStatd | CUnique);
2445         ReleaseWriteLock(&afs_xcbhash);
2446         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2447             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2448         ReleaseWriteLock(&tvc->lock);
2449         afs_PutVCache(tvc);
2450         return NULL;
2451     }
2452
2453     ObtainWriteLock(&afs_xcbhash, 468);
2454     if (origCBs == afs_allCBs) {
2455         tvc->f.states |= CTruth;
2456         tvc->callback = serverp;
2457         if (CallBack.ExpirationTime != 0) {
2458             tvc->cbExpires = CallBack.ExpirationTime + start;
2459             tvc->f.states |= CStatd;
2460             tvc->f.states &= ~CBulkFetching;
2461             afs_QueueCallback(tvc, CBHash(CallBack.ExpirationTime), tvolp);
2462         } else if (tvc->f.states & CRO) {
2463             /* adapt gives us an hour. */
2464             tvc->cbExpires = 3600 + osi_Time();
2465              /*XXX*/ tvc->f.states |= CStatd;
2466             tvc->f.states &= ~CBulkFetching;
2467             afs_QueueCallback(tvc, CBHash(3600), tvolp);
2468         }
2469     } else {
2470         afs_DequeueCallback(tvc);
2471         tvc->callback = NULL;
2472         tvc->f.states &= ~(CStatd | CUnique);
2473         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2474             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2475     }
2476     ReleaseWriteLock(&afs_xcbhash);
2477     afs_ProcessFS(tvc, &OutStatus, areq);
2478
2479     ReleaseWriteLock(&tvc->lock);
2480     return tvc;
2481 }
2482
2483
2484 /*!
2485  * Update callback status and (sometimes) attributes of a vnode.
2486  * Called after doing a fetch status RPC. Whilst disconnected, attributes
2487  * shouldn't be written to the vcache here.
2488  *
2489  * \param avc
2490  * \param afid
2491  * \param areq
2492  * \param Outsp Server status after rpc call.
2493  * \param acb Callback for this vnode.
2494  *
2495  * \note The vcache must be write locked.
2496  */
2497 void
2498 afs_UpdateStatus(struct vcache *avc,
2499                         struct VenusFid *afid,
2500                         struct vrequest *areq,
2501                         struct AFSFetchStatus *Outsp,
2502                         struct AFSCallBack *acb,
2503                         afs_uint32 start)
2504 {
2505     struct volume *volp;
2506
2507     if (!AFS_IN_SYNC)
2508         /* Dont write status in vcache if resyncing after a disconnection. */
2509         afs_ProcessFS(avc, Outsp, areq);
2510
2511     volp = afs_GetVolume(afid, areq, READ_LOCK);
2512     ObtainWriteLock(&afs_xcbhash, 469);
2513     avc->f.states |= CTruth;
2514     if (avc->callback /* check for race */ ) {
2515         if (acb->ExpirationTime != 0) {
2516             avc->cbExpires = acb->ExpirationTime + start;
2517             avc->f.states |= CStatd;
2518             avc->f.states &= ~CBulkFetching;
2519             afs_QueueCallback(avc, CBHash(acb->ExpirationTime), volp);
2520         } else if (avc->f.states & CRO) {
2521             /* ordinary callback on a read-only volume -- AFS 3.2 style */
2522             avc->cbExpires = 3600 + start;
2523             avc->f.states |= CStatd;
2524             avc->f.states &= ~CBulkFetching;
2525             afs_QueueCallback(avc, CBHash(3600), volp);
2526         } else {
2527             afs_DequeueCallback(avc);
2528             avc->callback = NULL;
2529             avc->f.states &= ~(CStatd | CUnique);
2530             if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
2531                 osi_dnlc_purgedp(avc);  /* if it (could be) a directory */
2532         }
2533     } else {
2534         afs_DequeueCallback(avc);
2535         avc->callback = NULL;
2536         avc->f.states &= ~(CStatd | CUnique);
2537         if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
2538             osi_dnlc_purgedp(avc);      /* if it (could be) a directory */
2539     }
2540     ReleaseWriteLock(&afs_xcbhash);
2541     if (volp)
2542         afs_PutVolume(volp, READ_LOCK);
2543 }
2544
2545 /*!
2546  * Must be called with avc write-locked
2547  * don't absolutely have to invalidate the hint unless the dv has
2548  * changed, but be sure to get it right else there will be consistency bugs.
2549  */
2550 afs_int32
2551 afs_FetchStatus(struct vcache * avc, struct VenusFid * afid,
2552                 struct vrequest * areq, struct AFSFetchStatus * Outsp)
2553 {
2554     int code;
2555     afs_uint32 start = 0;
2556     register struct afs_conn *tc;
2557     struct AFSCallBack CallBack;
2558     struct AFSVolSync tsync;
2559     XSTATS_DECLS;
2560     do {
2561         tc = afs_Conn(afid, areq, SHARED_LOCK);
2562         avc->dchint = NULL;     /* invalidate hints */
2563         if (tc) {
2564             avc->callback = tc->srvr->server;
2565             start = osi_Time();
2566             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHSTATUS);
2567             RX_AFS_GUNLOCK();
2568             code =
2569                 RXAFS_FetchStatus(tc->id, (struct AFSFid *)&afid->Fid, Outsp,
2570                                   &CallBack, &tsync);
2571             RX_AFS_GLOCK();
2572
2573             XSTATS_END_TIME;
2574
2575         } else
2576             code = -1;
2577     } while (afs_Analyze
2578              (tc, code, afid, areq, AFS_STATS_FS_RPCIDX_FETCHSTATUS,
2579               SHARED_LOCK, NULL));
2580
2581     if (!code) {
2582         afs_UpdateStatus(avc, afid, areq, Outsp, &CallBack, start);
2583     } else {
2584         /* used to undo the local callback, but that's too extreme.
2585          * There are plenty of good reasons that fetchstatus might return
2586          * an error, such as EPERM.  If we have the vnode cached, statd,
2587          * with callback, might as well keep track of the fact that we
2588          * don't have access...
2589          */
2590         if (code == EPERM || code == EACCES) {
2591             struct axscache *ac;
2592             if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
2593                 ac->axess = 0;
2594             else                /* not found, add a new one if possible */
2595                 afs_AddAxs(avc->Access, areq->uid, 0);
2596         }
2597     }
2598     return code;
2599 }
2600
2601 #if 0
2602 /*
2603  * afs_StuffVcache
2604  *
2605  * Description:
2606  *      Stuff some information into the vcache for the given file.
2607  *
2608  * Parameters:
2609  *      afid      : File in question.
2610  *      OutStatus : Fetch status on the file.
2611  *      CallBack  : Callback info.
2612  *      tc        : RPC connection involved.
2613  *      areq      : vrequest involved.
2614  *
2615  * Environment:
2616  *      Nothing interesting.
2617  */
2618 void
2619 afs_StuffVcache(register struct VenusFid *afid,
2620                 struct AFSFetchStatus *OutStatus,
2621                 struct AFSCallBack *CallBack, register struct afs_conn *tc,
2622                 struct vrequest *areq)
2623 {
2624     register afs_int32 code, i, newvcache = 0;
2625     register struct vcache *tvc;
2626     struct AFSVolSync tsync;
2627     struct volume *tvp;
2628     struct axscache *ac;
2629     afs_int32 retry;
2630
2631     AFS_STATCNT(afs_StuffVcache);
2632 #ifdef IFS_VCACHECOUNT
2633     ifs_gvcachecall++;
2634 #endif
2635
2636   loop:
2637     ObtainSharedLock(&afs_xvcache, 8);
2638
2639     tvc = afs_FindVCache(afid, &retry, DO_VLRU| IS_SLOCK /* no stats */ );
2640     if (tvc && retry) {
2641 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2642         ReleaseSharedLock(&afs_xvcache);
2643         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
2644         goto loop;
2645 #endif
2646     }
2647
2648     if (!tvc) {
2649         /* no cache entry, better grab one */
2650         UpgradeSToWLock(&afs_xvcache, 25);
2651         tvc = afs_NewVCache(afid, NULL);
2652         newvcache = 1;
2653         ConvertWToSLock(&afs_xvcache);
2654         if (!tvc)
2655         {
2656                 ReleaseSharedLock(&afs_xvcache);
2657                 return NULL;
2658         }
2659     }
2660
2661     ReleaseSharedLock(&afs_xvcache);
2662     ObtainWriteLock(&tvc->lock, 58);
2663
2664     tvc->f.states &= ~CStatd;
2665     if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2666         osi_dnlc_purgedp(tvc);  /* if it (could be) a directory */
2667
2668     /* Is it always appropriate to throw away all the access rights? */
2669     afs_FreeAllAxs(&(tvc->Access));
2670
2671     /*Copy useful per-volume info */
2672     tvp = afs_GetVolume(afid, areq, READ_LOCK);
2673     if (tvp) {
2674         if (newvcache && (tvp->states & VForeign))
2675             tvc->f.states |= CForeign;
2676         if (tvp->states & VRO)
2677             tvc->f.states |= CRO;
2678         if (tvp->states & VBackup)
2679             tvc->f.states |= CBackup;
2680         /*
2681          * Now, copy ".." entry back out of volume structure, if
2682          * necessary
2683          */
2684         if (tvc->mvstat == 2 && tvp->dotdot.Fid.Volume != 0) {
2685             if (!tvc->mvid)
2686                 tvc->mvid = (struct VenusFid *)
2687                     osi_AllocSmallSpace(sizeof(struct VenusFid));
2688             *tvc->mvid = tvp->dotdot;
2689         }
2690     }
2691     /* store the stat on the file */
2692     afs_RemoveVCB(afid);
2693     afs_ProcessFS(tvc, OutStatus, areq);
2694     tvc->callback = tc->srvr->server;
2695
2696     /* we use osi_Time twice below.  Ideally, we would use the time at which
2697      * the FetchStatus call began, instead, but we don't have it here.  So we
2698      * make do with "now".  In the CRO case, it doesn't really matter. In
2699      * the other case, we hope that the difference between "now" and when the
2700      * call actually began execution on the server won't be larger than the
2701      * padding which the server keeps.  Subtract 1 second anyway, to be on
2702      * the safe side.  Can't subtract more because we don't know how big
2703      * ExpirationTime is.  Possible consistency problems may arise if the call
2704      * timeout period becomes longer than the server's expiration padding.  */
2705     ObtainWriteLock(&afs_xcbhash, 470);
2706     if (CallBack->ExpirationTime != 0) {
2707         tvc->cbExpires = CallBack->ExpirationTime + osi_Time() - 1;
2708         tvc->f.states |= CStatd;
2709         tvc->f.states &= ~CBulkFetching;
2710         afs_QueueCallback(tvc, CBHash(CallBack->ExpirationTime), tvp);
2711     } else if (tvc->f.states & CRO) {
2712         /* old-fashioned AFS 3.2 style */
2713         tvc->cbExpires = 3600 + osi_Time();
2714          /*XXX*/ tvc->f.states |= CStatd;
2715         tvc->f.states &= ~CBulkFetching;
2716         afs_QueueCallback(tvc, CBHash(3600), tvp);
2717     } else {
2718         afs_DequeueCallback(tvc);
2719         tvc->callback = NULL;
2720         tvc->f.states &= ~(CStatd | CUnique);
2721         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2722             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2723     }
2724     ReleaseWriteLock(&afs_xcbhash);
2725     if (tvp)
2726         afs_PutVolume(tvp, READ_LOCK);
2727
2728     /* look in per-pag cache */
2729     if (tvc->Access && (ac = afs_FindAxs(tvc->Access, areq->uid)))
2730         ac->axess = OutStatus->CallerAccess;    /* substitute pags */
2731     else                        /* not found, add a new one if possible */
2732         afs_AddAxs(tvc->Access, areq->uid, OutStatus->CallerAccess);
2733
2734     ReleaseWriteLock(&tvc->lock);
2735     afs_Trace4(afs_iclSetp, CM_TRACE_STUFFVCACHE, ICL_TYPE_POINTER, tvc,
2736                ICL_TYPE_POINTER, tvc->callback, ICL_TYPE_INT32,
2737                tvc->cbExpires, ICL_TYPE_INT32, tvc->cbExpires - osi_Time());
2738     /*
2739      * Release ref count... hope this guy stays around...
2740      */
2741     afs_PutVCache(tvc);
2742 }                               /*afs_StuffVcache */
2743 #endif
2744
2745 /*!
2746  * Decrements the reference count on a cache entry.
2747  *
2748  * \param avc Pointer to the cache entry to decrement.
2749  *
2750  * \note Environment: Nothing interesting.
2751  */
2752 void
2753 afs_PutVCache(register struct vcache *avc)
2754 {
2755     AFS_STATCNT(afs_PutVCache);
2756 #ifdef AFS_DARWIN80_ENV
2757     vnode_put(AFSTOV(avc));
2758     AFS_FAST_RELE(avc);
2759 #else
2760     /*
2761      * Can we use a read lock here?
2762      */
2763     ObtainReadLock(&afs_xvcache);
2764     AFS_FAST_RELE(avc);
2765     ReleaseReadLock(&afs_xvcache);
2766 #endif
2767 }                               /*afs_PutVCache */
2768
2769
2770 /*!
2771  * Reset a vcache entry, so local contents are ignored, and the
2772  * server will be reconsulted next time the vcache is used
2773  * 
2774  * \param avc Pointer to the cache entry to reset
2775  * \param acred 
2776  *
2777  * \note avc must be write locked on entry
2778  */
2779 void
2780 afs_ResetVCache(struct vcache *avc, afs_ucred_t *acred) {
2781     ObtainWriteLock(&afs_xcbhash, 456);
2782     afs_DequeueCallback(avc);
2783     avc->f.states &= ~(CStatd | CDirty);    /* next reference will re-stat */
2784     ReleaseWriteLock(&afs_xcbhash);
2785     /* now find the disk cache entries */
2786     afs_TryToSmush(avc, acred, 1);
2787     osi_dnlc_purgedp(avc);
2788     if (avc->linkData && !(avc->f.states & CCore)) {
2789         afs_osi_Free(avc->linkData, strlen(avc->linkData) + 1);
2790         avc->linkData = NULL;
2791     }
2792 }
2793
2794 /*!
2795  * Sleepa when searching for a vcache. Releases all the pending locks,
2796  * sleeps then obtains the previously released locks.
2797  *
2798  * \param vcache Enter sleep state.
2799  * \param flag Determines what locks to use.
2800  *
2801  * \return 
2802  */
2803 static void findvc_sleep(struct vcache *avc, int flag) {
2804     if (flag & IS_SLOCK) {
2805             ReleaseSharedLock(&afs_xvcache);
2806     } else {
2807         if (flag & IS_WLOCK) {
2808             ReleaseWriteLock(&afs_xvcache);
2809         } else {
2810             ReleaseReadLock(&afs_xvcache);
2811         }
2812     }
2813     afs_osi_Sleep(&avc->f.states);
2814     if (flag & IS_SLOCK) {
2815             ObtainSharedLock(&afs_xvcache, 341);
2816     } else {
2817         if (flag & IS_WLOCK) {
2818             ObtainWriteLock(&afs_xvcache, 343);
2819         } else {
2820             ObtainReadLock(&afs_xvcache);
2821         }
2822     }
2823 }
2824 /*!
2825  * Find a vcache entry given a fid.
2826  *
2827  * \param afid Pointer to the fid whose cache entry we desire.
2828  * \param retry (SGI-specific) tell the caller to drop the lock on xvcache,
2829  *  unlock the vnode, and try again.
2830  * \param flag Bit 1 to specify whether to compute hit statistics.  Not
2831  *  set if FindVCache is called as part of internal bookkeeping.
2832  *
2833  * \note Environment: Must be called with the afs_xvcache lock at least held at
2834  * the read level.  In order to do the VLRU adjustment, the xvcache lock
2835  * must be shared-- we upgrade it here.
2836  */
2837
2838 struct vcache *
2839 afs_FindVCache(struct VenusFid *afid, afs_int32 * retry, afs_int32 flag)
2840 {
2841
2842     register struct vcache *tvc;
2843     afs_int32 i;
2844 #ifdef AFS_DARWIN80_ENV
2845     vnode_t tvp;
2846 #endif
2847
2848     AFS_STATCNT(afs_FindVCache);
2849
2850  findloop:
2851     i = VCHash(afid);
2852     for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2853         if (FidMatches(afid, tvc)) {
2854             if (tvc->f.states & CVInit) {
2855                 findvc_sleep(tvc, flag);
2856                 goto findloop;
2857             }
2858 #ifdef  AFS_DARWIN80_ENV
2859             if (tvc->f.states & CDeadVnode) {
2860                 findvc_sleep(tvc, flag);
2861                 goto findloop;
2862             }
2863             tvp = AFSTOV(tvc);
2864             if (vnode_get(tvp))
2865                 continue;
2866             if (vnode_ref(tvp)) {
2867                 AFS_GUNLOCK();
2868                 /* AFSTOV(tvc) may be NULL */
2869                 vnode_put(tvp);
2870                 AFS_GLOCK();
2871                 continue;
2872             }
2873 #endif
2874             break;
2875         }
2876     }
2877
2878     /* should I have a read lock on the vnode here? */
2879     if (tvc) {
2880         if (retry)
2881             *retry = 0;
2882 #if !defined(AFS_DARWIN80_ENV)
2883         osi_vnhold(tvc, retry); /* already held, above */
2884         if (retry && *retry)
2885             return 0;
2886 #endif
2887 #if defined(AFS_DARWIN_ENV) && !defined(AFS_DARWIN80_ENV)
2888         tvc->f.states |= CUBCinit;
2889         AFS_GUNLOCK();
2890         if (UBCINFOMISSING(AFSTOV(tvc)) ||
2891             UBCINFORECLAIMED(AFSTOV(tvc))) {
2892           ubc_info_init(AFSTOV(tvc));
2893         }
2894         AFS_GLOCK();
2895         tvc->f.states &= ~CUBCinit;
2896 #endif
2897         /*
2898          * only move to front of vlru if we have proper vcache locking)
2899          */
2900         if (flag & DO_VLRU) {
2901             if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2902                 refpanic("FindVC VLRU inconsistent1");
2903             }
2904             if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2905                 refpanic("FindVC VLRU inconsistent1");
2906             }
2907             if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2908                 refpanic("FindVC VLRU inconsistent2");
2909             }
2910             UpgradeSToWLock(&afs_xvcache, 26);
2911             QRemove(&tvc->vlruq);
2912             QAdd(&VLRU, &tvc->vlruq);
2913             ConvertWToSLock(&afs_xvcache);
2914             if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2915                 refpanic("FindVC VLRU inconsistent1");
2916             }
2917             if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2918                 refpanic("FindVC VLRU inconsistent2");
2919             }
2920             if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2921                 refpanic("FindVC VLRU inconsistent3");
2922             }
2923         }
2924         vcachegen++;
2925     }
2926
2927     if (flag & DO_STATS) {
2928         if (tvc)
2929             afs_stats_cmperf.vcacheHits++;
2930         else
2931             afs_stats_cmperf.vcacheMisses++;
2932         if (afs_IsPrimaryCellNum(afid->Cell))
2933             afs_stats_cmperf.vlocalAccesses++;
2934         else
2935             afs_stats_cmperf.vremoteAccesses++;
2936     }
2937     return tvc;
2938 }                               /*afs_FindVCache */
2939
2940 /*!
2941  * Find a vcache entry given a fid. Does a wildcard match on what we
2942  * have for the fid. If more than one entry, don't return anything.
2943  *
2944  * \param avcp Fill in pointer if we found one and only one.
2945  * \param afid Pointer to the fid whose cache entry we desire.
2946  * \param retry (SGI-specific) tell the caller to drop the lock on xvcache,
2947  *             unlock the vnode, and try again.
2948  * \param flags bit 1 to specify whether to compute hit statistics.  Not
2949  *             set if FindVCache is called as part of internal bookkeeping.
2950  *
2951  * \note Environment: Must be called with the afs_xvcache lock at least held at
2952  *  the read level.  In order to do the VLRU adjustment, the xvcache lock
2953  *  must be shared-- we upgrade it here.
2954  *
2955  * \return Number of matches found.
2956  */
2957
2958 int afs_duplicate_nfs_fids = 0;
2959
2960 afs_int32
2961 afs_NFSFindVCache(struct vcache **avcp, struct VenusFid *afid)
2962 {
2963     register struct vcache *tvc;
2964     afs_int32 i;
2965     afs_int32 count = 0;
2966     struct vcache *found_tvc = NULL;
2967 #ifdef AFS_DARWIN80_ENV
2968     vnode_t tvp;
2969 #endif
2970
2971     AFS_STATCNT(afs_FindVCache);
2972
2973   loop:
2974
2975     ObtainSharedLock(&afs_xvcache, 331);
2976
2977     i = VCHash(afid);
2978     for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2979         /* Match only on what we have.... */
2980         if (((tvc->f.fid.Fid.Vnode & 0xffff) == afid->Fid.Vnode)
2981             && (tvc->f.fid.Fid.Volume == afid->Fid.Volume)
2982             && ((tvc->f.fid.Fid.Unique & 0xffffff) == afid->Fid.Unique)
2983             && (tvc->f.fid.Cell == afid->Cell)) {
2984             if (tvc->f.states & CVInit) {
2985                 ReleaseSharedLock(&afs_xvcache);
2986                 afs_osi_Sleep(&tvc->f.states);
2987                 goto loop;
2988             }
2989 #ifdef  AFS_DARWIN80_ENV
2990             if (tvc->f.states & CDeadVnode) {
2991                 ReleaseSharedLock(&afs_xvcache);
2992                 afs_osi_Sleep(&tvc->f.states);
2993                 goto loop;
2994             }
2995             tvp = AFSTOV(tvc);
2996             if (vnode_get(tvp)) {
2997                 /* This vnode no longer exists. */
2998                 continue;
2999             }
3000             if (vnode_ref(tvp)) {
3001                 /* This vnode no longer exists. */
3002                 AFS_GUNLOCK();
3003                 /* AFSTOV(tvc) may be NULL */
3004                 vnode_put(tvp);
3005                 AFS_GLOCK();
3006                 continue;
3007             }
3008 #endif /* AFS_DARWIN80_ENV */
3009             count++;
3010             if (found_tvc) {
3011                 /* Duplicates */
3012                 afs_duplicate_nfs_fids++;
3013                 ReleaseSharedLock(&afs_xvcache);
3014 #ifdef AFS_DARWIN80_ENV
3015                 /* Drop our reference counts. */
3016                 vnode_put(AFSTOV(tvc));
3017                 vnode_put(AFSTOV(found_tvc));
3018 #endif
3019                 return count;
3020             }
3021             found_tvc = tvc;
3022         }
3023     }
3024
3025     tvc = found_tvc;
3026     /* should I have a read lock on the vnode here? */
3027     if (tvc) {
3028 #if defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
3029         afs_int32 retry = 0;
3030         osi_vnhold(tvc, &retry);
3031         if (retry) {
3032             count = 0;
3033             found_tvc = (struct vcache *)0;
3034             ReleaseSharedLock(&afs_xvcache);
3035             spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
3036             goto loop;
3037         }
3038 #else
3039         osi_vnhold(tvc, (int *)0);      /* already held, above */
3040 #endif
3041         /*
3042          * We obtained the xvcache lock above.
3043          */
3044         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
3045             refpanic("FindVC VLRU inconsistent1");
3046         }
3047         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
3048             refpanic("FindVC VLRU inconsistent1");
3049         }
3050         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
3051             refpanic("FindVC VLRU inconsistent2");
3052         }
3053         UpgradeSToWLock(&afs_xvcache, 568);
3054         QRemove(&tvc->vlruq);
3055         QAdd(&VLRU, &tvc->vlruq);
3056         ConvertWToSLock(&afs_xvcache);
3057         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
3058             refpanic("FindVC VLRU inconsistent1");
3059         }
3060         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
3061             refpanic("FindVC VLRU inconsistent2");
3062         }
3063         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
3064             refpanic("FindVC VLRU inconsistent3");
3065         }
3066     }
3067     vcachegen++;
3068
3069     if (tvc)
3070         afs_stats_cmperf.vcacheHits++;
3071     else
3072         afs_stats_cmperf.vcacheMisses++;
3073     if (afs_IsPrimaryCellNum(afid->Cell))
3074         afs_stats_cmperf.vlocalAccesses++;
3075     else
3076         afs_stats_cmperf.vremoteAccesses++;
3077
3078     *avcp = tvc;                /* May be null */
3079
3080     ReleaseSharedLock(&afs_xvcache);
3081     return (tvc ? 1 : 0);
3082
3083 }                               /*afs_NFSFindVCache */
3084
3085
3086
3087
3088 /*!
3089  * Initialize vcache related variables
3090  *
3091  * \param astatSize
3092  */
3093 void
3094 afs_vcacheInit(int astatSize)
3095 {
3096 #if !defined(AFS_LINUX22_ENV)
3097     register struct vcache *tvp;
3098 #endif
3099     int i;
3100 #if defined(AFS_LINUX22_ENV)
3101     if (!afs_maxvcount) {
3102         afs_maxvcount = astatSize;      /* no particular limit on linux? */
3103         if (astatSize < afs_maxvcount) {
3104             afs_maxvcount = astatSize;
3105         }
3106     }
3107 #else /* AFS_LINUX22_ENV */
3108     freeVCList = NULL;
3109 #endif
3110
3111     AFS_RWLOCK_INIT(&afs_xvcache, "afs_xvcache");
3112     LOCK_INIT(&afs_xvcb, "afs_xvcb");
3113
3114 #if !defined(AFS_LINUX22_ENV)
3115     /* Allocate and thread the struct vcache entries */
3116     tvp = (struct vcache *)afs_osi_Alloc(astatSize * sizeof(struct vcache));
3117     memset(tvp, 0, sizeof(struct vcache) * astatSize);
3118
3119     Initial_freeVCList = tvp;
3120     freeVCList = &(tvp[0]);
3121     for (i = 0; i < astatSize - 1; i++) {
3122         tvp[i].nextfree = &(tvp[i + 1]);
3123     }
3124     tvp[astatSize - 1].nextfree = NULL;
3125 # ifdef  KERNEL_HAVE_PIN
3126     pin((char *)tvp, astatSize * sizeof(struct vcache));        /* XXX */
3127 # endif
3128 #endif
3129
3130 #if defined(AFS_SGI_ENV)
3131     for (i = 0; i < astatSize; i++) {
3132         char name[METER_NAMSZ];
3133         struct vcache *tvc = &tvp[i];
3134
3135         tvc->v.v_number = ++afsvnumbers;
3136         tvc->vc_rwlockid = OSI_NO_LOCKID;
3137         initnsema(&tvc->vc_rwlock, 1,
3138                   makesname(name, "vrw", tvc->v.v_number));
3139 #ifndef AFS_SGI53_ENV
3140         initnsema(&tvc->v.v_sync, 0, makesname(name, "vsy", tvc->v.v_number));
3141 #endif
3142 #ifndef AFS_SGI62_ENV
3143         initnlock(&tvc->v.v_lock, makesname(name, "vlk", tvc->v.v_number));
3144 #endif /* AFS_SGI62_ENV */
3145     }
3146 #endif
3147     QInit(&VLRU);
3148     for(i = 0; i < VCSIZE; ++i)
3149         QInit(&afs_vhashTV[i]);
3150 }
3151
3152 /*!
3153  * Shutdown vcache.
3154  */
3155 void
3156 shutdown_vcache(void)
3157 {
3158     int i;
3159     struct afs_cbr *tsp;
3160     /*
3161      * XXX We may potentially miss some of the vcaches because if when
3162      * there are no free vcache entries and all the vcache entries are active
3163      * ones then we allocate an additional one - admittedly we almost never
3164      * had that occur.
3165      */
3166
3167     {
3168         register struct afs_q *tq, *uq = NULL;
3169         register struct vcache *tvc;
3170         for (tq = VLRU.prev; tq != &VLRU; tq = uq) {
3171             tvc = QTOV(tq);
3172             uq = QPrev(tq);
3173             if (tvc->mvid) {
3174                 osi_FreeSmallSpace(tvc->mvid);
3175                 tvc->mvid = (struct VenusFid *)0;
3176             }
3177 #ifdef  AFS_AIX_ENV
3178             aix_gnode_rele(AFSTOV(tvc));
3179 #endif
3180             if (tvc->linkData) {
3181                 afs_osi_Free(tvc->linkData, strlen(tvc->linkData) + 1);
3182                 tvc->linkData = 0;
3183             }
3184         }
3185         /*
3186          * Also free the remaining ones in the Cache
3187          */
3188         for (i = 0; i < VCSIZE; i++) {
3189             for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
3190                 if (tvc->mvid) {
3191                     osi_FreeSmallSpace(tvc->mvid);
3192                     tvc->mvid = (struct VenusFid *)0;
3193                 }
3194 #ifdef  AFS_AIX_ENV
3195                 if (tvc->v.v_gnode)
3196                     afs_osi_Free(tvc->v.v_gnode, sizeof(struct gnode));
3197 #ifdef  AFS_AIX32_ENV
3198                 if (tvc->segid) {
3199                     AFS_GUNLOCK();
3200                     vms_delete(tvc->segid);
3201                     AFS_GLOCK();
3202                     tvc->segid = tvc->vmh = NULL;
3203                     if (VREFCOUNT_GT(tvc,0))
3204                         osi_Panic("flushVcache: vm race");
3205                 }
3206                 if (tvc->credp) {
3207                     crfree(tvc->credp);
3208                     tvc->credp = NULL;
3209                 }
3210 #endif
3211 #endif
3212 #if     defined(AFS_SUN5_ENV)
3213                 if (tvc->credp) {
3214                     crfree(tvc->credp);
3215                     tvc->credp = NULL;
3216                 }
3217 #endif
3218                 if (tvc->linkData) {
3219                     afs_osi_Free(tvc->linkData, strlen(tvc->linkData) + 1);
3220                     tvc->linkData = 0;
3221                 }
3222
3223                 if (tvc->Access)
3224                     afs_FreeAllAxs(&(tvc->Access));
3225             }
3226             afs_vhashT[i] = 0;
3227         }
3228     }
3229     /*
3230      * Free any leftover callback queue
3231      */
3232     for (i = 0; i < afs_stats_cmperf.CallBackAlloced; i++) {
3233         tsp = afs_cbrHeads[i];
3234         afs_cbrHeads[i] = 0;
3235         afs_osi_Free((char *)tsp, AFS_NCBRS * sizeof(struct afs_cbr));
3236     }
3237     afs_cbrSpace = 0;
3238
3239 #if !defined(AFS_LINUX22_ENV)
3240     afs_osi_Free(Initial_freeVCList, afs_cacheStats * sizeof(struct vcache));
3241
3242 # ifdef  KERNEL_HAVE_PIN
3243     unpin(Initial_freeVCList, afs_cacheStats * sizeof(struct vcache));
3244 # endif
3245
3246     freeVCList = Initial_freeVCList = 0;
3247 #endif
3248
3249     AFS_RWLOCK_INIT(&afs_xvcache, "afs_xvcache");
3250     LOCK_INIT(&afs_xvcb, "afs_xvcb");
3251     QInit(&VLRU);
3252     for(i = 0; i < VCSIZE; ++i)
3253         QInit(&afs_vhashTV[i]);
3254 }
3255
3256 void
3257 afs_DisconGiveUpCallbacks(void) {
3258     int i;
3259     struct vcache *tvc;
3260     int nq=0;
3261             
3262     ObtainWriteLock(&afs_xvcache, 1002); /* XXX - should be a unique number */
3263     
3264     /* Somehow, walk the set of vcaches, with each one coming out as tvc */
3265     for (i = 0; i < VCSIZE; i++) {
3266         for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
3267             if (afs_QueueVCB(tvc)) {
3268                 tvc->callback = NULL;
3269                 nq++;
3270             }
3271         }
3272     }
3273
3274     ReleaseWriteLock(&afs_xvcache);
3275
3276     afs_FlushVCBs(1);
3277 }
3278
3279 /*!
3280  *
3281  * Clear the Statd flag from all vcaches
3282  *
3283  * This function removes the Statd flag from all vcaches. It's used by 
3284  * disconnected mode to tidy up during reconnection
3285  *
3286  */
3287 void
3288 afs_ClearAllStatdFlag(void) {
3289     int i;
3290     struct vcache *tvc;
3291    
3292     ObtainWriteLock(&afs_xvcache, 715);
3293
3294     for (i = 0; i < VCSIZE; i++) {
3295         for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
3296             tvc->f.states &= ~(CStatd|CUnique);
3297         }
3298     }
3299     ReleaseWriteLock(&afs_xvcache);
3300 }