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