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