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