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