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