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