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