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