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