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