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