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