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