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