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