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