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