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