3c5b3ed34f9fcd45c3712ecfd634d3cc5ea914d9
[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             printf("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             printf("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_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(UKERNEL)
746     tvc->v = NULL; /* important to clean this, or use memset 0 */
747 #endif
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 struct vcache *
803 afs_NewVCache(struct VenusFid *afid, struct server *serverp)
804 {
805     struct vcache *tvc;
806     afs_int32 i, j;
807     afs_int32 anumber = VCACHE_FREE;
808 #ifdef  AFS_AIX_ENV
809     struct gnode *gnodepnt;
810 #endif
811 #if !defined(AFS_LINUX22_ENV)
812     struct afs_q *tq, *uq;
813     int code, fv_slept;
814 #endif
815
816     AFS_STATCNT(afs_NewVCache);
817
818     afs_FlushReclaimedVcaches();
819
820 #if defined(AFS_LINUX22_ENV)
821     if(!afsd_dynamic_vcaches) {
822         afs_ShakeLooseVCaches(anumber);
823         if (afs_vcount >= afs_maxvcount) {
824             printf("afs_NewVCache - none freed\n");
825             return NULL;
826         }
827     }
828     tvc = afs_AllocVCache();
829 #else /* AFS_LINUX22_ENV */
830     /* pull out a free cache entry */
831     if (!freeVCList) {
832         int loop = 0;
833         i = 0;
834         for (tq = VLRU.prev; (anumber > 0) && (tq != &VLRU); tq = uq) {
835             tvc = QTOV(tq);
836             uq = QPrev(tq);
837
838             if (tvc->f.states & CVFlushed) {
839                 refpanic("CVFlushed on VLRU");
840             } else if (i++ > 2 * afs_cacheStats) {      /* even allowing for a few xallocs... */
841                 refpanic("Increase -stat parameter of afsd(VLRU cycle?)");
842             } else if (QNext(uq) != tq) {
843                 refpanic("VLRU inconsistent");
844             } else if (tvc->f.states & CVInit) {
845                 continue;
846             }
847
848            if (!VREFCOUNT_GT(tvc,0)
849 #if defined(AFS_DARWIN_ENV) && !defined(UKERNEL) && !defined(AFS_DARWIN80_ENV)
850                || ((VREFCOUNT(tvc) == 1) && 
851                    (UBCINFOEXISTS(AFSTOV(tvc))))
852 #endif
853                && tvc->opens == 0 && (tvc->f.states & CUnlinkedDel) == 0) {
854 #if defined (AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
855 #ifdef AFS_DARWIN80_ENV
856                 vnode_t tvp = AFSTOV(tvc);
857                 /* VREFCOUNT_GT only sees usecounts, not iocounts */
858                 /* so this may fail to actually recycle the vnode now */
859                 /* must call vnode_get to avoid races. */
860                 fv_slept = 0;
861                 if (vnode_get(tvp) == 0) {
862                     fv_slept=1;
863                     /* must release lock, since vnode_put will immediately
864                        reclaim if there are no other users */
865                     ReleaseWriteLock(&afs_xvcache);
866                     AFS_GUNLOCK();
867                     vnode_recycle(tvp);
868                     vnode_put(tvp);
869                     AFS_GLOCK();
870                     ObtainWriteLock(&afs_xvcache, 336);
871                 }
872                 /* we can't use the vnode_recycle return value to figure
873                  * this out, since the iocount we have to hold makes it
874                  * always "fail" */
875                 if (AFSTOV(tvc) == tvp) {
876                     if (anumber > 0 && fv_slept) {
877                        QRemove(&tvc->vlruq);
878                        QAdd(&VLRU, &tvc->vlruq);
879                     }
880                     code = EBUSY;
881                 } else
882                     code = 0;
883 #else /* AFS_DARWIN80_ENV */
884                 /*
885                  * vgone() reclaims the vnode, which calls afs_FlushVCache(),
886                  * then it puts the vnode on the free list.
887                  * If we don't do this we end up with a cleaned vnode that's
888                  * not on the free list.
889                  * XXX assume FreeBSD is the same for now.
890                  */
891                 AFS_GUNLOCK();
892                 vgone(AFSTOV(tvc));
893                 fv_slept = 0;
894                 code = 0;
895                 AFS_GLOCK();
896 #endif
897 #else /* AFS_DARWIN80_ENV || AFS_XBSD_ENV */
898                 code = afs_FlushVCache(tvc, &fv_slept);
899 #endif /* AFS_DARWIN80_ENV || AFS_XBSD_ENV */
900                 if (code == 0) {
901                     anumber--;
902                 }
903                 if (fv_slept) {
904                     if (loop++ > 100)
905                        break;
906                     uq = VLRU.prev;
907                     i = 0;
908                     continue;   /* start over - may have raced. */
909                 }
910             }
911             if (tq == uq)
912                 break;
913         }
914     } /* end of if (!freeVCList) */
915
916     if (!freeVCList) {
917         tvc = afs_AllocVCache();
918     } else {
919         tvc = freeVCList;       /* take from free list */
920         freeVCList = tvc->nextfree;
921         tvc->nextfree = NULL;
922     } /* end of if (!freeVCList) */
923
924 #endif /* AFS_LINUX22_ENV */
925
926 #if defined(AFS_XBSD_ENV) || defined(AFS_DARWIN_ENV)
927     if (tvc->v)
928         panic("afs_NewVCache(): free vcache with vnode attached");
929 #endif
930
931 #if !defined(AFS_SGI_ENV) && !defined(AFS_LINUX22_ENV)
932
933 #if defined(AFS_DISCON_ENV)
934     /* We need to preserve the slot that we're being stored into on
935      * disk */
936     { 
937         afs_uint32 slot;
938         slot = tvc->diskSlot;
939         memset(tvc, 0, sizeof(struct vcache));
940         tvc->diskSlot = slot;
941     }
942 #else
943     memset(tvc, 0, sizeof(struct vcache));
944 #endif
945
946 #else
947     tvc->uncred = 0;
948     memset(&(tvc->f), 0, sizeof(struct fvcache));
949 #endif
950
951     AFS_RWLOCK_INIT(&tvc->lock, "vcache lock");
952 #if     defined(AFS_SUN5_ENV)
953     AFS_RWLOCK_INIT(&tvc->vlock, "vcache vlock");
954 #endif /* defined(AFS_SUN5_ENV) */
955
956     tvc->mvid = NULL;
957     tvc->linkData = NULL;
958     tvc->cbExpires = 0;
959     tvc->opens = 0;
960     tvc->execsOrWriters = 0;
961     tvc->flockCount = 0;
962     tvc->f.states = CVInit;
963     tvc->last_looker = 0;
964     tvc->f.fid = *afid;
965     tvc->asynchrony = -1;
966     tvc->vc_error = 0;
967 #if defined(AFS_LINUX26_ENV)
968     tvc->cred = NULL;
969 #endif
970 #ifdef AFS_TEXT_ENV
971     tvc->flushDV.low = tvc->flushDV.high = AFS_MAXDV;
972 #endif
973     hzero(tvc->mapDV);
974     tvc->f.truncPos = AFS_NOTRUNC;        /* don't truncate until we need to */
975     hzero(tvc->f.m.DataVersion);  /* in case we copy it into flushDV */
976     tvc->Access = NULL;
977     tvc->callback = serverp;    /* to minimize chance that clear
978                                  * request is lost */
979 #if defined(AFS_DISCON_ENV)
980     QZero(&tvc->metadirty);
981 #endif
982
983     i = VCHash(afid);
984     j = VCHashV(afid);
985
986     tvc->hnext = afs_vhashT[i];
987     afs_vhashT[i] = tvc;
988     QAdd(&afs_vhashTV[j], &tvc->vhashq);
989     
990     if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
991         refpanic("NewVCache VLRU inconsistent");
992     }
993     QAdd(&VLRU, &tvc->vlruq);   /* put in lruq */
994     if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
995         refpanic("NewVCache VLRU inconsistent2");
996     }
997     if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
998         refpanic("NewVCache VLRU inconsistent3");
999     }
1000     if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
1001         refpanic("NewVCache VLRU inconsistent4");
1002     }
1003     vcachegen++;
1004     /* it should now be safe to drop the xvcache lock */
1005 #ifdef AFS_OBSD_ENV
1006     ReleaseWriteLock(&afs_xvcache);
1007     AFS_GUNLOCK();
1008     afs_nbsd_getnewvnode(tvc);  /* includes one refcount */
1009     AFS_GLOCK();
1010     ObtainWriteLock(&afs_xvcache,337);
1011     lockinit(&tvc->rwlock, PINOD, "vcache", 0, 0);
1012 #endif
1013 #ifdef AFS_DARWIN_ENV
1014     ReleaseWriteLock(&afs_xvcache);
1015     AFS_GUNLOCK();
1016     afs_darwin_getnewvnode(tvc);        /* includes one refcount */
1017     AFS_GLOCK();
1018     ObtainWriteLock(&afs_xvcache,338);
1019 #ifdef AFS_DARWIN80_ENV
1020     LOCKINIT(tvc->rwlock);
1021 #else
1022     lockinit(&tvc->rwlock, PINOD, "vcache", 0, 0);
1023 #endif
1024 #endif
1025 #ifdef AFS_FBSD_ENV
1026     {
1027         struct vnode *vp;
1028
1029         ReleaseWriteLock(&afs_xvcache);
1030         AFS_GUNLOCK();
1031 #if defined(AFS_FBSD60_ENV)
1032         if (getnewvnode(MOUNT_AFS, afs_globalVFS, &afs_vnodeops, &vp))
1033 #elif defined(AFS_FBSD50_ENV)
1034         if (getnewvnode(MOUNT_AFS, afs_globalVFS, afs_vnodeop_p, &vp))
1035 #else
1036         if (getnewvnode(VT_AFS, afs_globalVFS, afs_vnodeop_p, &vp))
1037 #endif
1038             panic("afs getnewvnode");   /* can't happen */
1039         AFS_GLOCK();
1040         ObtainWriteLock(&afs_xvcache,339);
1041         if (tvc->v != NULL) {
1042             /* I'd like to know if this ever happens...
1043              * We don't drop global for the rest of this function,
1044              * so if we do lose the race, the other thread should
1045              * have found the same vnode and finished initializing
1046              * the vcache entry.  Is it conceivable that this vcache
1047              * entry could be recycled during this interval?  If so,
1048              * then there probably needs to be some sort of additional
1049              * mutual exclusion (an Embryonic flag would suffice).
1050              * -GAW */
1051             printf("afs_NewVCache: lost the race\n");
1052             return (tvc);
1053         }
1054         tvc->v = vp;
1055         tvc->v->v_data = tvc;
1056         lockinit(&tvc->rwlock, PINOD, "vcache", 0, 0);
1057     }
1058 #endif
1059
1060 #if defined(AFS_LINUX22_ENV)
1061     /* Hold it for the LRU (should make count 2) */
1062     VN_HOLD(AFSTOV(tvc));
1063 #elif !(defined (AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV))
1064     VREFCOUNT_SET(tvc, 1);      /* us */
1065 #endif
1066
1067 #ifdef  AFS_AIX32_ENV
1068     LOCK_INIT(&tvc->pvmlock, "vcache pvmlock");
1069     tvc->vmh = tvc->segid = NULL;
1070     tvc->credp = NULL;
1071 #endif
1072
1073 #if defined(AFS_CACHE_BYPASS)
1074     tvc->cachingStates = 0;
1075     tvc->cachingTransitions = 0;
1076 #endif
1077
1078 #ifdef AFS_BOZONLOCK_ENV
1079 #if     defined(AFS_SUN5_ENV)
1080     rw_init(&tvc->rwlock, "vcache rwlock", RW_DEFAULT, NULL);
1081
1082 #if     defined(AFS_SUN55_ENV)
1083     /* This is required if the kaio (kernel aynchronous io)
1084      ** module is installed. Inside the kernel, the function
1085      ** check_vp( common/os/aio.c) checks to see if the kernel has
1086      ** to provide asynchronous io for this vnode. This
1087      ** function extracts the device number by following the
1088      ** v_data field of the vnode. If we do not set this field
1089      ** then the system panics. The  value of the v_data field
1090      ** is not really important for AFS vnodes because the kernel
1091      ** does not do asynchronous io for regular files. Hence,
1092      ** for the time being, we fill up the v_data field with the
1093      ** vnode pointer itself. */
1094     tvc->v.v_data = (char *)tvc;
1095 #endif /* AFS_SUN55_ENV */
1096 #endif
1097     afs_BozonInit(&tvc->pvnLock, tvc);
1098 #endif
1099
1100     /* initialize vnode data, note vrefCount is v.v_count */
1101 #ifdef  AFS_AIX_ENV
1102     /* Don't forget to free the gnode space */
1103     tvc->v.v_gnode = gnodepnt =
1104         (struct gnode *)osi_AllocSmallSpace(sizeof(struct gnode));
1105     memset(gnodepnt, 0, sizeof(struct gnode));
1106 #endif
1107 #ifdef AFS_SGI64_ENV
1108     memset((void *)&(tvc->vc_bhv_desc), 0, sizeof(tvc->vc_bhv_desc));
1109     bhv_desc_init(&(tvc->vc_bhv_desc), tvc, tvc, &Afs_vnodeops);
1110 #ifdef AFS_SGI65_ENV
1111     vn_bhv_head_init(&(tvc->v.v_bh), "afsvp");
1112     vn_bhv_insert_initial(&(tvc->v.v_bh), &(tvc->vc_bhv_desc));
1113 #else
1114     bhv_head_init(&(tvc->v.v_bh));
1115     bhv_insert_initial(&(tvc->v.v_bh), &(tvc->vc_bhv_desc));
1116 #endif
1117 #ifdef AFS_SGI65_ENV
1118     tvc->v.v_mreg = tvc->v.v_mregb = (struct pregion *)tvc;
1119 #ifdef VNODE_TRACING
1120     tvc->v.v_trace = ktrace_alloc(VNODE_TRACE_SIZE, 0);
1121 #endif
1122     init_bitlock(&tvc->v.v_pcacheflag, VNODE_PCACHE_LOCKBIT, "afs_pcache",
1123                  tvc->v.v_number);
1124     init_mutex(&tvc->v.v_filocksem, MUTEX_DEFAULT, "afsvfl", (long)tvc);
1125     init_mutex(&tvc->v.v_buf_lock, MUTEX_DEFAULT, "afsvnbuf", (long)tvc);
1126 #endif
1127     vnode_pcache_init(&tvc->v);
1128 #if defined(DEBUG) && defined(VNODE_INIT_BITLOCK)
1129     /* Above define is never true execpt in SGI test kernels. */
1130     init_bitlock(&(tvc->v.v_flag, VLOCK, "vnode", tvc->v.v_number);
1131 #endif
1132 #ifdef INTR_KTHREADS
1133                  AFS_VN_INIT_BUF_LOCK(&(tvc->v));
1134 #endif
1135 #else
1136     SetAfsVnode(AFSTOV(tvc));
1137 #endif /* AFS_SGI64_ENV */
1138     /*
1139      * The proper value for mvstat (for root fids) is setup by the caller.
1140      */
1141     tvc->mvstat = 0;
1142     if (afid->Fid.Vnode == 1 && afid->Fid.Unique == 1)
1143         tvc->mvstat = 2;
1144     if (afs_globalVFS == 0)
1145         osi_Panic("afs globalvfs");
1146 #if !defined(AFS_LINUX22_ENV)
1147     vSetVfsp(tvc, afs_globalVFS);
1148 #endif
1149     vSetType(tvc, VREG);
1150 #ifdef  AFS_AIX_ENV
1151     tvc->v.v_vfsnext = afs_globalVFS->vfs_vnodes;       /* link off vfs */
1152     tvc->v.v_vfsprev = NULL;
1153     afs_globalVFS->vfs_vnodes = &tvc->v;
1154     if (tvc->v.v_vfsnext != NULL)
1155         tvc->v.v_vfsnext->v_vfsprev = &tvc->v;
1156     tvc->v.v_next = gnodepnt->gn_vnode; /*Single vnode per gnode for us! */
1157     gnodepnt->gn_vnode = &tvc->v;
1158 #endif
1159 #ifdef AFS_FBSD70_ENV
1160 #ifndef AFS_FBSD80_ENV /* yup.  they put it back. */
1161     insmntque(AFSTOV(tvc), afs_globalVFS);
1162 #endif
1163 #endif
1164 #if defined(AFS_SGI_ENV)
1165     VN_SET_DPAGES(&(tvc->v), (struct pfdat *)NULL);
1166     osi_Assert((tvc->v.v_flag & VINACT) == 0);
1167     tvc->v.v_flag = 0;
1168     osi_Assert(VN_GET_PGCNT(&(tvc->v)) == 0);
1169     osi_Assert(tvc->mapcnt == 0 && tvc->vc_locktrips == 0);
1170     osi_Assert(tvc->vc_rwlockid == OSI_NO_LOCKID);
1171     osi_Assert(tvc->v.v_filocks == NULL);
1172 #if !defined(AFS_SGI65_ENV)
1173     osi_Assert(tvc->v.v_filocksem == NULL);
1174 #endif
1175     osi_Assert(tvc->cred == NULL);
1176 #ifdef AFS_SGI64_ENV
1177     vnode_pcache_reinit(&tvc->v);
1178     tvc->v.v_rdev = NODEV;
1179 #endif
1180     vn_initlist((struct vnlist *)&tvc->v);
1181     tvc->lastr = 0;
1182 #endif /* AFS_SGI_ENV */
1183     tvc->dchint = NULL;
1184     osi_dnlc_purgedp(tvc);      /* this may be overkill */
1185     memset(&(tvc->callsort), 0, sizeof(struct afs_q));
1186     tvc->slocks = NULL;
1187     tvc->f.states &=~ CVInit;
1188     afs_osi_Wakeup(&tvc->f.states);
1189
1190     return tvc;
1191
1192 }                               /*afs_NewVCache */
1193
1194
1195 /*!
1196  * ???
1197  *
1198  * LOCK: afs_FlushActiveVcaches afs_xvcache N
1199  *
1200  * \param doflocks : Do we handle flocks?
1201  */
1202 void
1203 afs_FlushActiveVcaches(register afs_int32 doflocks)
1204 {
1205     register struct vcache *tvc;
1206     register int i;
1207     register struct afs_conn *tc;
1208     register afs_int32 code;
1209     afs_ucred_t *cred = NULL;
1210     struct vrequest treq, ureq;
1211     struct AFSVolSync tsync;
1212     int didCore;
1213     XSTATS_DECLS;
1214     AFS_STATCNT(afs_FlushActiveVcaches);
1215     ObtainReadLock(&afs_xvcache);
1216     for (i = 0; i < VCSIZE; i++) {
1217         for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
1218             if (tvc->f.states & CVInit) continue;
1219 #ifdef AFS_DARWIN80_ENV
1220             if (tvc->f.states & CDeadVnode &&
1221                 (tvc->f.states & (CCore|CUnlinkedDel) ||
1222                  tvc->flockCount)) panic("Dead vnode has core/unlinkedel/flock");
1223 #endif
1224             if (doflocks && tvc->flockCount != 0) {
1225                 /* if this entry has an flock, send a keep-alive call out */
1226                 osi_vnhold(tvc, 0);
1227                 ReleaseReadLock(&afs_xvcache);
1228                 ObtainWriteLock(&tvc->lock, 51);
1229                 do {
1230                     afs_InitReq(&treq, afs_osi_credp);
1231                     treq.flags |= O_NONBLOCK;
1232
1233                     tc = afs_Conn(&tvc->f.fid, &treq, SHARED_LOCK);
1234                     if (tc) {
1235                         XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_EXTENDLOCK);
1236                         RX_AFS_GUNLOCK();
1237                         code =
1238                             RXAFS_ExtendLock(tc->id,
1239                                              (struct AFSFid *)&tvc->f.fid.Fid,
1240                                              &tsync);
1241                         RX_AFS_GLOCK();
1242                         XSTATS_END_TIME;
1243                     } else
1244                         code = -1;
1245                 } while (afs_Analyze
1246                          (tc, code, &tvc->f.fid, &treq,
1247                           AFS_STATS_FS_RPCIDX_EXTENDLOCK, SHARED_LOCK, NULL));
1248
1249                 ReleaseWriteLock(&tvc->lock);
1250 #ifdef AFS_DARWIN80_ENV
1251                 AFS_FAST_RELE(tvc);
1252                 ObtainReadLock(&afs_xvcache);
1253 #else
1254                 ObtainReadLock(&afs_xvcache);
1255                 AFS_FAST_RELE(tvc);
1256 #endif
1257             }
1258             didCore = 0;
1259             if ((tvc->f.states & CCore) || (tvc->f.states & CUnlinkedDel)) {
1260                 /*
1261                  * Don't let it evaporate in case someone else is in
1262                  * this code.  Also, drop the afs_xvcache lock while
1263                  * getting vcache locks.
1264                  */
1265                 osi_vnhold(tvc, 0);
1266                 ReleaseReadLock(&afs_xvcache);
1267 #ifdef AFS_BOZONLOCK_ENV
1268                 afs_BozonLock(&tvc->pvnLock, tvc);
1269 #endif
1270 #if defined(AFS_SGI_ENV)
1271                 /*
1272                  * That's because if we come in via the CUnlinkedDel bit state path we'll be have 0 refcnt
1273                  */
1274                 osi_Assert(VREFCOUNT_GT(tvc,0));
1275                 AFS_RWLOCK((vnode_t *) tvc, VRWLOCK_WRITE);
1276 #endif
1277                 ObtainWriteLock(&tvc->lock, 52);
1278                 if (tvc->f.states & CCore) {
1279                     tvc->f.states &= ~CCore;
1280                     /* XXXX Find better place-holder for cred XXXX */
1281                     cred = (afs_ucred_t *)tvc->linkData;
1282                     tvc->linkData = NULL;       /* XXX */
1283                     afs_InitReq(&ureq, cred);
1284                     afs_Trace2(afs_iclSetp, CM_TRACE_ACTCCORE,
1285                                ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32,
1286                                tvc->execsOrWriters);
1287                     code = afs_StoreOnLastReference(tvc, &ureq);
1288                     ReleaseWriteLock(&tvc->lock);
1289 #ifdef AFS_BOZONLOCK_ENV
1290                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1291 #endif
1292                     hzero(tvc->flushDV);
1293                     osi_FlushText(tvc);
1294                     didCore = 1;
1295                     if (code && code != VNOVNODE) {
1296                         afs_StoreWarn(code, tvc->f.fid.Fid.Volume,
1297                                       /* /dev/console */ 1);
1298                     }
1299                 } else if (tvc->f.states & CUnlinkedDel) {
1300                     /*
1301                      * Ignore errors
1302                      */
1303                     ReleaseWriteLock(&tvc->lock);
1304 #ifdef AFS_BOZONLOCK_ENV
1305                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1306 #endif
1307 #if defined(AFS_SGI_ENV)
1308                     AFS_RWUNLOCK((vnode_t *) tvc, VRWLOCK_WRITE);
1309 #endif
1310                     afs_remunlink(tvc, 0);
1311 #if defined(AFS_SGI_ENV)
1312                     AFS_RWLOCK((vnode_t *) tvc, VRWLOCK_WRITE);
1313 #endif
1314                 } else {
1315                     /* lost (or won, perhaps) the race condition */
1316                     ReleaseWriteLock(&tvc->lock);
1317 #ifdef AFS_BOZONLOCK_ENV
1318                     afs_BozonUnlock(&tvc->pvnLock, tvc);
1319 #endif
1320                 }
1321 #if defined(AFS_SGI_ENV)
1322                 AFS_RWUNLOCK((vnode_t *) tvc, VRWLOCK_WRITE);
1323 #endif
1324 #ifdef AFS_DARWIN80_ENV
1325                 AFS_FAST_RELE(tvc);
1326                 if (didCore) {
1327                     AFS_RELE(AFSTOV(tvc));
1328                     /* Matches write code setting CCore flag */
1329                     crfree(cred);
1330                 }
1331                 ObtainReadLock(&afs_xvcache);
1332 #else
1333                 ObtainReadLock(&afs_xvcache);
1334                 AFS_FAST_RELE(tvc);
1335                 if (didCore) {
1336                     AFS_RELE(AFSTOV(tvc));
1337                     /* Matches write code setting CCore flag */
1338                     crfree(cred);
1339                 }
1340 #endif
1341             }
1342         }
1343     }
1344     ReleaseReadLock(&afs_xvcache);
1345 }
1346
1347
1348
1349 /*!
1350  *   Make sure a cache entry is up-to-date status-wise.
1351  *
1352  * NOTE: everywhere that calls this can potentially be sped up
1353  *       by checking CStatd first, and avoiding doing the InitReq
1354  *       if this is up-to-date.
1355  *
1356  *  Anymore, the only places that call this KNOW already that the
1357  *  vcache is not up-to-date, so we don't screw around.
1358  *
1359  * \param avc  : Ptr to vcache entry to verify.
1360  * \param areq : ???
1361  */
1362
1363 /*!
1364  * 
1365  *   Make sure a cache entry is up-to-date status-wise.
1366  *   
1367  *   NOTE: everywhere that calls this can potentially be sped up
1368  *       by checking CStatd first, and avoiding doing the InitReq
1369  *       if this is up-to-date.
1370  *
1371  *   Anymore, the only places that call this KNOW already that the
1372  * vcache is not up-to-date, so we don't screw around.
1373  *
1374  * \param avc Pointer to vcache entry to verify.
1375  * \param areq
1376  *
1377  * \return 0 for success or other error codes.
1378  */
1379 int
1380 afs_VerifyVCache2(struct vcache *avc, struct vrequest *areq)
1381 {
1382     register struct vcache *tvc;
1383
1384     AFS_STATCNT(afs_VerifyVCache);
1385
1386     /* otherwise we must fetch the status info */
1387
1388     ObtainWriteLock(&avc->lock, 53);
1389     if (avc->f.states & CStatd) {
1390         ReleaseWriteLock(&avc->lock);
1391         return 0;
1392     }
1393     ObtainWriteLock(&afs_xcbhash, 461);
1394     avc->f.states &= ~(CStatd | CUnique);
1395     avc->callback = NULL;
1396     afs_DequeueCallback(avc);
1397     ReleaseWriteLock(&afs_xcbhash);
1398     ReleaseWriteLock(&avc->lock);
1399
1400     /* since we've been called back, or the callback has expired,
1401      * it's possible that the contents of this directory, or this
1402      * file's name have changed, thus invalidating the dnlc contents.
1403      */
1404     if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
1405         osi_dnlc_purgedp(avc);
1406     else
1407         osi_dnlc_purgevp(avc);
1408
1409     /* fetch the status info */
1410     tvc = afs_GetVCache(&avc->f.fid, areq, NULL, avc);
1411     if (!tvc)
1412         return ENOENT;
1413     /* Put it back; caller has already incremented vrefCount */
1414     afs_PutVCache(tvc);
1415     return 0;
1416
1417 }                               /*afs_VerifyVCache */
1418
1419
1420 /*!
1421  * Simple copy of stat info into cache.
1422  *
1423  * Callers:as of 1992-04-29, only called by WriteVCache
1424  *
1425  * \param avc   Ptr to vcache entry involved.
1426  * \param astat Ptr to stat info to copy.
1427  *
1428  */
1429 static void
1430 afs_SimpleVStat(register struct vcache *avc,
1431                 register struct AFSFetchStatus *astat, struct vrequest *areq)
1432 {
1433     afs_size_t length;
1434     AFS_STATCNT(afs_SimpleVStat);
1435
1436 #ifdef AFS_SGI_ENV
1437     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)
1438         && !AFS_VN_MAPPED((vnode_t *) avc)) {
1439 #else
1440     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)) {
1441 #endif
1442 #ifdef AFS_64BIT_CLIENT
1443         FillInt64(length, astat->Length_hi, astat->Length);
1444 #else /* AFS_64BIT_CLIENT */
1445         length = astat->Length;
1446 #endif /* AFS_64BIT_CLIENT */
1447 #if defined(AFS_SGI_ENV)
1448         osi_Assert((valusema(&avc->vc_rwlock) <= 0)
1449                    && (OSI_GET_LOCKID() == avc->vc_rwlockid));
1450         if (length < avc->f.m.Length) {
1451             vnode_t *vp = (vnode_t *) avc;
1452
1453             osi_Assert(WriteLocked(&avc->lock));
1454             ReleaseWriteLock(&avc->lock);
1455             AFS_GUNLOCK();
1456             PTOSSVP(vp, (off_t) length, (off_t) MAXLONG);
1457             AFS_GLOCK();
1458             ObtainWriteLock(&avc->lock, 67);
1459         }
1460 #endif
1461         /* if writing the file, don't fetch over this value */
1462         afs_Trace3(afs_iclSetp, CM_TRACE_SIMPLEVSTAT, ICL_TYPE_POINTER, avc,
1463                    ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length),
1464                    ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(length));
1465         avc->f.m.Length = length;
1466         avc->f.m.Date = astat->ClientModTime;
1467     }
1468     avc->f.m.Owner = astat->Owner;
1469     avc->f.m.Group = astat->Group;
1470     avc->f.m.Mode = astat->UnixModeBits;
1471     if (vType(avc) == VREG) {
1472         avc->f.m.Mode |= S_IFREG;
1473     } else if (vType(avc) == VDIR) {
1474         avc->f.m.Mode |= S_IFDIR;
1475     } else if (vType(avc) == VLNK) {
1476         avc->f.m.Mode |= S_IFLNK;
1477         if ((avc->f.m.Mode & 0111) == 0)
1478             avc->mvstat = 1;
1479     }
1480     if (avc->f.states & CForeign) {
1481         struct axscache *ac;
1482         avc->f.anyAccess = astat->AnonymousAccess;
1483 #ifdef badidea
1484         if ((astat->CallerAccess & ~astat->AnonymousAccess))
1485             /*   USED TO SAY :
1486              * Caller has at least one bit not covered by anonymous, and
1487              * thus may have interesting rights.
1488              *
1489              * HOWEVER, this is a really bad idea, because any access query
1490              * for bits which aren't covered by anonymous, on behalf of a user
1491              * who doesn't have any special rights, will result in an answer of
1492              * the form "I don't know, lets make a FetchStatus RPC and find out!"
1493              * It's an especially bad idea under Ultrix, since (due to the lack of
1494              * a proper access() call) it must perform several afs_access() calls
1495              * in order to create magic mode bits that vary according to who makes
1496              * the call.  In other words, _every_ stat() generates a test for
1497              * writeability...
1498              */
1499 #endif /* badidea */
1500             if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
1501                 ac->axess = astat->CallerAccess;
1502             else                /* not found, add a new one if possible */
1503                 afs_AddAxs(avc->Access, areq->uid, astat->CallerAccess);
1504     }
1505
1506 }                               /*afs_SimpleVStat */
1507
1508
1509 /*!
1510  * Store the status info *only* back to the server for a
1511  * fid/vrequest.
1512  *
1513  * Environment: Must be called with a shared lock held on the vnode.
1514  *
1515  * \param avc Ptr to the vcache entry.
1516  * \param astatus Ptr to the status info to store.
1517  * \param areq Ptr to the associated vrequest.
1518  *
1519  * \return Operation status.
1520  */
1521
1522 int
1523 afs_WriteVCache(register struct vcache *avc,
1524                 register struct AFSStoreStatus *astatus,
1525                 struct vrequest *areq)
1526 {
1527     afs_int32 code;
1528     struct afs_conn *tc;
1529     struct AFSFetchStatus OutStatus;
1530     struct AFSVolSync tsync;
1531     XSTATS_DECLS;
1532     AFS_STATCNT(afs_WriteVCache);
1533     afs_Trace2(afs_iclSetp, CM_TRACE_WVCACHE, ICL_TYPE_POINTER, avc,
1534                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1535     do {
1536         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
1537         if (tc) {
1538             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_STORESTATUS);
1539             RX_AFS_GUNLOCK();
1540             code =
1541                 RXAFS_StoreStatus(tc->id, (struct AFSFid *)&avc->f.fid.Fid,
1542                                   astatus, &OutStatus, &tsync);
1543             RX_AFS_GLOCK();
1544             XSTATS_END_TIME;
1545         } else
1546             code = -1;
1547     } while (afs_Analyze
1548              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_STORESTATUS,
1549               SHARED_LOCK, NULL));
1550
1551     UpgradeSToWLock(&avc->lock, 20);
1552     if (code == 0) {
1553         /* success, do the changes locally */
1554         afs_SimpleVStat(avc, &OutStatus, areq);
1555         /*
1556          * Update the date, too.  SimpleVStat didn't do this, since
1557          * it thought we were doing this after fetching new status
1558          * over a file being written.
1559          */
1560         avc->f.m.Date = OutStatus.ClientModTime;
1561     } else {
1562         /* failure, set up to check with server next time */
1563         ObtainWriteLock(&afs_xcbhash, 462);
1564         afs_DequeueCallback(avc);
1565         avc->f.states &= ~(CStatd | CUnique);   /* turn off stat valid flag */
1566         ReleaseWriteLock(&afs_xcbhash);
1567         if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
1568             osi_dnlc_purgedp(avc);      /* if it (could be) a directory */
1569     }
1570     ConvertWToSLock(&avc->lock);
1571     return code;
1572
1573 }                               /*afs_WriteVCache */
1574 #if defined(AFS_DISCON_ENV)
1575
1576 /*!
1577  * Store status info only locally, set the proper disconnection flags
1578  * and add to dirty list.
1579  *
1580  * \param avc The vcache to be written locally.
1581  * \param astatus Get attr fields from local store.
1582  * \param attrs This one is only of the vs_size.
1583  *
1584  * \note Must be called with a shared lock on the vnode
1585  */
1586 int afs_WriteVCacheDiscon(register struct vcache *avc,
1587                                 register struct AFSStoreStatus *astatus,
1588                                 struct vattr *attrs)
1589 {
1590     afs_int32 code = 0;
1591     afs_int32 flags = 0;
1592
1593     UpgradeSToWLock(&avc->lock, 700);
1594
1595     if (!astatus->Mask) {
1596
1597         return code;
1598
1599     } else {
1600
1601         /* Set attributes. */
1602         if (astatus->Mask & AFS_SETMODTIME) {
1603                 avc->f.m.Date = astatus->ClientModTime;
1604                 flags |= VDisconSetTime;
1605         }
1606
1607         if (astatus->Mask & AFS_SETOWNER) {
1608                 printf("Not allowed yet. \n");
1609                 /*avc->f.m.Owner = astatus->Owner;*/
1610         }
1611
1612         if (astatus->Mask & AFS_SETGROUP) {
1613                 printf("Not allowed yet. \n");
1614                 /*avc->f.m.Group =  astatus->Group;*/
1615         }
1616
1617         if (astatus->Mask & AFS_SETMODE) {
1618                 avc->f.m.Mode = astatus->UnixModeBits;
1619
1620 #if 0   /* XXX: Leaving this out, so it doesn't mess up the file type flag.*/
1621
1622                 if (vType(avc) == VREG) {
1623                         avc->f.m.Mode |= S_IFREG;
1624                 } else if (vType(avc) == VDIR) {
1625                         avc->f.m.Mode |= S_IFDIR;
1626                 } else if (vType(avc) == VLNK) {
1627                         avc->f.m.Mode |= S_IFLNK;
1628                         if ((avc->f.m.Mode & 0111) == 0)
1629                                 avc->mvstat = 1;
1630                 }
1631 #endif
1632                 flags |= VDisconSetMode;
1633          }              /* if(astatus.Mask & AFS_SETMODE) */
1634
1635      }                  /* if (!astatus->Mask) */
1636
1637      if (attrs->va_size > 0) {
1638         /* XXX: Do I need more checks? */
1639         /* Truncation operation. */
1640         flags |= VDisconTrunc;
1641      }
1642
1643     if (flags)
1644         afs_DisconAddDirty(avc, flags, 1);
1645
1646     /* XXX: How about the rest of the fields? */
1647
1648     ConvertWToSLock(&avc->lock);
1649
1650     return code;
1651 }
1652
1653 #endif
1654
1655 /*!
1656  * Copy astat block into vcache info
1657  *
1658  * \note This code may get dataversion and length out of sync if the file has
1659  * been modified.  This is less than ideal.  I haven't thought about it sufficiently 
1660  * to be certain that it is adequate.
1661  *
1662  * \note Environment: Must be called under a write lock
1663  *
1664  * \param avc  Ptr to vcache entry.
1665  * \param astat Ptr to stat block to copy in.
1666  * \param areq Ptr to associated request.
1667  */
1668 void
1669 afs_ProcessFS(register struct vcache *avc,
1670               register struct AFSFetchStatus *astat, struct vrequest *areq)
1671 {
1672     afs_size_t length;
1673     AFS_STATCNT(afs_ProcessFS);
1674
1675 #ifdef AFS_64BIT_CLIENT
1676     FillInt64(length, astat->Length_hi, astat->Length);
1677 #else /* AFS_64BIT_CLIENT */
1678     length = astat->Length;
1679 #endif /* AFS_64BIT_CLIENT */
1680     /* WARNING: afs_DoBulkStat uses the Length field to store a sequence
1681      * number for each bulk status request. Under no circumstances
1682      * should afs_DoBulkStat store a sequence number if the new
1683      * length will be ignored when afs_ProcessFS is called with
1684      * new stats. If you change the following conditional then you
1685      * also need to change the conditional in afs_DoBulkStat.  */
1686 #ifdef AFS_SGI_ENV
1687     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)
1688         && !AFS_VN_MAPPED((vnode_t *) avc)) {
1689 #else
1690     if ((avc->execsOrWriters <= 0) && !afs_DirtyPages(avc)) {
1691 #endif
1692         /* if we're writing or mapping this file, don't fetch over these
1693          *  values.
1694          */
1695         afs_Trace3(afs_iclSetp, CM_TRACE_PROCESSFS, ICL_TYPE_POINTER, avc,
1696                    ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length),
1697                    ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(length));
1698         avc->f.m.Length = length;
1699         avc->f.m.Date = astat->ClientModTime;
1700     }
1701     hset64(avc->f.m.DataVersion, astat->dataVersionHigh, astat->DataVersion);
1702     avc->f.m.Owner = astat->Owner;
1703     avc->f.m.Mode = astat->UnixModeBits;
1704     avc->f.m.Group = astat->Group;
1705     avc->f.m.LinkCount = astat->LinkCount;
1706     if (astat->FileType == File) {
1707         vSetType(avc, VREG);
1708         avc->f.m.Mode |= S_IFREG;
1709     } else if (astat->FileType == Directory) {
1710         vSetType(avc, VDIR);
1711         avc->f.m.Mode |= S_IFDIR;
1712     } else if (astat->FileType == SymbolicLink) {
1713         if (afs_fakestat_enable && (avc->f.m.Mode & 0111) == 0) {
1714             vSetType(avc, VDIR);
1715             avc->f.m.Mode |= S_IFDIR;
1716         } else {
1717             vSetType(avc, VLNK);
1718             avc->f.m.Mode |= S_IFLNK;
1719         }
1720         if ((avc->f.m.Mode & 0111) == 0) {
1721             avc->mvstat = 1;
1722         }
1723     }
1724     avc->f.anyAccess = astat->AnonymousAccess;
1725 #ifdef badidea
1726     if ((astat->CallerAccess & ~astat->AnonymousAccess))
1727         /*   USED TO SAY :
1728          * Caller has at least one bit not covered by anonymous, and
1729          * thus may have interesting rights.
1730          *
1731          * HOWEVER, this is a really bad idea, because any access query
1732          * for bits which aren't covered by anonymous, on behalf of a user
1733          * who doesn't have any special rights, will result in an answer of
1734          * the form "I don't know, lets make a FetchStatus RPC and find out!"
1735          * It's an especially bad idea under Ultrix, since (due to the lack of
1736          * a proper access() call) it must perform several afs_access() calls
1737          * in order to create magic mode bits that vary according to who makes
1738          * the call.  In other words, _every_ stat() generates a test for
1739          * writeability...
1740          */
1741 #endif /* badidea */
1742     {
1743         struct axscache *ac;
1744         if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
1745             ac->axess = astat->CallerAccess;
1746         else                    /* not found, add a new one if possible */
1747             afs_AddAxs(avc->Access, areq->uid, astat->CallerAccess);
1748     }
1749 }                               /*afs_ProcessFS */
1750
1751
1752 /*!
1753  * Get fid from server.
1754  *
1755  * \param afid 
1756  * \param areq Request to be passed on.
1757  * \param name Name of ?? to lookup.
1758  * \param OutStatus Fetch status.
1759  * \param CallBackp 
1760  * \param serverp
1761  * \param tsyncp
1762  *
1763  * \return Success status of operation.
1764  */
1765 int
1766 afs_RemoteLookup(register struct VenusFid *afid, struct vrequest *areq,
1767                  char *name, struct VenusFid *nfid,
1768                  struct AFSFetchStatus *OutStatusp,
1769                  struct AFSCallBack *CallBackp, struct server **serverp,
1770                  struct AFSVolSync *tsyncp)
1771 {
1772     afs_int32 code;
1773     afs_uint32 start;
1774     register struct afs_conn *tc;
1775     struct AFSFetchStatus OutDirStatus;
1776     XSTATS_DECLS;
1777     if (!name)
1778         name = "";              /* XXX */    
1779     do {
1780         tc = afs_Conn(afid, areq, SHARED_LOCK);
1781         if (tc) {
1782             if (serverp)
1783                 *serverp = tc->srvr->server;
1784             start = osi_Time();
1785             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_XLOOKUP);
1786             RX_AFS_GUNLOCK();
1787             code =
1788                 RXAFS_Lookup(tc->id, (struct AFSFid *)&afid->Fid, name,
1789                              (struct AFSFid *)&nfid->Fid, OutStatusp,
1790                              &OutDirStatus, CallBackp, tsyncp);
1791             RX_AFS_GLOCK();
1792             XSTATS_END_TIME;
1793         } else
1794             code = -1;
1795     } while (afs_Analyze
1796              (tc, code, afid, areq, AFS_STATS_FS_RPCIDX_XLOOKUP, SHARED_LOCK,
1797               NULL));
1798
1799     return code;
1800 }
1801
1802
1803 /*!
1804  * afs_GetVCache
1805  *
1806  * Given a file id and a vrequest structure, fetch the status
1807  * information associated with the file.
1808  *
1809  * \param afid File ID.
1810  * \param areq Ptr to associated vrequest structure, specifying the
1811  *  user whose authentication tokens will be used.
1812  * \param avc Caller may already have a vcache for this file, which is
1813  *  already held.
1814  *
1815  * \note Environment:
1816  *      The cache entry is returned with an increased vrefCount field.
1817  *      The entry must be discarded by calling afs_PutVCache when you
1818  *      are through using the pointer to the cache entry.
1819  *
1820  *      You should not hold any locks when calling this function, except
1821  *      locks on other vcache entries.  If you lock more than one vcache
1822  *      entry simultaneously, you should lock them in this order:
1823  *
1824  *          1. Lock all files first, then directories.
1825  *          2.  Within a particular type, lock entries in Fid.Vnode order.
1826  *
1827  *      This locking hierarchy is convenient because it allows locking
1828  *      of a parent dir cache entry, given a file (to check its access
1829  *      control list).  It also allows renames to be handled easily by
1830  *      locking directories in a constant order.
1831  * 
1832  * \note NB.  NewVCache -> FlushVCache presently (4/10/95) drops the xvcache lock.
1833  *
1834  * \note Might have a vcache structure already, which must
1835  *  already be held by the caller 
1836  */
1837 struct vcache *
1838 afs_GetVCache(register struct VenusFid *afid, struct vrequest *areq,
1839               afs_int32 * cached, struct vcache *avc)
1840 {
1841
1842     afs_int32 code, newvcache = 0;
1843     register struct vcache *tvc;
1844     struct volume *tvp;
1845     afs_int32 retry;
1846
1847     AFS_STATCNT(afs_GetVCache);
1848
1849     if (cached)
1850         *cached = 0;            /* Init just in case */
1851
1852 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
1853   loop:
1854 #endif
1855
1856     ObtainSharedLock(&afs_xvcache, 5);
1857
1858     tvc = afs_FindVCache(afid, &retry, DO_STATS | DO_VLRU | IS_SLOCK);
1859     if (tvc && retry) {
1860 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
1861         ReleaseSharedLock(&afs_xvcache);
1862         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
1863         goto loop;
1864 #endif
1865     }
1866
1867     if (tvc) {
1868         if (cached)
1869             *cached = 1;
1870         osi_Assert((tvc->f.states & CVInit) == 0);
1871         /* If we are in readdir, return the vnode even if not statd */
1872         if ((tvc->f.states & CStatd) || afs_InReadDir(tvc)) {
1873             ReleaseSharedLock(&afs_xvcache);
1874             return tvc;
1875         }
1876     } else {
1877         UpgradeSToWLock(&afs_xvcache, 21);
1878
1879         /* no cache entry, better grab one */
1880         tvc = afs_NewVCache(afid, NULL);
1881         newvcache = 1;
1882
1883         ConvertWToSLock(&afs_xvcache);
1884         if (tvc == NULL)
1885         {
1886                 ReleaseSharedLock(&afs_xvcache);
1887                 return NULL;
1888         }
1889
1890         afs_stats_cmperf.vcacheMisses++;
1891     }
1892
1893     ReleaseSharedLock(&afs_xvcache);
1894
1895     ObtainWriteLock(&tvc->lock, 54);
1896
1897     if (tvc->f.states & CStatd) {
1898         ReleaseWriteLock(&tvc->lock);
1899         return tvc;
1900     }
1901 #ifdef AFS_DARWIN80_ENV
1902 /* Darwin 8.0 only has bufs in nfs, so we shouldn't have to worry about them.
1903    What about ubc? */
1904 #else
1905 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
1906     /*
1907      * XXX - I really don't like this.  Should try to understand better.
1908      * It seems that sometimes, when we get called, we already hold the
1909      * lock on the vnode (e.g., from afs_getattr via afs_VerifyVCache).
1910      * We can't drop the vnode lock, because that could result in a race.
1911      * Sometimes, though, we get here and don't hold the vnode lock.
1912      * I hate code paths that sometimes hold locks and sometimes don't.
1913      * In any event, the dodge we use here is to check whether the vnode
1914      * is locked, and if it isn't, then we gain and drop it around the call
1915      * to vinvalbuf; otherwise, we leave it alone.
1916      */
1917     {
1918         struct vnode *vp = AFSTOV(tvc);
1919         int iheldthelock;
1920
1921 #if defined(AFS_DARWIN_ENV)
1922         iheldthelock = VOP_ISLOCKED(vp);
1923         if (!iheldthelock)
1924             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, current_proc());
1925         /* this is messy. we can call fsync which will try to reobtain this */
1926         if (VTOAFS(vp) == tvc) 
1927           ReleaseWriteLock(&tvc->lock);
1928         if (UBCINFOEXISTS(vp)) {
1929           vinvalbuf(vp, V_SAVE, &afs_osi_cred, current_proc(), PINOD, 0);
1930         }
1931         if (VTOAFS(vp) == tvc) 
1932           ObtainWriteLock(&tvc->lock, 954);
1933         if (!iheldthelock)
1934             VOP_UNLOCK(vp, LK_EXCLUSIVE, current_proc());
1935 #elif defined(AFS_FBSD80_ENV)
1936         iheldthelock = VOP_ISLOCKED(vp);
1937         if (!iheldthelock) {
1938             /* nosleep/sleep lock order reversal */
1939             int glocked = ISAFS_GLOCK();
1940             if (glocked)
1941                 AFS_GUNLOCK();
1942             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1943             if (glocked)
1944                 AFS_GLOCK();
1945         }
1946         vinvalbuf(vp, V_SAVE, PINOD, 0); /* changed late in 8.0-CURRENT */
1947         if (!iheldthelock)
1948             VOP_UNLOCK(vp, 0);
1949 #elif defined(AFS_FBSD60_ENV)
1950         iheldthelock = VOP_ISLOCKED(vp, curthread);
1951         if (!iheldthelock)
1952             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
1953         vinvalbuf(vp, V_SAVE, curthread, PINOD, 0);
1954         if (!iheldthelock)
1955             VOP_UNLOCK(vp, LK_EXCLUSIVE, curthread);
1956 #elif defined(AFS_FBSD50_ENV)
1957         iheldthelock = VOP_ISLOCKED(vp, curthread);
1958         if (!iheldthelock)
1959             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
1960         vinvalbuf(vp, V_SAVE, osi_curcred(), curthread, PINOD, 0);
1961         if (!iheldthelock)
1962             VOP_UNLOCK(vp, LK_EXCLUSIVE, curthread);
1963 #elif defined(AFS_FBSD40_ENV)
1964         iheldthelock = VOP_ISLOCKED(vp, curproc);
1965         if (!iheldthelock)
1966             vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curproc);
1967         vinvalbuf(vp, V_SAVE, osi_curcred(), curproc, PINOD, 0);
1968         if (!iheldthelock)
1969             VOP_UNLOCK(vp, LK_EXCLUSIVE, curproc);
1970 #elif defined(AFS_OBSD_ENV)
1971         iheldthelock = VOP_ISLOCKED(vp, curproc);
1972         if (!iheldthelock)
1973             VOP_LOCK(vp, LK_EXCLUSIVE | LK_RETRY, curproc);
1974         uvm_vnp_uncache(vp);
1975         if (!iheldthelock)
1976             VOP_UNLOCK(vp, 0, curproc);
1977 #endif
1978     }
1979 #endif
1980 #endif
1981
1982     ObtainWriteLock(&afs_xcbhash, 464);
1983     tvc->f.states &= ~CUnique;
1984     tvc->callback = 0;
1985     afs_DequeueCallback(tvc);
1986     ReleaseWriteLock(&afs_xcbhash);
1987
1988     /* It is always appropriate to throw away all the access rights? */
1989     afs_FreeAllAxs(&(tvc->Access));
1990     tvp = afs_GetVolume(afid, areq, READ_LOCK); /* copy useful per-volume info */
1991     if (tvp) {
1992         if ((tvp->states & VForeign)) {
1993             if (newvcache)
1994                 tvc->f.states |= CForeign;
1995             if (newvcache && (tvp->rootVnode == afid->Fid.Vnode)
1996                 && (tvp->rootUnique == afid->Fid.Unique)) {
1997                 tvc->mvstat = 2;
1998             }
1999         }
2000         if (tvp->states & VRO)
2001             tvc->f.states |= CRO;
2002         if (tvp->states & VBackup)
2003             tvc->f.states |= CBackup;
2004         /* now copy ".." entry back out of volume structure, if necessary */
2005         if (tvc->mvstat == 2 && tvp->dotdot.Fid.Volume != 0) {
2006             if (!tvc->mvid)
2007                 tvc->mvid = (struct VenusFid *)
2008                     osi_AllocSmallSpace(sizeof(struct VenusFid));
2009             *tvc->mvid = tvp->dotdot;
2010         }
2011         afs_PutVolume(tvp, READ_LOCK);
2012     }
2013
2014     /* stat the file */
2015     afs_RemoveVCB(afid);
2016     {
2017         struct AFSFetchStatus OutStatus;
2018
2019         if (afs_DynrootNewVnode(tvc, &OutStatus)) {
2020             afs_ProcessFS(tvc, &OutStatus, areq);
2021             tvc->f.states |= CStatd | CUnique;
2022             tvc->f.parent.vnode  = OutStatus.ParentVnode;
2023             tvc->f.parent.unique = OutStatus.ParentUnique;
2024             code = 0;
2025         } else {
2026
2027             if (AFS_IS_DISCONNECTED) {
2028                 /* Nothing to do otherwise...*/
2029                 code = ENETDOWN;
2030                 printf("Network is down in afs_GetCache");
2031             } else
2032                 code = afs_FetchStatus(tvc, afid, areq, &OutStatus);
2033
2034             /* For the NFS translator's benefit, make sure
2035              * non-directory vnodes always have their parent FID set
2036              * correctly, even when created as a result of decoding an
2037              * NFS filehandle.  It would be nice to also do this for
2038              * directories, but we can't because the fileserver fills
2039              * in the FID of the directory itself instead of that of
2040              * its parent.
2041              */
2042             if (!code && OutStatus.FileType != Directory &&
2043                 !tvc->f.parent.vnode) {
2044                 tvc->f.parent.vnode  = OutStatus.ParentVnode;
2045                 tvc->f.parent.unique = OutStatus.ParentUnique;
2046                 /* XXX - SXW - It's conceivable we should mark ourselves
2047                  *             as dirty again here, incase we've been raced
2048                  *             out of the FetchStatus call.
2049                  */
2050             }
2051         }
2052     }
2053
2054     if (code) {
2055         ReleaseWriteLock(&tvc->lock);
2056
2057         afs_PutVCache(tvc);
2058         return NULL;
2059     }
2060
2061     ReleaseWriteLock(&tvc->lock);
2062     return tvc;
2063
2064 }                               /*afs_GetVCache */
2065
2066
2067
2068 /*!
2069  * Lookup a vcache by fid. Look inside the cache first, if not
2070  * there, lookup the file on the server, and then get it's fresh
2071  * cache entry.
2072  * 
2073  * \param afid
2074  * \param areq 
2075  * \param cached Is element cached? If NULL, don't answer.
2076  * \param adp
2077  * \param aname
2078  *
2079  * \return The found element or NULL.
2080  */
2081 struct vcache *
2082 afs_LookupVCache(struct VenusFid *afid, struct vrequest *areq,
2083                  afs_int32 * cached, struct vcache *adp, char *aname)
2084 {
2085     afs_int32 code, now, newvcache = 0;
2086     struct VenusFid nfid;
2087     register struct vcache *tvc;
2088     struct volume *tvp;
2089     struct AFSFetchStatus OutStatus;
2090     struct AFSCallBack CallBack;
2091     struct AFSVolSync tsync;
2092     struct server *serverp = 0;
2093     afs_int32 origCBs;
2094     afs_int32 retry;
2095
2096     AFS_STATCNT(afs_GetVCache);
2097     if (cached)
2098         *cached = 0;            /* Init just in case */
2099
2100 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2101   loop1:
2102 #endif
2103
2104     ObtainReadLock(&afs_xvcache);
2105     tvc = afs_FindVCache(afid, &retry, DO_STATS /* no vlru */ );
2106
2107     if (tvc) {
2108         ReleaseReadLock(&afs_xvcache);
2109         if (retry) {
2110 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2111             spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
2112             goto loop1;
2113 #endif
2114         }
2115         ObtainReadLock(&tvc->lock);
2116
2117         if (tvc->f.states & CStatd) {
2118             if (cached) {
2119                 *cached = 1;
2120             }
2121             ReleaseReadLock(&tvc->lock);
2122             return tvc;
2123         }
2124         tvc->f.states &= ~CUnique;
2125
2126         ReleaseReadLock(&tvc->lock);
2127         afs_PutVCache(tvc);
2128         ObtainReadLock(&afs_xvcache);
2129     }
2130     /* if (tvc) */
2131     ReleaseReadLock(&afs_xvcache);
2132
2133     /* lookup the file */
2134     nfid = *afid;
2135     now = osi_Time();
2136     origCBs = afs_allCBs;       /* if anything changes, we don't have a cb */
2137     
2138     if (AFS_IS_DISCONNECTED) {
2139         printf("Network is down in afs_LookupVcache\n");
2140         code = ENETDOWN;
2141     } else 
2142         code =
2143             afs_RemoteLookup(&adp->f.fid, areq, aname, &nfid, &OutStatus, 
2144                              &CallBack, &serverp, &tsync);
2145
2146 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2147   loop2:
2148 #endif
2149
2150     ObtainSharedLock(&afs_xvcache, 6);
2151     tvc = afs_FindVCache(&nfid, &retry, DO_VLRU | IS_SLOCK/* no xstats now */ );
2152     if (tvc && retry) {
2153 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2154         ReleaseSharedLock(&afs_xvcache);
2155         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
2156         goto loop2;
2157 #endif
2158     }
2159
2160     if (!tvc) {
2161         /* no cache entry, better grab one */
2162         UpgradeSToWLock(&afs_xvcache, 22);
2163         tvc = afs_NewVCache(&nfid, serverp);
2164         newvcache = 1;
2165         ConvertWToSLock(&afs_xvcache);
2166         if (!tvc)
2167         {
2168                 ReleaseSharedLock(&afs_xvcache);
2169                 return NULL;
2170         }
2171     }
2172
2173     ReleaseSharedLock(&afs_xvcache);
2174     ObtainWriteLock(&tvc->lock, 55);
2175
2176     /* It is always appropriate to throw away all the access rights? */
2177     afs_FreeAllAxs(&(tvc->Access));
2178     tvp = afs_GetVolume(afid, areq, READ_LOCK); /* copy useful per-vol info */
2179     if (tvp) {
2180         if ((tvp->states & VForeign)) {
2181             if (newvcache)
2182                 tvc->f.states |= CForeign;
2183             if (newvcache && (tvp->rootVnode == afid->Fid.Vnode)
2184                 && (tvp->rootUnique == afid->Fid.Unique))
2185                 tvc->mvstat = 2;
2186         }
2187         if (tvp->states & VRO)
2188             tvc->f.states |= CRO;
2189         if (tvp->states & VBackup)
2190             tvc->f.states |= CBackup;
2191         /* now copy ".." entry back out of volume structure, if necessary */
2192         if (tvc->mvstat == 2 && tvp->dotdot.Fid.Volume != 0) {
2193             if (!tvc->mvid)
2194                 tvc->mvid = (struct VenusFid *)
2195                     osi_AllocSmallSpace(sizeof(struct VenusFid));
2196             *tvc->mvid = tvp->dotdot;
2197         }
2198     }
2199
2200     if (code) {
2201         ObtainWriteLock(&afs_xcbhash, 465);
2202         afs_DequeueCallback(tvc);
2203         tvc->f.states &= ~(CStatd | CUnique);
2204         ReleaseWriteLock(&afs_xcbhash);
2205         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2206             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2207         if (tvp)
2208             afs_PutVolume(tvp, READ_LOCK);
2209         ReleaseWriteLock(&tvc->lock);
2210         afs_PutVCache(tvc);
2211         return NULL;
2212     }
2213
2214     ObtainWriteLock(&afs_xcbhash, 466);
2215     if (origCBs == afs_allCBs) {
2216         if (CallBack.ExpirationTime) {
2217             tvc->callback = serverp;
2218             tvc->cbExpires = CallBack.ExpirationTime + now;
2219             tvc->f.states |= CStatd | CUnique;
2220             tvc->f.states &= ~CBulkFetching;
2221             afs_QueueCallback(tvc, CBHash(CallBack.ExpirationTime), tvp);
2222         } else if (tvc->f.states & CRO) {
2223             /* adapt gives us an hour. */
2224             tvc->cbExpires = 3600 + osi_Time();
2225              /*XXX*/ tvc->f.states |= CStatd | CUnique;
2226             tvc->f.states &= ~CBulkFetching;
2227             afs_QueueCallback(tvc, CBHash(3600), tvp);
2228         } else {
2229             tvc->callback = NULL;
2230             afs_DequeueCallback(tvc);
2231             tvc->f.states &= ~(CStatd | CUnique);
2232             if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2233                 osi_dnlc_purgedp(tvc);  /* if it (could be) a directory */
2234         }
2235     } else {
2236         afs_DequeueCallback(tvc);
2237         tvc->f.states &= ~CStatd;
2238         tvc->f.states &= ~CUnique;
2239         tvc->callback = NULL;
2240         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2241             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2242     }
2243     ReleaseWriteLock(&afs_xcbhash);
2244     if (tvp)
2245         afs_PutVolume(tvp, READ_LOCK);
2246     afs_ProcessFS(tvc, &OutStatus, areq);
2247
2248     ReleaseWriteLock(&tvc->lock);
2249     return tvc;
2250
2251 }
2252
2253 struct vcache *
2254 afs_GetRootVCache(struct VenusFid *afid, struct vrequest *areq,
2255                   afs_int32 * cached, struct volume *tvolp)
2256 {
2257     afs_int32 code = 0, i, newvcache = 0, haveStatus = 0;
2258     afs_int32 getNewFid = 0;
2259     afs_uint32 start;
2260     struct VenusFid nfid;
2261     register struct vcache *tvc;
2262     struct server *serverp = 0;
2263     struct AFSFetchStatus OutStatus;
2264     struct AFSCallBack CallBack;
2265     struct AFSVolSync tsync;
2266     int origCBs = 0;
2267 #ifdef AFS_DARWIN80_ENV
2268     vnode_t tvp;
2269 #endif
2270
2271     start = osi_Time();
2272
2273   newmtpt:
2274     if (!tvolp->rootVnode || getNewFid) {
2275         struct VenusFid tfid;
2276
2277         tfid = *afid;
2278         tfid.Fid.Vnode = 0;     /* Means get rootfid of volume */
2279         origCBs = afs_allCBs;   /* ignore InitCallBackState */
2280         code =
2281             afs_RemoteLookup(&tfid, areq, NULL, &nfid, &OutStatus, &CallBack,
2282                              &serverp, &tsync);
2283         if (code) {
2284             return NULL;
2285         }
2286 /*      ReleaseReadLock(&tvolp->lock);           */
2287         ObtainWriteLock(&tvolp->lock, 56);
2288         tvolp->rootVnode = afid->Fid.Vnode = nfid.Fid.Vnode;
2289         tvolp->rootUnique = afid->Fid.Unique = nfid.Fid.Unique;
2290         ReleaseWriteLock(&tvolp->lock);
2291 /*      ObtainReadLock(&tvolp->lock);*/
2292         haveStatus = 1;
2293     } else {
2294         afid->Fid.Vnode = tvolp->rootVnode;
2295         afid->Fid.Unique = tvolp->rootUnique;
2296     }
2297
2298  rootvc_loop:
2299     ObtainSharedLock(&afs_xvcache, 7);
2300     i = VCHash(afid);
2301     for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2302         if (!FidCmp(&(tvc->f.fid), afid)) {
2303             if (tvc->f.states & CVInit) {
2304                 ReleaseSharedLock(&afs_xvcache);
2305                 afs_osi_Sleep(&tvc->f.states);
2306                 goto rootvc_loop;
2307             }
2308 #ifdef AFS_DARWIN80_ENV
2309             if (tvc->f.states & CDeadVnode) {
2310                 ReleaseSharedLock(&afs_xvcache);
2311                 afs_osi_Sleep(&tvc->f.states);
2312                 goto rootvc_loop;
2313             }
2314             tvp = AFSTOV(tvc);
2315             if (vnode_get(tvp))       /* this bumps ref count */
2316                 continue;
2317             if (vnode_ref(tvp)) {
2318                 AFS_GUNLOCK();
2319                 /* AFSTOV(tvc) may be NULL */
2320                 vnode_put(tvp);
2321                 AFS_GLOCK();
2322                 continue;
2323             }
2324 #endif
2325             break;
2326         }
2327     }
2328
2329     if (!haveStatus && (!tvc || !(tvc->f.states & CStatd))) {
2330         /* Mount point no longer stat'd or unknown. FID may have changed. */
2331         getNewFid = 1;
2332         ReleaseSharedLock(&afs_xvcache);
2333 #ifdef AFS_DARWIN80_ENV
2334         if (tvc) {
2335             AFS_GUNLOCK();
2336             vnode_put(AFSTOV(tvc));
2337             vnode_rele(AFSTOV(tvc));
2338             AFS_GLOCK();
2339         }
2340 #endif
2341         tvc = NULL;
2342         goto newmtpt;
2343     }
2344
2345     if (!tvc) {
2346         UpgradeSToWLock(&afs_xvcache, 23);
2347         /* no cache entry, better grab one */
2348         tvc = afs_NewVCache(afid, NULL);
2349         if (!tvc)
2350         {
2351                 ReleaseWriteLock(&afs_xvcache);
2352                 return NULL;
2353         }
2354         newvcache = 1;
2355         afs_stats_cmperf.vcacheMisses++;
2356     } else {
2357         if (cached)
2358             *cached = 1;
2359         afs_stats_cmperf.vcacheHits++;
2360 #if     defined(AFS_DARWIN80_ENV)
2361         /* we already bumped the ref count in the for loop above */
2362 #else /* AFS_DARWIN80_ENV */
2363         osi_vnhold(tvc, 0);
2364 #endif
2365         UpgradeSToWLock(&afs_xvcache, 24);
2366         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2367             refpanic("GRVC VLRU inconsistent0");
2368         }
2369         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2370             refpanic("GRVC VLRU inconsistent1");
2371         }
2372         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2373             refpanic("GRVC VLRU inconsistent2");
2374         }
2375         QRemove(&tvc->vlruq);   /* move to lruq head */
2376         QAdd(&VLRU, &tvc->vlruq);
2377         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2378             refpanic("GRVC VLRU inconsistent3");
2379         }
2380         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2381             refpanic("GRVC VLRU inconsistent4");
2382         }
2383         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2384             refpanic("GRVC VLRU inconsistent5");
2385         }
2386         vcachegen++;
2387     }
2388
2389     ReleaseWriteLock(&afs_xvcache);
2390
2391     if (tvc->f.states & CStatd) {
2392         return tvc;
2393     } else {
2394
2395         ObtainReadLock(&tvc->lock);
2396         tvc->f.states &= ~CUnique;
2397         tvc->callback = NULL;   /* redundant, perhaps */
2398         ReleaseReadLock(&tvc->lock);
2399     }
2400
2401     ObtainWriteLock(&tvc->lock, 57);
2402
2403     /* It is always appropriate to throw away all the access rights? */
2404     afs_FreeAllAxs(&(tvc->Access));
2405
2406     if (newvcache)
2407         tvc->f.states |= CForeign;
2408     if (tvolp->states & VRO)
2409         tvc->f.states |= CRO;
2410     if (tvolp->states & VBackup)
2411         tvc->f.states |= CBackup;
2412     /* now copy ".." entry back out of volume structure, if necessary */
2413     if (newvcache && (tvolp->rootVnode == afid->Fid.Vnode)
2414         && (tvolp->rootUnique == afid->Fid.Unique)) {
2415         tvc->mvstat = 2;
2416     }
2417     if (tvc->mvstat == 2 && tvolp->dotdot.Fid.Volume != 0) {
2418         if (!tvc->mvid)
2419             tvc->mvid = (struct VenusFid *)
2420                 osi_AllocSmallSpace(sizeof(struct VenusFid));
2421         *tvc->mvid = tvolp->dotdot;
2422     }
2423
2424     /* stat the file */
2425     afs_RemoveVCB(afid);
2426
2427     if (!haveStatus) {
2428         struct VenusFid tfid;
2429
2430         tfid = *afid;
2431         tfid.Fid.Vnode = 0;     /* Means get rootfid of volume */
2432         origCBs = afs_allCBs;   /* ignore InitCallBackState */
2433         code =
2434             afs_RemoteLookup(&tfid, areq, NULL, &nfid, &OutStatus, &CallBack,
2435                              &serverp, &tsync);
2436     }
2437
2438     if (code) {
2439         ObtainWriteLock(&afs_xcbhash, 467);
2440         afs_DequeueCallback(tvc);
2441         tvc->callback = NULL;
2442         tvc->f.states &= ~(CStatd | CUnique);
2443         ReleaseWriteLock(&afs_xcbhash);
2444         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2445             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2446         ReleaseWriteLock(&tvc->lock);
2447         afs_PutVCache(tvc);
2448         return NULL;
2449     }
2450
2451     ObtainWriteLock(&afs_xcbhash, 468);
2452     if (origCBs == afs_allCBs) {
2453         tvc->f.states |= CTruth;
2454         tvc->callback = serverp;
2455         if (CallBack.ExpirationTime != 0) {
2456             tvc->cbExpires = CallBack.ExpirationTime + start;
2457             tvc->f.states |= CStatd;
2458             tvc->f.states &= ~CBulkFetching;
2459             afs_QueueCallback(tvc, CBHash(CallBack.ExpirationTime), tvolp);
2460         } else if (tvc->f.states & CRO) {
2461             /* adapt gives us an hour. */
2462             tvc->cbExpires = 3600 + osi_Time();
2463              /*XXX*/ tvc->f.states |= CStatd;
2464             tvc->f.states &= ~CBulkFetching;
2465             afs_QueueCallback(tvc, CBHash(3600), tvolp);
2466         }
2467     } else {
2468         afs_DequeueCallback(tvc);
2469         tvc->callback = NULL;
2470         tvc->f.states &= ~(CStatd | CUnique);
2471         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2472             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2473     }
2474     ReleaseWriteLock(&afs_xcbhash);
2475     afs_ProcessFS(tvc, &OutStatus, areq);
2476
2477     ReleaseWriteLock(&tvc->lock);
2478     return tvc;
2479 }
2480
2481
2482 /*!
2483  * Update callback status and (sometimes) attributes of a vnode.
2484  * Called after doing a fetch status RPC. Whilst disconnected, attributes
2485  * shouldn't be written to the vcache here.
2486  *
2487  * \param avc
2488  * \param afid
2489  * \param areq
2490  * \param Outsp Server status after rpc call.
2491  * \param acb Callback for this vnode.
2492  *
2493  * \note The vcache must be write locked.
2494  */
2495 void
2496 afs_UpdateStatus(struct vcache *avc,
2497                         struct VenusFid *afid,
2498                         struct vrequest *areq,
2499                         struct AFSFetchStatus *Outsp,
2500                         struct AFSCallBack *acb,
2501                         afs_uint32 start)
2502 {
2503     struct volume *volp;
2504
2505     if (!AFS_IN_SYNC)
2506         /* Dont write status in vcache if resyncing after a disconnection. */
2507         afs_ProcessFS(avc, Outsp, areq);
2508
2509     volp = afs_GetVolume(afid, areq, READ_LOCK);
2510     ObtainWriteLock(&afs_xcbhash, 469);
2511     avc->f.states |= CTruth;
2512     if (avc->callback /* check for race */ ) {
2513         if (acb->ExpirationTime != 0) {
2514             avc->cbExpires = acb->ExpirationTime + start;
2515             avc->f.states |= CStatd;
2516             avc->f.states &= ~CBulkFetching;
2517             afs_QueueCallback(avc, CBHash(acb->ExpirationTime), volp);
2518         } else if (avc->f.states & CRO) {
2519             /* ordinary callback on a read-only volume -- AFS 3.2 style */
2520             avc->cbExpires = 3600 + start;
2521             avc->f.states |= CStatd;
2522             avc->f.states &= ~CBulkFetching;
2523             afs_QueueCallback(avc, CBHash(3600), volp);
2524         } else {
2525             afs_DequeueCallback(avc);
2526             avc->callback = NULL;
2527             avc->f.states &= ~(CStatd | CUnique);
2528             if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
2529                 osi_dnlc_purgedp(avc);  /* if it (could be) a directory */
2530         }
2531     } else {
2532         afs_DequeueCallback(avc);
2533         avc->callback = NULL;
2534         avc->f.states &= ~(CStatd | CUnique);
2535         if ((avc->f.states & CForeign) || (avc->f.fid.Fid.Vnode & 1))
2536             osi_dnlc_purgedp(avc);      /* if it (could be) a directory */
2537     }
2538     ReleaseWriteLock(&afs_xcbhash);
2539     if (volp)
2540         afs_PutVolume(volp, READ_LOCK);
2541 }
2542
2543 /*!
2544  * Must be called with avc write-locked
2545  * don't absolutely have to invalidate the hint unless the dv has
2546  * changed, but be sure to get it right else there will be consistency bugs.
2547  */
2548 afs_int32
2549 afs_FetchStatus(struct vcache * avc, struct VenusFid * afid,
2550                 struct vrequest * areq, struct AFSFetchStatus * Outsp)
2551 {
2552     int code;
2553     afs_uint32 start = 0;
2554     register struct afs_conn *tc;
2555     struct AFSCallBack CallBack;
2556     struct AFSVolSync tsync;
2557     XSTATS_DECLS;
2558     do {
2559         tc = afs_Conn(afid, areq, SHARED_LOCK);
2560         avc->dchint = NULL;     /* invalidate hints */
2561         if (tc) {
2562             avc->callback = tc->srvr->server;
2563             start = osi_Time();
2564             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHSTATUS);
2565             RX_AFS_GUNLOCK();
2566             code =
2567                 RXAFS_FetchStatus(tc->id, (struct AFSFid *)&afid->Fid, Outsp,
2568                                   &CallBack, &tsync);
2569             RX_AFS_GLOCK();
2570
2571             XSTATS_END_TIME;
2572
2573         } else
2574             code = -1;
2575     } while (afs_Analyze
2576              (tc, code, afid, areq, AFS_STATS_FS_RPCIDX_FETCHSTATUS,
2577               SHARED_LOCK, NULL));
2578
2579     if (!code) {
2580         afs_UpdateStatus(avc, afid, areq, Outsp, &CallBack, start);
2581     } else {
2582         /* used to undo the local callback, but that's too extreme.
2583          * There are plenty of good reasons that fetchstatus might return
2584          * an error, such as EPERM.  If we have the vnode cached, statd,
2585          * with callback, might as well keep track of the fact that we
2586          * don't have access...
2587          */
2588         if (code == EPERM || code == EACCES) {
2589             struct axscache *ac;
2590             if (avc->Access && (ac = afs_FindAxs(avc->Access, areq->uid)))
2591                 ac->axess = 0;
2592             else                /* not found, add a new one if possible */
2593                 afs_AddAxs(avc->Access, areq->uid, 0);
2594         }
2595     }
2596     return code;
2597 }
2598
2599 #if 0
2600 /*
2601  * afs_StuffVcache
2602  *
2603  * Description:
2604  *      Stuff some information into the vcache for the given file.
2605  *
2606  * Parameters:
2607  *      afid      : File in question.
2608  *      OutStatus : Fetch status on the file.
2609  *      CallBack  : Callback info.
2610  *      tc        : RPC connection involved.
2611  *      areq      : vrequest involved.
2612  *
2613  * Environment:
2614  *      Nothing interesting.
2615  */
2616 void
2617 afs_StuffVcache(register struct VenusFid *afid,
2618                 struct AFSFetchStatus *OutStatus,
2619                 struct AFSCallBack *CallBack, register struct afs_conn *tc,
2620                 struct vrequest *areq)
2621 {
2622     register afs_int32 code, i, newvcache = 0;
2623     register struct vcache *tvc;
2624     struct AFSVolSync tsync;
2625     struct volume *tvp;
2626     struct axscache *ac;
2627     afs_int32 retry;
2628
2629     AFS_STATCNT(afs_StuffVcache);
2630 #ifdef IFS_VCACHECOUNT
2631     ifs_gvcachecall++;
2632 #endif
2633
2634   loop:
2635     ObtainSharedLock(&afs_xvcache, 8);
2636
2637     tvc = afs_FindVCache(afid, &retry, DO_VLRU| IS_SLOCK /* no stats */ );
2638     if (tvc && retry) {
2639 #if     defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
2640         ReleaseSharedLock(&afs_xvcache);
2641         spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
2642         goto loop;
2643 #endif
2644     }
2645
2646     if (!tvc) {
2647         /* no cache entry, better grab one */
2648         UpgradeSToWLock(&afs_xvcache, 25);
2649         tvc = afs_NewVCache(afid, NULL);
2650         newvcache = 1;
2651         ConvertWToSLock(&afs_xvcache);
2652         if (!tvc)
2653         {
2654                 ReleaseSharedLock(&afs_xvcache);
2655                 return NULL;
2656         }
2657     }
2658
2659     ReleaseSharedLock(&afs_xvcache);
2660     ObtainWriteLock(&tvc->lock, 58);
2661
2662     tvc->f.states &= ~CStatd;
2663     if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2664         osi_dnlc_purgedp(tvc);  /* if it (could be) a directory */
2665
2666     /* Is it always appropriate to throw away all the access rights? */
2667     afs_FreeAllAxs(&(tvc->Access));
2668
2669     /*Copy useful per-volume info */
2670     tvp = afs_GetVolume(afid, areq, READ_LOCK);
2671     if (tvp) {
2672         if (newvcache && (tvp->states & VForeign))
2673             tvc->f.states |= CForeign;
2674         if (tvp->states & VRO)
2675             tvc->f.states |= CRO;
2676         if (tvp->states & VBackup)
2677             tvc->f.states |= CBackup;
2678         /*
2679          * Now, copy ".." entry back out of volume structure, if
2680          * necessary
2681          */
2682         if (tvc->mvstat == 2 && tvp->dotdot.Fid.Volume != 0) {
2683             if (!tvc->mvid)
2684                 tvc->mvid = (struct VenusFid *)
2685                     osi_AllocSmallSpace(sizeof(struct VenusFid));
2686             *tvc->mvid = tvp->dotdot;
2687         }
2688     }
2689     /* store the stat on the file */
2690     afs_RemoveVCB(afid);
2691     afs_ProcessFS(tvc, OutStatus, areq);
2692     tvc->callback = tc->srvr->server;
2693
2694     /* we use osi_Time twice below.  Ideally, we would use the time at which
2695      * the FetchStatus call began, instead, but we don't have it here.  So we
2696      * make do with "now".  In the CRO case, it doesn't really matter. In
2697      * the other case, we hope that the difference between "now" and when the
2698      * call actually began execution on the server won't be larger than the
2699      * padding which the server keeps.  Subtract 1 second anyway, to be on
2700      * the safe side.  Can't subtract more because we don't know how big
2701      * ExpirationTime is.  Possible consistency problems may arise if the call
2702      * timeout period becomes longer than the server's expiration padding.  */
2703     ObtainWriteLock(&afs_xcbhash, 470);
2704     if (CallBack->ExpirationTime != 0) {
2705         tvc->cbExpires = CallBack->ExpirationTime + osi_Time() - 1;
2706         tvc->f.states |= CStatd;
2707         tvc->f.states &= ~CBulkFetching;
2708         afs_QueueCallback(tvc, CBHash(CallBack->ExpirationTime), tvp);
2709     } else if (tvc->f.states & CRO) {
2710         /* old-fashioned AFS 3.2 style */
2711         tvc->cbExpires = 3600 + osi_Time();
2712          /*XXX*/ tvc->f.states |= CStatd;
2713         tvc->f.states &= ~CBulkFetching;
2714         afs_QueueCallback(tvc, CBHash(3600), tvp);
2715     } else {
2716         afs_DequeueCallback(tvc);
2717         tvc->callback = NULL;
2718         tvc->f.states &= ~(CStatd | CUnique);
2719         if ((tvc->f.states & CForeign) || (tvc->f.fid.Fid.Vnode & 1))
2720             osi_dnlc_purgedp(tvc);      /* if it (could be) a directory */
2721     }
2722     ReleaseWriteLock(&afs_xcbhash);
2723     if (tvp)
2724         afs_PutVolume(tvp, READ_LOCK);
2725
2726     /* look in per-pag cache */
2727     if (tvc->Access && (ac = afs_FindAxs(tvc->Access, areq->uid)))
2728         ac->axess = OutStatus->CallerAccess;    /* substitute pags */
2729     else                        /* not found, add a new one if possible */
2730         afs_AddAxs(tvc->Access, areq->uid, OutStatus->CallerAccess);
2731
2732     ReleaseWriteLock(&tvc->lock);
2733     afs_Trace4(afs_iclSetp, CM_TRACE_STUFFVCACHE, ICL_TYPE_POINTER, tvc,
2734                ICL_TYPE_POINTER, tvc->callback, ICL_TYPE_INT32,
2735                tvc->cbExpires, ICL_TYPE_INT32, tvc->cbExpires - osi_Time());
2736     /*
2737      * Release ref count... hope this guy stays around...
2738      */
2739     afs_PutVCache(tvc);
2740 }                               /*afs_StuffVcache */
2741 #endif
2742
2743 /*!
2744  * Decrements the reference count on a cache entry.
2745  *
2746  * \param avc Pointer to the cache entry to decrement.
2747  *
2748  * \note Environment: Nothing interesting.
2749  */
2750 void
2751 afs_PutVCache(register struct vcache *avc)
2752 {
2753     AFS_STATCNT(afs_PutVCache);
2754 #ifdef AFS_DARWIN80_ENV
2755     vnode_put(AFSTOV(avc));
2756     AFS_FAST_RELE(avc);
2757 #else
2758     /*
2759      * Can we use a read lock here?
2760      */
2761     ObtainReadLock(&afs_xvcache);
2762     AFS_FAST_RELE(avc);
2763     ReleaseReadLock(&afs_xvcache);
2764 #endif
2765 }                               /*afs_PutVCache */
2766
2767
2768 /*!
2769  * Reset a vcache entry, so local contents are ignored, and the
2770  * server will be reconsulted next time the vcache is used
2771  * 
2772  * \param avc Pointer to the cache entry to reset
2773  * \param acred 
2774  *
2775  * \note avc must be write locked on entry
2776  */
2777 void
2778 afs_ResetVCache(struct vcache *avc, afs_ucred_t *acred) {
2779     ObtainWriteLock(&afs_xcbhash, 456);
2780     afs_DequeueCallback(avc);
2781     avc->f.states &= ~(CStatd | CDirty);    /* next reference will re-stat */
2782     ReleaseWriteLock(&afs_xcbhash);
2783     /* now find the disk cache entries */
2784     afs_TryToSmush(avc, acred, 1);
2785     osi_dnlc_purgedp(avc);
2786     if (avc->linkData && !(avc->f.states & CCore)) {
2787         afs_osi_Free(avc->linkData, strlen(avc->linkData) + 1);
2788         avc->linkData = NULL;
2789     }
2790 }
2791
2792 /*!
2793  * Sleepa when searching for a vcache. Releases all the pending locks,
2794  * sleeps then obtains the previously released locks.
2795  *
2796  * \param vcache Enter sleep state.
2797  * \param flag Determines what locks to use.
2798  *
2799  * \return 
2800  */
2801 static void findvc_sleep(struct vcache *avc, int flag) {
2802     if (flag & IS_SLOCK) {
2803             ReleaseSharedLock(&afs_xvcache);
2804     } else {
2805         if (flag & IS_WLOCK) {
2806             ReleaseWriteLock(&afs_xvcache);
2807         } else {
2808             ReleaseReadLock(&afs_xvcache);
2809         }
2810     }
2811     afs_osi_Sleep(&avc->f.states);
2812     if (flag & IS_SLOCK) {
2813             ObtainSharedLock(&afs_xvcache, 341);
2814     } else {
2815         if (flag & IS_WLOCK) {
2816             ObtainWriteLock(&afs_xvcache, 343);
2817         } else {
2818             ObtainReadLock(&afs_xvcache);
2819         }
2820     }
2821 }
2822 /*!
2823  * Find a vcache entry given a fid.
2824  *
2825  * \param afid Pointer to the fid whose cache entry we desire.
2826  * \param retry (SGI-specific) tell the caller to drop the lock on xvcache,
2827  *  unlock the vnode, and try again.
2828  * \param flag Bit 1 to specify whether to compute hit statistics.  Not
2829  *  set if FindVCache is called as part of internal bookkeeping.
2830  *
2831  * \note Environment: Must be called with the afs_xvcache lock at least held at
2832  * the read level.  In order to do the VLRU adjustment, the xvcache lock
2833  * must be shared-- we upgrade it here.
2834  */
2835
2836 struct vcache *
2837 afs_FindVCache(struct VenusFid *afid, afs_int32 * retry, afs_int32 flag)
2838 {
2839
2840     register struct vcache *tvc;
2841     afs_int32 i;
2842 #ifdef AFS_DARWIN80_ENV
2843     vnode_t tvp;
2844 #endif
2845
2846     AFS_STATCNT(afs_FindVCache);
2847
2848  findloop:
2849     i = VCHash(afid);
2850     for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2851         if (FidMatches(afid, tvc)) {
2852             if (tvc->f.states & CVInit) {
2853                 findvc_sleep(tvc, flag);
2854                 goto findloop;
2855             }
2856 #ifdef  AFS_DARWIN80_ENV
2857             if (tvc->f.states & CDeadVnode) {
2858                 findvc_sleep(tvc, flag);
2859                 goto findloop;
2860             }
2861             tvp = AFSTOV(tvc);
2862             if (vnode_get(tvp))
2863                 continue;
2864             if (vnode_ref(tvp)) {
2865                 AFS_GUNLOCK();
2866                 /* AFSTOV(tvc) may be NULL */
2867                 vnode_put(tvp);
2868                 AFS_GLOCK();
2869                 continue;
2870             }
2871 #endif
2872             break;
2873         }
2874     }
2875
2876     /* should I have a read lock on the vnode here? */
2877     if (tvc) {
2878         if (retry)
2879             *retry = 0;
2880 #if !defined(AFS_DARWIN80_ENV)
2881         osi_vnhold(tvc, retry); /* already held, above */
2882         if (retry && *retry)
2883             return 0;
2884 #endif
2885 #if defined(AFS_DARWIN_ENV) && !defined(AFS_DARWIN80_ENV)
2886         tvc->f.states |= CUBCinit;
2887         AFS_GUNLOCK();
2888         if (UBCINFOMISSING(AFSTOV(tvc)) ||
2889             UBCINFORECLAIMED(AFSTOV(tvc))) {
2890           ubc_info_init(AFSTOV(tvc));
2891         }
2892         AFS_GLOCK();
2893         tvc->f.states &= ~CUBCinit;
2894 #endif
2895         /*
2896          * only move to front of vlru if we have proper vcache locking)
2897          */
2898         if (flag & DO_VLRU) {
2899             if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2900                 refpanic("FindVC VLRU inconsistent1");
2901             }
2902             if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2903                 refpanic("FindVC VLRU inconsistent1");
2904             }
2905             if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2906                 refpanic("FindVC VLRU inconsistent2");
2907             }
2908             UpgradeSToWLock(&afs_xvcache, 26);
2909             QRemove(&tvc->vlruq);
2910             QAdd(&VLRU, &tvc->vlruq);
2911             ConvertWToSLock(&afs_xvcache);
2912             if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
2913                 refpanic("FindVC VLRU inconsistent1");
2914             }
2915             if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
2916                 refpanic("FindVC VLRU inconsistent2");
2917             }
2918             if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
2919                 refpanic("FindVC VLRU inconsistent3");
2920             }
2921         }
2922         vcachegen++;
2923     }
2924
2925     if (flag & DO_STATS) {
2926         if (tvc)
2927             afs_stats_cmperf.vcacheHits++;
2928         else
2929             afs_stats_cmperf.vcacheMisses++;
2930         if (afs_IsPrimaryCellNum(afid->Cell))
2931             afs_stats_cmperf.vlocalAccesses++;
2932         else
2933             afs_stats_cmperf.vremoteAccesses++;
2934     }
2935     return tvc;
2936 }                               /*afs_FindVCache */
2937
2938 /*!
2939  * Find a vcache entry given a fid. Does a wildcard match on what we
2940  * have for the fid. If more than one entry, don't return anything.
2941  *
2942  * \param avcp Fill in pointer if we found one and only one.
2943  * \param afid Pointer to the fid whose cache entry we desire.
2944  * \param retry (SGI-specific) tell the caller to drop the lock on xvcache,
2945  *             unlock the vnode, and try again.
2946  * \param flags bit 1 to specify whether to compute hit statistics.  Not
2947  *             set if FindVCache is called as part of internal bookkeeping.
2948  *
2949  * \note Environment: Must be called with the afs_xvcache lock at least held at
2950  *  the read level.  In order to do the VLRU adjustment, the xvcache lock
2951  *  must be shared-- we upgrade it here.
2952  *
2953  * \return Number of matches found.
2954  */
2955
2956 int afs_duplicate_nfs_fids = 0;
2957
2958 afs_int32
2959 afs_NFSFindVCache(struct vcache **avcp, struct VenusFid *afid)
2960 {
2961     register struct vcache *tvc;
2962     afs_int32 i;
2963     afs_int32 count = 0;
2964     struct vcache *found_tvc = NULL;
2965 #ifdef AFS_DARWIN80_ENV
2966     vnode_t tvp;
2967 #endif
2968
2969     AFS_STATCNT(afs_FindVCache);
2970
2971   loop:
2972
2973     ObtainSharedLock(&afs_xvcache, 331);
2974
2975     i = VCHash(afid);
2976     for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
2977         /* Match only on what we have.... */
2978         if (((tvc->f.fid.Fid.Vnode & 0xffff) == afid->Fid.Vnode)
2979             && (tvc->f.fid.Fid.Volume == afid->Fid.Volume)
2980             && ((tvc->f.fid.Fid.Unique & 0xffffff) == afid->Fid.Unique)
2981             && (tvc->f.fid.Cell == afid->Cell)) {
2982             if (tvc->f.states & CVInit) {
2983                 ReleaseSharedLock(&afs_xvcache);
2984                 afs_osi_Sleep(&tvc->f.states);
2985                 goto loop;
2986             }
2987 #ifdef  AFS_DARWIN80_ENV
2988             if (tvc->f.states & CDeadVnode) {
2989                 ReleaseSharedLock(&afs_xvcache);
2990                 afs_osi_Sleep(&tvc->f.states);
2991                 goto loop;
2992             }
2993             tvp = AFSTOV(tvc);
2994             if (vnode_get(tvp)) {
2995                 /* This vnode no longer exists. */
2996                 continue;
2997             }
2998             if (vnode_ref(tvp)) {
2999                 /* This vnode no longer exists. */
3000                 AFS_GUNLOCK();
3001                 /* AFSTOV(tvc) may be NULL */
3002                 vnode_put(tvp);
3003                 AFS_GLOCK();
3004                 continue;
3005             }
3006 #endif /* AFS_DARWIN80_ENV */
3007             count++;
3008             if (found_tvc) {
3009                 /* Duplicates */
3010                 afs_duplicate_nfs_fids++;
3011                 ReleaseSharedLock(&afs_xvcache);
3012 #ifdef AFS_DARWIN80_ENV
3013                 /* Drop our reference counts. */
3014                 vnode_put(AFSTOV(tvc));
3015                 vnode_put(AFSTOV(found_tvc));
3016 #endif
3017                 return count;
3018             }
3019             found_tvc = tvc;
3020         }
3021     }
3022
3023     tvc = found_tvc;
3024     /* should I have a read lock on the vnode here? */
3025     if (tvc) {
3026 #if defined(AFS_SGI_ENV) && !defined(AFS_SGI53_ENV)
3027         afs_int32 retry = 0;
3028         osi_vnhold(tvc, &retry);
3029         if (retry) {
3030             count = 0;
3031             found_tvc = (struct vcache *)0;
3032             ReleaseSharedLock(&afs_xvcache);
3033             spunlock_psema(tvc->v.v_lock, retry, &tvc->v.v_sync, PINOD);
3034             goto loop;
3035         }
3036 #else
3037         osi_vnhold(tvc, (int *)0);      /* already held, above */
3038 #endif
3039         /*
3040          * We obtained the xvcache lock above.
3041          */
3042         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
3043             refpanic("FindVC VLRU inconsistent1");
3044         }
3045         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
3046             refpanic("FindVC VLRU inconsistent1");
3047         }
3048         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
3049             refpanic("FindVC VLRU inconsistent2");
3050         }
3051         UpgradeSToWLock(&afs_xvcache, 568);
3052         QRemove(&tvc->vlruq);
3053         QAdd(&VLRU, &tvc->vlruq);
3054         ConvertWToSLock(&afs_xvcache);
3055         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
3056             refpanic("FindVC VLRU inconsistent1");
3057         }
3058         if (tvc->vlruq.next->prev != &(tvc->vlruq)) {
3059             refpanic("FindVC VLRU inconsistent2");
3060         }
3061         if (tvc->vlruq.prev->next != &(tvc->vlruq)) {
3062             refpanic("FindVC VLRU inconsistent3");
3063         }
3064     }
3065     vcachegen++;
3066
3067     if (tvc)
3068         afs_stats_cmperf.vcacheHits++;
3069     else
3070         afs_stats_cmperf.vcacheMisses++;
3071     if (afs_IsPrimaryCellNum(afid->Cell))
3072         afs_stats_cmperf.vlocalAccesses++;
3073     else
3074         afs_stats_cmperf.vremoteAccesses++;
3075
3076     *avcp = tvc;                /* May be null */
3077
3078     ReleaseSharedLock(&afs_xvcache);
3079     return (tvc ? 1 : 0);
3080
3081 }                               /*afs_NFSFindVCache */
3082
3083
3084
3085
3086 /*!
3087  * Initialize vcache related variables
3088  *
3089  * \param astatSize
3090  */
3091 void
3092 afs_vcacheInit(int astatSize)
3093 {
3094 #if !defined(AFS_LINUX22_ENV)
3095     register struct vcache *tvp;
3096 #endif
3097     int i;
3098 #if defined(AFS_LINUX22_ENV)
3099     if (!afs_maxvcount) {
3100         afs_maxvcount = astatSize;      /* no particular limit on linux? */
3101         if (astatSize < afs_maxvcount) {
3102             afs_maxvcount = astatSize;
3103         }
3104     }
3105 #else /* AFS_LINUX22_ENV */
3106     freeVCList = NULL;
3107 #endif
3108
3109     AFS_RWLOCK_INIT(&afs_xvcache, "afs_xvcache");
3110     LOCK_INIT(&afs_xvcb, "afs_xvcb");
3111
3112 #if !defined(AFS_LINUX22_ENV)
3113     /* Allocate and thread the struct vcache entries */
3114     tvp = (struct vcache *)afs_osi_Alloc(astatSize * sizeof(struct vcache));
3115     memset(tvp, 0, sizeof(struct vcache) * astatSize);
3116
3117     Initial_freeVCList = tvp;
3118     freeVCList = &(tvp[0]);
3119     for (i = 0; i < astatSize - 1; i++) {
3120         tvp[i].nextfree = &(tvp[i + 1]);
3121     }
3122     tvp[astatSize - 1].nextfree = NULL;
3123 # ifdef  KERNEL_HAVE_PIN
3124     pin((char *)tvp, astatSize * sizeof(struct vcache));        /* XXX */
3125 # endif
3126 #endif
3127
3128 #if defined(AFS_SGI_ENV)
3129     for (i = 0; i < astatSize; i++) {
3130         char name[METER_NAMSZ];
3131         struct vcache *tvc = &tvp[i];
3132
3133         tvc->v.v_number = ++afsvnumbers;
3134         tvc->vc_rwlockid = OSI_NO_LOCKID;
3135         initnsema(&tvc->vc_rwlock, 1,
3136                   makesname(name, "vrw", tvc->v.v_number));
3137 #ifndef AFS_SGI53_ENV
3138         initnsema(&tvc->v.v_sync, 0, makesname(name, "vsy", tvc->v.v_number));
3139 #endif
3140 #ifndef AFS_SGI62_ENV
3141         initnlock(&tvc->v.v_lock, makesname(name, "vlk", tvc->v.v_number));
3142 #endif /* AFS_SGI62_ENV */
3143     }
3144 #endif
3145     QInit(&VLRU);
3146     for(i = 0; i < VCSIZE; ++i)
3147         QInit(&afs_vhashTV[i]);
3148 }
3149
3150 /*!
3151  * Shutdown vcache.
3152  */
3153 void
3154 shutdown_vcache(void)
3155 {
3156     int i;
3157     struct afs_cbr *tsp;
3158     /*
3159      * XXX We may potentially miss some of the vcaches because if when
3160      * there are no free vcache entries and all the vcache entries are active
3161      * ones then we allocate an additional one - admittedly we almost never
3162      * had that occur.
3163      */
3164
3165     {
3166         register struct afs_q *tq, *uq = NULL;
3167         register struct vcache *tvc;
3168         for (tq = VLRU.prev; tq != &VLRU; tq = uq) {
3169             tvc = QTOV(tq);
3170             uq = QPrev(tq);
3171             if (tvc->mvid) {
3172                 osi_FreeSmallSpace(tvc->mvid);
3173                 tvc->mvid = (struct VenusFid *)0;
3174             }
3175 #ifdef  AFS_AIX_ENV
3176             aix_gnode_rele(AFSTOV(tvc));
3177 #endif
3178             if (tvc->linkData) {
3179                 afs_osi_Free(tvc->linkData, strlen(tvc->linkData) + 1);
3180                 tvc->linkData = 0;
3181             }
3182         }
3183         /*
3184          * Also free the remaining ones in the Cache
3185          */
3186         for (i = 0; i < VCSIZE; i++) {
3187             for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
3188                 if (tvc->mvid) {
3189                     osi_FreeSmallSpace(tvc->mvid);
3190                     tvc->mvid = (struct VenusFid *)0;
3191                 }
3192 #ifdef  AFS_AIX_ENV
3193                 if (tvc->v.v_gnode)
3194                     afs_osi_Free(tvc->v.v_gnode, sizeof(struct gnode));
3195 #ifdef  AFS_AIX32_ENV
3196                 if (tvc->segid) {
3197                     AFS_GUNLOCK();
3198                     vms_delete(tvc->segid);
3199                     AFS_GLOCK();
3200                     tvc->segid = tvc->vmh = NULL;
3201                     if (VREFCOUNT_GT(tvc,0))
3202                         osi_Panic("flushVcache: vm race");
3203                 }
3204                 if (tvc->credp) {
3205                     crfree(tvc->credp);
3206                     tvc->credp = NULL;
3207                 }
3208 #endif
3209 #endif
3210 #if     defined(AFS_SUN5_ENV)
3211                 if (tvc->credp) {
3212                     crfree(tvc->credp);
3213                     tvc->credp = NULL;
3214                 }
3215 #endif
3216                 if (tvc->linkData) {
3217                     afs_osi_Free(tvc->linkData, strlen(tvc->linkData) + 1);
3218                     tvc->linkData = 0;
3219                 }
3220
3221                 if (tvc->Access)
3222                     afs_FreeAllAxs(&(tvc->Access));
3223             }
3224             afs_vhashT[i] = 0;
3225         }
3226     }
3227     /*
3228      * Free any leftover callback queue
3229      */
3230     for (i = 0; i < afs_stats_cmperf.CallBackAlloced; i++) {
3231         tsp = afs_cbrHeads[i];
3232         afs_cbrHeads[i] = 0;
3233         afs_osi_Free((char *)tsp, AFS_NCBRS * sizeof(struct afs_cbr));
3234     }
3235     afs_cbrSpace = 0;
3236
3237 #if !defined(AFS_LINUX22_ENV)
3238     afs_osi_Free(Initial_freeVCList, afs_cacheStats * sizeof(struct vcache));
3239
3240 # ifdef  KERNEL_HAVE_PIN
3241     unpin(Initial_freeVCList, afs_cacheStats * sizeof(struct vcache));
3242 # endif
3243
3244     freeVCList = Initial_freeVCList = 0;
3245 #endif
3246
3247     AFS_RWLOCK_INIT(&afs_xvcache, "afs_xvcache");
3248     LOCK_INIT(&afs_xvcb, "afs_xvcb");
3249     QInit(&VLRU);
3250     for(i = 0; i < VCSIZE; ++i)
3251         QInit(&afs_vhashTV[i]);
3252 }
3253
3254 void
3255 afs_DisconGiveUpCallbacks(void) {
3256     int i;
3257     struct vcache *tvc;
3258     int nq=0;
3259             
3260     ObtainWriteLock(&afs_xvcache, 1002); /* XXX - should be a unique number */
3261     
3262     /* Somehow, walk the set of vcaches, with each one coming out as tvc */
3263     for (i = 0; i < VCSIZE; i++) {
3264         for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
3265             if (afs_QueueVCB(tvc)) {
3266                 tvc->callback = NULL;
3267                 nq++;
3268             }
3269         }
3270     }
3271
3272     ReleaseWriteLock(&afs_xvcache);
3273
3274     afs_FlushVCBs(1);
3275 }
3276
3277 /*!
3278  *
3279  * Clear the Statd flag from all vcaches
3280  *
3281  * This function removes the Statd flag from all vcaches. It's used by 
3282  * disconnected mode to tidy up during reconnection
3283  *
3284  */
3285 void
3286 afs_ClearAllStatdFlag(void) {
3287     int i;
3288     struct vcache *tvc;
3289    
3290     ObtainWriteLock(&afs_xvcache, 715);
3291
3292     for (i = 0; i < VCSIZE; i++) {
3293         for (tvc = afs_vhashT[i]; tvc; tvc = tvc->hnext) {
3294             tvc->f.states &= ~(CStatd|CUnique);
3295         }
3296     }
3297     ReleaseWriteLock(&afs_xvcache);
3298 }