e9d760a043953a1a30ee434c82b72c0422f85001
[openafs.git] / src / afs / VNOPS / afs_vnop_lookup.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_lookup
13  * EvalMountPoint
14  * afs_DoBulkStat
15  */
16
17 #include <afsconfig.h>
18 #include "afs/param.h"
19
20 RCSID
21     ("$Header$");
22
23 #include "afs/sysincludes.h"    /* Standard vendor system headers */
24 #include "afsincludes.h"        /* Afs-based standard headers */
25 #include "afs/afs_stats.h"      /* statistics */
26 #include "afs/afs_cbqueue.h"
27 #include "afs/nfsclient.h"
28 #include "afs/exporter.h"
29 #include "afs/afs_osidnlc.h"
30
31
32 extern struct DirEntry *afs_dir_GetBlob();
33
34 #ifdef AFS_LINUX22_ENV
35 extern struct inode_operations afs_symlink_iops, afs_dir_iops;
36 #endif
37
38
39 afs_int32 afs_bkvolpref = 0;
40 afs_int32 afs_bulkStatsDone;
41 static int bulkStatCounter = 0; /* counter for bulk stat seq. numbers */
42 int afs_fakestat_enable = 0;    /* 1: fakestat-all, 2: fakestat-crosscell */
43
44
45 /* this would be faster if it did comparison as int32word, but would be 
46  * dependant on byte-order and alignment, and I haven't figured out
47  * what "@sys" is in binary... */
48 #define AFS_EQ_ATSYS(name) (((name)[0]=='@')&&((name)[1]=='s')&&((name)[2]=='y')&&((name)[3]=='s')&&(!(name)[4]))
49
50 /* call under write lock, evaluate mvid field from a mt pt.
51  * avc is the vnode of the mount point object; must be write-locked.
52  * advc is the vnode of the containing directory (optional; if NULL and
53  *   EvalMountPoint succeeds, caller must initialize *avolpp->dotdot)
54  * avolpp is where we return a pointer to the volume named by the mount pt, if success
55  * areq is the identity of the caller.
56  *
57  * NOTE: this function returns a held volume structure in *volpp if it returns 0!
58  */
59 int
60 EvalMountPoint(register struct vcache *avc, struct vcache *advc,
61                struct volume **avolpp, register struct vrequest *areq)
62 {
63     afs_int32 code;
64     struct volume *tvp = 0;
65     struct VenusFid tfid;
66     struct cell *tcell;
67     char   *cpos, *volnamep;
68     char   type, *buf;
69     afs_int32  prefetch;          /* 1=>None  2=>RO  3=>BK */
70     afs_int32  mtptCell, assocCell, hac = 0;
71     afs_int32  samecell, roname, len;
72
73     AFS_STATCNT(EvalMountPoint);
74 #ifdef notdef
75     if (avc->mvid && (avc->states & CMValid))
76         return 0;               /* done while racing */
77 #endif
78     *avolpp = NULL;
79     code = afs_HandleLink(avc, areq);
80     if (code)
81         return code;
82
83     /* Determine which cell and volume the mointpoint goes to */
84     type = avc->linkData[0];    /* '#'=>Regular '%'=>RW */
85     cpos = afs_strchr(&avc->linkData[1], ':');  /* if cell name present */
86     if (cpos) {
87         volnamep = cpos + 1;
88         *cpos = 0;
89         tcell = afs_GetCellByName(&avc->linkData[1], READ_LOCK);
90         *cpos = ':';
91     } else {
92         volnamep = &avc->linkData[1];
93         tcell = afs_GetCell(avc->fid.Cell, READ_LOCK);
94     }
95     if (!tcell)
96         return ENODEV;
97
98     mtptCell = tcell->cellNum;  /* The cell for the mountpoint */
99     if (tcell->lcellp) {
100         hac = 1;                /* has associated cell */
101         assocCell = tcell->lcellp->cellNum;     /* The associated cell */
102     }
103     afs_PutCell(tcell, READ_LOCK);
104
105     /* Is volume name a "<n>.backup" or "<n>.readonly" name */
106     len = strlen(volnamep);
107     roname = ((len > 9) && (strcmp(&volnamep[len - 9], ".readonly") == 0))
108         || ((len > 7) && (strcmp(&volnamep[len - 7], ".backup") == 0));
109
110     /* When we cross mountpoint, do we stay in the same cell */
111     samecell = (avc->fid.Cell == mtptCell) || (hac
112                                                && (avc->fid.Cell ==
113                                                    assocCell));
114
115     /* Decide whether to prefetch the BK, or RO.  Also means we want the BK or
116      * RO.
117      * If this is a regular mountpoint with a RW volume name
118      * - If BK preference is enabled AND we remain within the same cell AND
119      *   start from a BK volume, then we will want to prefetch the BK volume.
120      * - If we cross a cell boundary OR start from a RO volume, then we will
121      *   want to prefetch the RO volume.
122      */
123     if ((type == '#') && !roname) {
124        if (afs_bkvolpref && samecell && (avc->states & CBackup))
125            prefetch = 3; /* Prefetch the BK */
126        else if (!samecell || (avc->states & CRO))
127            prefetch = 2; /* Prefetch the RO */
128        else
129            prefetch = 1; /* Do not prefetch */
130     } else {
131        prefetch = 1; /* Do not prefetch */
132     }
133
134     /* Get the volume struct. Unless this volume name has ".readonly" or
135      * ".backup" in it, this will get the volume struct for the RW volume.
136      * The RO volume will be prefetched if requested (but not returned).
137      */
138     tvp = afs_GetVolumeByName(volnamep, mtptCell, prefetch, areq, WRITE_LOCK);
139
140     /* If no volume was found in this cell, try the associated linked cell */
141     if (!tvp && hac && areq->volumeError) {
142        tvp =
143             afs_GetVolumeByName(volnamep, assocCell, prefetch, areq,
144                                 WRITE_LOCK);
145     }
146
147     /* Still not found. If we are looking for the RO, then perhaps the RW 
148      * doesn't exist? Try adding ".readonly" to volname and look for that.
149      * Don't know why we do this. Would have still found it in above call - jpm.
150      */
151     if (!tvp && (prefetch == 2)) {
152         buf = (char *)osi_AllocSmallSpace(strlen(volnamep) + 10);
153
154         strcpy(buf, volnamep);
155         afs_strcat(buf, ".readonly");
156
157         tvp = afs_GetVolumeByName(buf, mtptCell, 1, areq, WRITE_LOCK);
158
159         /* Try the associated linked cell if failed */
160         if (!tvp && hac && areq->volumeError) {
161             tvp = afs_GetVolumeByName(buf, assocCell, 1, areq, WRITE_LOCK);
162         }
163         osi_FreeSmallSpace(buf);
164     }
165
166     if (!tvp)
167         return ENODEV;          /* Couldn't find the volume */
168
169     /* Don't cross mountpoint from a BK to a BK volume */
170     if ((avc->states & CBackup) && (tvp->states & VBackup)) {
171         afs_PutVolume(tvp, WRITE_LOCK);
172         return ENODEV;
173     }
174
175     /* If we want (prefetched) the BK and it exists, then drop the RW volume
176      * and get the BK.
177      * Otherwise, if we want (prefetched0 the RO and it exists, then drop the
178      * RW volume and get the RO.
179      * Otherwise, go with the RW.
180      */
181     if ((prefetch == 3) && tvp->backVol) {
182         tfid.Fid.Volume = tvp->backVol; /* remember BK volume */
183         tfid.Cell = tvp->cell;
184         afs_PutVolume(tvp, WRITE_LOCK); /* release old volume */
185         tvp = afs_GetVolume(&tfid, areq, WRITE_LOCK);   /* get the new one */
186         if (!tvp)
187             return ENODEV;      /* oops, can't do it */
188     } else if ((prefetch >= 2) && tvp->roVol) {
189         tfid.Fid.Volume = tvp->roVol;   /* remember RO volume */
190         tfid.Cell = tvp->cell;
191         afs_PutVolume(tvp, WRITE_LOCK); /* release old volume */
192         tvp = afs_GetVolume(&tfid, areq, WRITE_LOCK);   /* get the new one */
193         if (!tvp)
194            return ENODEV;       /* oops, can't do it */
195     }
196
197     if (avc->mvid == 0)
198         avc->mvid =
199             (struct VenusFid *)osi_AllocSmallSpace(sizeof(struct VenusFid));
200     avc->mvid->Cell = tvp->cell;
201     avc->mvid->Fid.Volume = tvp->volume;
202     avc->mvid->Fid.Vnode = 1;
203     avc->mvid->Fid.Unique = 1;
204     avc->states |= CMValid;
205
206     /* Used to: if the mount point is stored within a backup volume,
207      * then we should only update the parent pointer information if
208      * there's none already set, so as to avoid updating a volume's ..
209      * info with something in an OldFiles directory.
210      *
211      * Next two lines used to be under this if:
212      *
213      * if (!(avc->states & CBackup) || tvp->dotdot.Fid.Volume == 0)
214      *
215      * Now: update mount point back pointer on every call, so that we handle
216      * multiple mount points better.  This way, when du tries to go back
217      * via chddir(".."), it will end up exactly where it started, yet
218      * cd'ing via a new path to a volume will reset the ".." pointer
219      * to the new path.
220      */
221     tvp->mtpoint = avc->fid;    /* setup back pointer to mtpoint */
222     if (advc)
223         tvp->dotdot = advc->fid;
224
225     *avolpp = tvp;
226     return 0;
227 }
228
229 /*
230  * afs_InitFakeStat
231  *
232  * Must be called on an afs_fakestat_state object before calling
233  * afs_EvalFakeStat or afs_PutFakeStat.  Calling afs_PutFakeStat
234  * without calling afs_EvalFakeStat is legal, as long as this
235  * function is called.
236  */
237 void
238 afs_InitFakeStat(struct afs_fakestat_state *state)
239 {
240     if (!afs_fakestat_enable)
241         return;
242
243     state->valid = 1;
244     state->did_eval = 0;
245     state->need_release = 0;
246 }
247
248 /*
249  * afs_EvalFakeStat_int
250  *
251  * The actual implementation of afs_EvalFakeStat and afs_TryEvalFakeStat,
252  * which is called by those wrapper functions.
253  *
254  * Only issues RPCs if canblock is non-zero.
255  */
256 int
257 afs_EvalFakeStat_int(struct vcache **avcp, struct afs_fakestat_state *state,
258                      struct vrequest *areq, int canblock)
259 {
260     struct vcache *tvc, *root_vp;
261     struct volume *tvolp = NULL;
262     int code = 0;
263
264     if (!afs_fakestat_enable)
265         return 0;
266
267     osi_Assert(state->valid == 1);
268     osi_Assert(state->did_eval == 0);
269     state->did_eval = 1;
270
271     tvc = *avcp;
272     if (tvc->mvstat != 1)
273         return 0;
274
275     /* Is the call to VerifyVCache really necessary? */
276     code = afs_VerifyVCache(tvc, areq);
277     if (code)
278         goto done;
279     if (canblock) {
280         ObtainWriteLock(&tvc->lock, 599);
281         code = EvalMountPoint(tvc, NULL, &tvolp, areq);
282         ReleaseWriteLock(&tvc->lock);
283         if (code)
284             goto done;
285         if (tvolp) {
286             tvolp->dotdot = tvc->fid;
287             tvolp->dotdot.Fid.Vnode = tvc->parentVnode;
288             tvolp->dotdot.Fid.Unique = tvc->parentUnique;
289         }
290     }
291     if (tvc->mvid && (tvc->states & CMValid)) {
292         if (!canblock) {
293             afs_int32 retry;
294
295             do {
296                 retry = 0;
297                 ObtainWriteLock(&afs_xvcache, 597);
298                 root_vp = afs_FindVCache(tvc->mvid, &retry, 0);
299                 if (root_vp && retry) {
300                     ReleaseWriteLock(&afs_xvcache);
301                     afs_PutVCache(root_vp);
302                 }
303             } while (root_vp && retry);
304             ReleaseWriteLock(&afs_xvcache);
305         } else {
306             root_vp = afs_GetVCache(tvc->mvid, areq, NULL, NULL);
307         }
308         if (!root_vp) {
309             code = canblock ? ENOENT : 0;
310             goto done;
311         }
312         if (tvolp) {
313             /* Is this always kosher?  Perhaps we should instead use
314              * NBObtainWriteLock to avoid potential deadlock.
315              */
316             ObtainWriteLock(&root_vp->lock, 598);
317             if (!root_vp->mvid)
318                 root_vp->mvid = osi_AllocSmallSpace(sizeof(struct VenusFid));
319             *root_vp->mvid = tvolp->dotdot;
320             ReleaseWriteLock(&root_vp->lock);
321         }
322         state->need_release = 1;
323         state->root_vp = root_vp;
324         *avcp = root_vp;
325         code = 0;
326     } else {
327         code = canblock ? ENOENT : 0;
328     }
329
330   done:
331     if (tvolp)
332         afs_PutVolume(tvolp, WRITE_LOCK);
333     return code;
334 }
335
336 /*
337  * afs_EvalFakeStat
338  *
339  * Automatically does the equivalent of EvalMountPoint for vcache entries
340  * which are mount points.  Remembers enough state to properly release
341  * the volume root vcache when afs_PutFakeStat() is called.
342  *
343  * State variable must be initialized by afs_InitFakeState() beforehand.
344  *
345  * Returns 0 when everything succeeds and *avcp points to the vcache entry
346  * that should be used for the real vnode operation.  Returns non-zero if
347  * something goes wrong and the error code should be returned to the user.
348  */
349 int
350 afs_EvalFakeStat(struct vcache **avcp, struct afs_fakestat_state *state,
351                  struct vrequest *areq)
352 {
353     return afs_EvalFakeStat_int(avcp, state, areq, 1);
354 }
355
356 /*
357  * afs_TryEvalFakeStat
358  *
359  * Same as afs_EvalFakeStat, but tries not to talk to remote servers
360  * and only evaluate the mount point if all the data is already in
361  * local caches.
362  *
363  * Returns 0 if everything succeeds and *avcp points to a valid
364  * vcache entry (possibly evaluated).
365  */
366 int
367 afs_TryEvalFakeStat(struct vcache **avcp, struct afs_fakestat_state *state,
368                     struct vrequest *areq)
369 {
370     return afs_EvalFakeStat_int(avcp, state, areq, 0);
371 }
372
373 /*
374  * afs_PutFakeStat
375  *
376  * Perform any necessary cleanup at the end of a vnode op, given that
377  * afs_InitFakeStat was previously called with this state.
378  */
379 void
380 afs_PutFakeStat(struct afs_fakestat_state *state)
381 {
382     if (!afs_fakestat_enable)
383         return;
384
385     osi_Assert(state->valid == 1);
386     if (state->need_release)
387         afs_PutVCache(state->root_vp);
388     state->valid = 0;
389 }
390
391 int
392 afs_ENameOK(register char *aname)
393 {
394     register int tlen;
395
396     AFS_STATCNT(ENameOK);
397     tlen = strlen(aname);
398     if (tlen >= 4 && strcmp(aname + tlen - 4, "@sys") == 0)
399         return 0;
400     return 1;
401 }
402
403 int
404 afs_getsysname(register struct vrequest *areq, register struct vcache *adp,
405                register char *bufp)
406 {
407     register struct unixuser *au;
408     register afs_int32 error;
409
410     if (!afs_nfsexporter) {
411         strcpy(bufp, afs_sysname);
412         return 0;
413     }
414     AFS_STATCNT(getsysname);
415     au = afs_GetUser(areq->uid, adp->fid.Cell, 0);
416     afs_PutUser(au, 0);
417     if (au->exporter) {
418         error = EXP_SYSNAME(au->exporter, NULL, bufp);
419         if (error)
420             strcpy(bufp, "@sys");
421         return -1;
422     } else {
423         strcpy(bufp, afs_sysname);
424         return 0;
425     }
426 }
427
428 void
429 Check_AtSys(register struct vcache *avc, const char *aname,
430             struct sysname_info *state, struct vrequest *areq)
431 {
432     if (AFS_EQ_ATSYS(aname)) {
433         state->offset = 0;
434         state->name = (char *)osi_AllocLargeSpace(AFS_SMALLOCSIZ);
435         state->allocked = 1;
436         state->index = afs_getsysname(areq, avc, state->name);
437     } else {
438         state->offset = -1;
439         state->allocked = 0;
440         state->index = 0;
441         state->name = aname;
442     }
443 }
444
445 int
446 Next_AtSys(register struct vcache *avc, struct vrequest *areq,
447            struct sysname_info *state)
448 {
449     if (state->index == -1)
450         return 0;               /* No list */
451
452     /* Check for the initial state of aname != "@sys" in Check_AtSys */
453     if (state->offset == -1 && state->allocked == 0) {
454         register char *tname;
455         /* Check for .*@sys */
456         for (tname = state->name; *tname; tname++)
457             /*Move to the end of the string */ ;
458         if ((tname > state->name + 4) && (AFS_EQ_ATSYS(tname - 4))) {
459             state->offset = (tname - 4) - state->name;
460             tname = (char *)osi_AllocLargeSpace(AFS_LRALLOCSIZ);
461             strncpy(tname, state->name, state->offset);
462             state->name = tname;
463             state->allocked = 1;
464             state->index =
465                 afs_getsysname(areq, avc, state->name + state->offset);
466             return 1;
467         } else
468             return 0;           /* .*@sys doesn't match either */
469     } else if (++(state->index) >= afs_sysnamecount
470                || !afs_sysnamelist[(int)state->index])
471         return 0;               /* end of list */
472     strcpy(state->name + state->offset, afs_sysnamelist[(int)state->index]);
473     return 1;
474 }
475
476 #if (defined(AFS_SGI62_ENV) || defined(AFS_SUN57_64BIT_ENV))
477 extern int BlobScan(ino64_t * afile, afs_int32 ablob);
478 #else
479 #if defined AFS_LINUX_64BIT_KERNEL
480 extern int BlobScan(long *afile, afs_int32 ablob);
481 #else
482 extern int BlobScan(afs_int32 * afile, afs_int32 ablob);
483 #endif
484 #endif
485
486
487 /* called with an unlocked directory and directory cookie.  Areqp
488  * describes who is making the call.
489  * Scans the next N (about 30, typically) directory entries, and does
490  * a bulk stat call to stat them all.
491  *
492  * Must be very careful when merging in RPC responses, since we dont
493  * want to overwrite newer info that was added by a file system mutating
494  * call that ran concurrently with our bulk stat call.
495  *
496  * We do that, as described below, by not merging in our info (always
497  * safe to skip the merge) if the status info is valid in the vcache entry.
498  *
499  * If adapt ever implements the bulk stat RPC, then this code will need to
500  * ensure that vcaches created for failed RPC's to older servers have the
501  * CForeign bit set.
502  */
503 static struct vcache *BStvc = NULL;
504
505 int
506 afs_DoBulkStat(struct vcache *adp, long dirCookie, struct vrequest *areqp)
507 {
508     int nentries;               /* # of entries to prefetch */
509     int nskip;                  /* # of slots in the LRU queue to skip */
510     struct vcache *lruvcp;      /* vcache ptr of our goal pos in LRU queue */
511     struct dcache *dcp;         /* chunk containing the dir block */
512     char *statMemp;             /* status memory block */
513     char *cbfMemp;              /* callback and fid memory block */
514     afs_size_t temp;            /* temp for holding chunk length, &c. */
515     struct AFSFid *fidsp;       /* file IDs were collecting */
516     struct AFSCallBack *cbsp;   /* call back pointers */
517     struct AFSCallBack *tcbp;   /* temp callback ptr */
518     struct AFSFetchStatus *statsp;      /* file status info */
519     struct AFSVolSync volSync;  /* vol sync return info */
520     struct vcache *tvcp;        /* temp vcp */
521     struct afs_q *tq;           /* temp queue variable */
522     AFSCBFids fidParm;          /* file ID parm for bulk stat */
523     AFSBulkStats statParm;      /* stat info parm for bulk stat */
524     int fidIndex;               /* which file were stating */
525     struct conn *tcp;           /* conn for call */
526     AFSCBs cbParm;              /* callback parm for bulk stat */
527     struct server *hostp = 0;   /* host we got callback from */
528     long startTime;             /* time we started the call,
529                                  * for callback expiration base
530                                  */
531     afs_size_t statSeqNo;       /* Valued of file size to detect races */
532     int code;                   /* error code */
533     long newIndex;              /* new index in the dir */
534     struct DirEntry *dirEntryp; /* dir entry we are examining */
535     int i;
536     struct VenusFid afid;       /* file ID we are using now */
537     struct VenusFid tfid;       /* another temp. file ID */
538     afs_int32 retry;            /* handle low-level SGI MP race conditions */
539     long volStates;             /* flags from vol structure */
540     struct volume *volp = 0;    /* volume ptr */
541     struct VenusFid dotdot;
542     int flagIndex;              /* First file with bulk fetch flag set */
543     int inlinebulk = 0;         /* Did we use InlineBulk RPC or not? */
544     XSTATS_DECLS
545         /* first compute some basic parameters.  We dont want to prefetch more
546          * than a fraction of the cache in any given call, and we want to preserve
547          * a portion of the LRU queue in any event, so as to avoid thrashing
548          * the entire stat cache (we will at least leave some of it alone).
549          * presently dont stat more than 1/8 the cache in any one call.      */
550         nentries = afs_cacheStats / 8;
551
552     /* dont bother prefetching more than one calls worth of info */
553     if (nentries > AFSCBMAX)
554         nentries = AFSCBMAX;
555
556     /* heuristic to make sure that things fit in 4K.  This means that
557      * we shouldnt make it any bigger than 47 entries.  I am typically
558      * going to keep it a little lower, since we don't want to load
559      * too much of the stat cache.
560      */
561     if (nentries > 30)
562         nentries = 30;
563
564     /* now, to reduce the stack size, well allocate two 4K blocks,
565      * one for fids and callbacks, and one for stat info.  Well set
566      * up our pointers to the memory from there, too.
567      */
568     statMemp = osi_AllocLargeSpace(nentries * sizeof(AFSFetchStatus));
569     statsp = (struct AFSFetchStatus *)statMemp;
570     cbfMemp =
571         osi_AllocLargeSpace(nentries *
572                             (sizeof(AFSCallBack) + sizeof(AFSFid)));
573     fidsp = (AFSFid *) cbfMemp;
574     cbsp = (AFSCallBack *) (cbfMemp + nentries * sizeof(AFSFid));
575
576     /* next, we must iterate over the directory, starting from the specified
577      * cookie offset (dirCookie), and counting out nentries file entries.
578      * We skip files that already have stat cache entries, since we
579      * dont want to bulk stat files that are already in the cache.
580      */
581   tagain:
582     code = afs_VerifyVCache(adp, areqp);
583     if (code)
584         goto done;
585
586     dcp = afs_GetDCache(adp, (afs_size_t) 0, areqp, &temp, &temp, 1);
587     if (!dcp) {
588         code = ENOENT;
589         goto done;
590     }
591
592     /* lock the directory cache entry */
593     ObtainReadLock(&adp->lock);
594     ObtainReadLock(&dcp->lock);
595
596     /*
597      * Make sure that the data in the cache is current. There are two
598      * cases we need to worry about:
599      * 1. The cache data is being fetched by another process.
600      * 2. The cache data is no longer valid
601      */
602     while ((adp->states & CStatd)
603            && (dcp->dflags & DFFetching)
604            && hsame(adp->m.DataVersion, dcp->f.versionNo)) {
605         afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAIT, ICL_TYPE_STRING,
606                    __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER, dcp,
607                    ICL_TYPE_INT32, dcp->dflags);
608         ReleaseReadLock(&dcp->lock);
609         ReleaseReadLock(&adp->lock);
610         afs_osi_Sleep(&dcp->validPos);
611         ObtainReadLock(&adp->lock);
612         ObtainReadLock(&dcp->lock);
613     }
614     if (!(adp->states & CStatd)
615         || !hsame(adp->m.DataVersion, dcp->f.versionNo)) {
616         ReleaseReadLock(&dcp->lock);
617         ReleaseReadLock(&adp->lock);
618         afs_PutDCache(dcp);
619         goto tagain;
620     }
621
622     /* Generate a sequence number so we can tell whether we should
623      * store the attributes when processing the response. This number is
624      * stored in the file size when we set the CBulkFetching bit. If the
625      * CBulkFetching is still set and this value hasn't changed, then
626      * we know we were the last to set CBulkFetching bit for this file,
627      * and it is safe to set the status information for this file.
628      */
629     statSeqNo = bulkStatCounter++;
630
631     /* now we have dir data in the cache, so scan the dir page */
632     fidIndex = 0;
633     flagIndex = 0;
634     while (1) {                 /* Should probably have some constant bound */
635         /* look for first safe entry to examine in the directory.  BlobScan
636          * looks for a the 1st allocated dir after the dirCookie slot.
637          */
638         newIndex = BlobScan(&dcp->f.inode, (dirCookie >> 5));
639         if (newIndex == 0)
640             break;
641
642         /* remember the updated directory cookie */
643         dirCookie = newIndex << 5;
644
645         /* get a ptr to the dir entry */
646         dirEntryp =
647             (struct DirEntry *)afs_dir_GetBlob(&dcp->f.inode, newIndex);
648         if (!dirEntryp)
649             break;
650
651         /* dont copy more than we have room for */
652         if (fidIndex >= nentries) {
653             DRelease((struct buffer *)dirEntryp, 0);
654             break;
655         }
656
657         /* now, if the dir entry looks good, copy it out to our list.  Vnode
658          * 0 means deleted, although it should also be free were it deleted.
659          */
660         if (dirEntryp->fid.vnode != 0) {
661             /* dont copy entries we have in our cache.  This check will
662              * also make us skip "." and probably "..", unless it has
663              * disappeared from the cache since we did our namei call.
664              */
665             tfid.Cell = adp->fid.Cell;
666             tfid.Fid.Volume = adp->fid.Fid.Volume;
667             tfid.Fid.Vnode = ntohl(dirEntryp->fid.vnode);
668             tfid.Fid.Unique = ntohl(dirEntryp->fid.vunique);
669             do {
670                 retry = 0;
671                 ObtainWriteLock(&afs_xvcache, 130);
672                 tvcp = afs_FindVCache(&tfid, &retry, 0 /* no stats | LRU */ );
673                 if (tvcp && retry) {
674                     ReleaseWriteLock(&afs_xvcache);
675                     afs_PutVCache(tvcp);
676                 }
677             } while (tvcp && retry);
678             if (!tvcp) {        /* otherwise, create manually */
679                 tvcp = afs_NewVCache(&tfid, hostp);
680                 ObtainWriteLock(&tvcp->lock, 505);
681                 ReleaseWriteLock(&afs_xvcache);
682                 afs_RemoveVCB(&tfid);
683                 ReleaseWriteLock(&tvcp->lock);
684             } else {
685                 ReleaseWriteLock(&afs_xvcache);
686             }
687             if (!tvcp)
688                 goto done;      /* can't happen at present, more's the pity */
689
690             /* WARNING: afs_DoBulkStat uses the Length field to store a
691              * sequence number for each bulk status request. Under no
692              * circumstances should afs_DoBulkStat store a sequence number
693              * if the new length will be ignored when afs_ProcessFS is
694              * called with new stats. */
695 #ifdef AFS_SGI_ENV
696             if (!(tvcp->states & (CStatd | CBulkFetching))
697                 && (tvcp->execsOrWriters <= 0)
698                 && !afs_DirtyPages(tvcp)
699                 && !AFS_VN_MAPPED((vnode_t *) tvcp))
700 #else
701             if (!(tvcp->states & (CStatd | CBulkFetching))
702                 && (tvcp->execsOrWriters <= 0)
703                 && !afs_DirtyPages(tvcp))
704 #endif
705
706             {
707                 /* this entry doesnt exist in the cache, and is not
708                  * already being fetched by someone else, so add it to the
709                  * list of file IDs to obtain.
710                  *
711                  * We detect a callback breaking race condition by checking the
712                  * CBulkFetching state bit and the value in the file size.
713                  * It is safe to set the status only if the CBulkFetching
714                  * flag is still set and the value in the file size does
715                  * not change.
716                  *
717                  * Don't fetch status for dirty files. We need to
718                  * preserve the value of the file size. We could
719                  * flush the pages, but it wouldn't be worthwhile.
720                  */
721                 memcpy((char *)(fidsp + fidIndex), (char *)&tfid.Fid,
722                        sizeof(*fidsp));
723                 tvcp->states |= CBulkFetching;
724                 tvcp->m.Length = statSeqNo;
725                 fidIndex++;
726             }
727             afs_PutVCache(tvcp);
728         }
729
730         /* if dir vnode has non-zero entry */
731         /* move to the next dir entry by adding in the # of entries
732          * used by this dir entry.
733          */
734         temp = afs_dir_NameBlobs(dirEntryp->name) << 5;
735         DRelease((struct buffer *)dirEntryp, 0);
736         if (temp <= 0)
737             break;
738         dirCookie += temp;
739     }                           /* while loop over all dir entries */
740
741     /* now release the dir lock and prepare to make the bulk RPC */
742     ReleaseReadLock(&dcp->lock);
743     ReleaseReadLock(&adp->lock);
744
745     /* release the chunk */
746     afs_PutDCache(dcp);
747
748     /* dont make a null call */
749     if (fidIndex == 0)
750         goto done;
751
752     do {
753         /* setup the RPC parm structures */
754         fidParm.AFSCBFids_len = fidIndex;
755         fidParm.AFSCBFids_val = fidsp;
756         statParm.AFSBulkStats_len = fidIndex;
757         statParm.AFSBulkStats_val = statsp;
758         cbParm.AFSCBs_len = fidIndex;
759         cbParm.AFSCBs_val = cbsp;
760
761         /* start the timer; callback expirations are relative to this */
762         startTime = osi_Time();
763
764         tcp = afs_Conn(&adp->fid, areqp, SHARED_LOCK);
765         if (tcp) {
766             hostp = tcp->srvr->server;
767             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_BULKSTATUS);
768             RX_AFS_GUNLOCK();
769
770             if (!(tcp->srvr->server->flags & SNO_INLINEBULK)) {
771                 code =
772                     RXAFS_InlineBulkStatus(tcp->id, &fidParm, &statParm,
773                                            &cbParm, &volSync);
774                 if (code == RXGEN_OPCODE) {
775                     tcp->srvr->server->flags |= SNO_INLINEBULK;
776                     inlinebulk = 0;
777                     code =
778                         RXAFS_BulkStatus(tcp->id, &fidParm, &statParm,
779                                          &cbParm, &volSync);
780                 } else
781                     inlinebulk = 1;
782             } else {
783                 inlinebulk = 0;
784                 code =
785                     RXAFS_BulkStatus(tcp->id, &fidParm, &statParm, &cbParm,
786                                      &volSync);
787             }
788             RX_AFS_GLOCK();
789             XSTATS_END_TIME;
790         } else
791             code = -1;
792     } while (afs_Analyze
793              (tcp, code, &adp->fid, areqp, AFS_STATS_FS_RPCIDX_BULKSTATUS,
794               SHARED_LOCK, NULL));
795
796     /* now, if we didnt get the info, bail out. */
797     if (code)
798         goto done;
799
800     /* we need vol flags to create the entries properly */
801     dotdot.Fid.Volume = 0;
802     volp = afs_GetVolume(&adp->fid, areqp, READ_LOCK);
803     if (volp) {
804         volStates = volp->states;
805         if (volp->dotdot.Fid.Volume != 0)
806             dotdot = volp->dotdot;
807     } else
808         volStates = 0;
809
810     /* find the place to merge the info into  We do this by skipping
811      * nskip entries in the LRU queue.  The more we skip, the more
812      * we preserve, since the head of the VLRU queue is the most recently
813      * referenced file.
814      */
815   reskip:
816     nskip = afs_cacheStats / 2; /* preserved fraction of the cache */
817     ObtainReadLock(&afs_xvcache);
818     if (QEmpty(&VLRU)) {
819         /* actually a serious error, probably should panic. Probably will 
820          * panic soon, oh well. */
821         ReleaseReadLock(&afs_xvcache);
822         afs_warnuser("afs_DoBulkStat: VLRU empty!");
823         goto done;
824     }
825     if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
826         refpanic("Bulkstat VLRU inconsistent");
827     }
828     for (tq = VLRU.next; tq != &VLRU; tq = QNext(tq)) {
829         if (--nskip <= 0)
830             break;
831         else if (QNext(QPrev(tq)) != tq) {
832             BStvc = QTOV(tq);
833             refpanic("BulkStat VLRU inconsistent");
834         }
835     }
836     if (tq != &VLRU)
837         lruvcp = QTOV(tq);
838     else
839         lruvcp = QTOV(VLRU.next);
840
841     /* now we have to hold this entry, so that it does not get moved
842      * into the free list while we're running.  It could still get
843      * moved within the lru queue, but hopefully that will be rare; it
844      * doesn't hurt nearly as much.
845      */
846     retry = 0;
847     osi_vnhold(lruvcp, &retry);
848     ReleaseReadLock(&afs_xvcache);      /* could be read lock */
849     if (retry)
850         goto reskip;
851
852     /* otherwise, merge in the info.  We have to be quite careful here,
853      * since we need to ensure that we don't merge old info over newer
854      * stuff in a stat cache entry.  We're very conservative here: we don't
855      * do the merge at all unless we ourselves create the stat cache
856      * entry.  That's pretty safe, and should work pretty well, since we
857      * typically expect to do the stat cache creation ourselves.
858      *
859      * We also have to take into account racing token revocations.
860      */
861     for (i = 0; i < fidIndex; i++) {
862         if ((&statsp[i])->errorCode)
863             continue;
864         afid.Cell = adp->fid.Cell;
865         afid.Fid.Volume = adp->fid.Fid.Volume;
866         afid.Fid.Vnode = fidsp[i].Vnode;
867         afid.Fid.Unique = fidsp[i].Unique;
868         do {
869             retry = 0;
870             ObtainReadLock(&afs_xvcache);
871             tvcp = afs_FindVCache(&afid, &retry, 0 /* !stats&!lru */ );
872             ReleaseReadLock(&afs_xvcache);
873         } while (tvcp && retry);
874
875         /* The entry may no longer exist */
876         if (tvcp == NULL) {
877             continue;
878         }
879
880         /* now we have the entry held, but we need to fill it in */
881         ObtainWriteLock(&tvcp->lock, 131);
882
883         /* if CBulkFetching is not set, or if the file size no longer
884          * matches the value we placed there when we set the CBulkFetching
885          * flag, then someone else has done something with this node,
886          * and we may not have the latest status information for this
887          * file.  Leave the entry alone.
888          */
889         if (!(tvcp->states & CBulkFetching) || (tvcp->m.Length != statSeqNo)) {
890             flagIndex++;
891             ReleaseWriteLock(&tvcp->lock);
892             afs_PutVCache(tvcp);
893             continue;
894         }
895
896         /* now copy ".." entry back out of volume structure, if necessary */
897         if (tvcp->mvstat == 2 && (dotdot.Fid.Volume != 0)) {
898             if (!tvcp->mvid)
899                 tvcp->mvid = (struct VenusFid *)
900                     osi_AllocSmallSpace(sizeof(struct VenusFid));
901             *tvcp->mvid = dotdot;
902         }
903
904         ObtainWriteLock(&afs_xvcache, 132);
905         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
906             refpanic("Bulkstat VLRU inconsistent2");
907         }
908         if ((QNext(QPrev(&tvcp->vlruq)) != &tvcp->vlruq)
909             || (QPrev(QNext(&tvcp->vlruq)) != &tvcp->vlruq)) {
910             refpanic("Bulkstat VLRU inconsistent4");
911         }
912         if ((QNext(QPrev(&lruvcp->vlruq)) != &lruvcp->vlruq)
913             || (QPrev(QNext(&lruvcp->vlruq)) != &lruvcp->vlruq)) {
914             refpanic("Bulkstat VLRU inconsistent5");
915         }
916
917         if (tvcp != lruvcp) {   /* if they are == don't move it, don't corrupt vlru */
918             QRemove(&tvcp->vlruq);
919             QAdd(&lruvcp->vlruq, &tvcp->vlruq);
920         }
921
922         if ((VLRU.next->prev != &VLRU) || (VLRU.prev->next != &VLRU)) {
923             refpanic("Bulkstat VLRU inconsistent3");
924         }
925         if ((QNext(QPrev(&tvcp->vlruq)) != &tvcp->vlruq)
926             || (QPrev(QNext(&tvcp->vlruq)) != &tvcp->vlruq)) {
927             refpanic("Bulkstat VLRU inconsistent5");
928         }
929         if ((QNext(QPrev(&lruvcp->vlruq)) != &lruvcp->vlruq)
930             || (QPrev(QNext(&lruvcp->vlruq)) != &lruvcp->vlruq)) {
931             refpanic("Bulkstat VLRU inconsistent6");
932         }
933         ReleaseWriteLock(&afs_xvcache);
934
935         ObtainWriteLock(&afs_xcbhash, 494);
936
937         /* We need to check the flags again. We may have missed
938          * something while we were waiting for a lock.
939          */
940         if (!(tvcp->states & CBulkFetching) || (tvcp->m.Length != statSeqNo)) {
941             flagIndex++;
942             ReleaseWriteLock(&tvcp->lock);
943             ReleaseWriteLock(&afs_xcbhash);
944             afs_PutVCache(tvcp);
945             continue;
946         }
947
948         /* now merge in the resulting status back into the vnode.
949          * We only do this if the entry looks clear.
950          */
951         afs_ProcessFS(tvcp, &statsp[i], areqp);
952 #ifdef AFS_LINUX22_ENV
953         /* overwrite the ops if it's a directory or symlink. */
954         if (vType(tvcp) == VDIR)
955             tvcp->v.v_op = &afs_dir_iops;
956         else if (vType(tvcp) == VLNK)
957             tvcp->v.v_op = &afs_symlink_iops;
958 #endif
959
960         /* do some accounting for bulk stats: mark this entry as
961          * loaded, so we can tell if we use it before it gets
962          * recycled.
963          */
964         tvcp->states |= CBulkStat;
965         tvcp->states &= ~CBulkFetching;
966         flagIndex++;
967         afs_bulkStatsDone++;
968
969         /* merge in vol info */
970         if (volStates & VRO)
971             tvcp->states |= CRO;
972         if (volStates & VBackup)
973             tvcp->states |= CBackup;
974         if (volStates & VForeign)
975             tvcp->states |= CForeign;
976
977         /* merge in the callback info */
978         tvcp->states |= CTruth;
979
980         /* get ptr to the callback we are interested in */
981         tcbp = cbsp + i;
982
983         if (tcbp->ExpirationTime != 0) {
984             tvcp->cbExpires = tcbp->ExpirationTime + startTime;
985             tvcp->callback = hostp;
986             tvcp->states |= CStatd;
987             afs_QueueCallback(tvcp, CBHash(tcbp->ExpirationTime), volp);
988         } else if (tvcp->states & CRO) {
989             /* ordinary callback on a read-only volume -- AFS 3.2 style */
990             tvcp->cbExpires = 3600 + startTime;
991             tvcp->callback = hostp;
992             tvcp->states |= CStatd;
993             afs_QueueCallback(tvcp, CBHash(3600), volp);
994         } else {
995             tvcp->callback = 0;
996             tvcp->states &= ~(CStatd | CUnique);
997             afs_DequeueCallback(tvcp);
998             if ((tvcp->states & CForeign) || (vType(tvcp) == VDIR))
999                 osi_dnlc_purgedp(tvcp); /* if it (could be) a directory */
1000         }
1001         ReleaseWriteLock(&afs_xcbhash);
1002
1003         ReleaseWriteLock(&tvcp->lock);
1004         /* finally, we're done with the entry */
1005         afs_PutVCache(tvcp);
1006     }                           /* for all files we got back */
1007
1008     /* finally return the pointer into the LRU queue */
1009     afs_PutVCache(lruvcp);
1010
1011   done:
1012     /* Be sure to turn off the CBulkFetching flags */
1013     for (i = flagIndex; i < fidIndex; i++) {
1014         afid.Cell = adp->fid.Cell;
1015         afid.Fid.Volume = adp->fid.Fid.Volume;
1016         afid.Fid.Vnode = fidsp[i].Vnode;
1017         afid.Fid.Unique = fidsp[i].Unique;
1018         do {
1019             retry = 0;
1020             ObtainReadLock(&afs_xvcache);
1021             tvcp = afs_FindVCache(&afid, &retry, 0 /* !stats&!lru */ );
1022             ReleaseReadLock(&afs_xvcache);
1023         } while (tvcp && retry);
1024         if (tvcp != NULL && (tvcp->states & CBulkFetching)
1025             && (tvcp->m.Length == statSeqNo)) {
1026             tvcp->states &= ~CBulkFetching;
1027         }
1028         if (tvcp != NULL) {
1029             afs_PutVCache(tvcp);
1030         }
1031     }
1032     if (volp)
1033         afs_PutVolume(volp, READ_LOCK);
1034
1035     /* If we did the InlineBulk RPC pull out the return code */
1036     if (inlinebulk) {
1037         if ((&statsp[0])->errorCode) {
1038             afs_Analyze(tcp, (&statsp[0])->errorCode, &adp->fid, areqp,
1039                         AFS_STATS_FS_RPCIDX_BULKSTATUS, SHARED_LOCK, NULL);
1040             code = (&statsp[0])->errorCode;
1041         }
1042     } else {
1043         code = 0;
1044     }
1045     osi_FreeLargeSpace(statMemp);
1046     osi_FreeLargeSpace(cbfMemp);
1047     return code;
1048 }
1049
1050 /* was: (AFS_DEC_ENV) || defined(AFS_OSF30_ENV) || defined(AFS_NCR_ENV) */
1051 static int AFSDOBULK = 1;
1052
1053 int
1054 #ifdef  AFS_OSF_ENV
1055 afs_lookup(adp, ndp)
1056      struct vcache *adp;
1057      struct nameidata *ndp;
1058 {
1059     char aname[MAXNAMLEN + 1];  /* XXX */
1060     struct vcache **avcp = (struct vcache **)&(ndp->ni_vp);
1061     struct ucred *acred = ndp->ni_cred;
1062     int wantparent = ndp->ni_nameiop & WANTPARENT;
1063     int opflag = ndp->ni_nameiop & OPFLAG;
1064 #else                           /* AFS_OSF_ENV */
1065 #if     defined(AFS_SUN5_ENV) || defined(AFS_SGI_ENV)
1066 afs_lookup(OSI_VC_ARG(adp), aname, avcp, pnp, flags, rdir, acred)
1067      struct pathname *pnp;
1068      int flags;
1069      struct vnode *rdir;
1070 #else
1071 #if defined(UKERNEL)
1072 afs_lookup(adp, aname, avcp, acred, flags)
1073      int flags;
1074 #else
1075 afs_lookup(adp, aname, avcp, acred)
1076 #endif                          /* UKERNEL */
1077 #endif                          /* SUN5 || SGI */
1078 OSI_VC_DECL(adp);
1079      struct vcache **avcp;
1080      char *aname;
1081      struct AFS_UCRED *acred;
1082 {
1083 #endif
1084     struct vrequest treq;
1085     char *tname = NULL;
1086     register struct vcache *tvc = 0;
1087     register afs_int32 code;
1088     register afs_int32 bulkcode = 0;
1089     int pass = 0, hit = 0;
1090     long dirCookie;
1091     extern afs_int32 afs_mariner;       /*Writing activity to log? */
1092     OSI_VC_CONVERT(adp)
1093     afs_hyper_t versionNo;
1094     int no_read_access = 0;
1095     struct sysname_info sysState;       /* used only for @sys checking */
1096     int dynrootRetry = 1;
1097     struct afs_fakestat_state fakestate;
1098     int tryEvalOnly = 0;
1099
1100     AFS_STATCNT(afs_lookup);
1101     afs_InitFakeStat(&fakestate);
1102
1103     if ((code = afs_InitReq(&treq, acred)))
1104         goto done;
1105
1106 #ifdef  AFS_OSF_ENV
1107     ndp->ni_dvp = AFSTOV(adp);
1108     memcpy(aname, ndp->ni_ptr, ndp->ni_namelen);
1109     aname[ndp->ni_namelen] = '\0';
1110 #endif /* AFS_OSF_ENV */
1111
1112 #if defined(AFS_DARWIN_ENV)
1113     /* Workaround for MacOSX Finder, which tries to look for
1114      * .DS_Store and Contents under every directory.
1115      */
1116     if (afs_fakestat_enable && adp->mvstat == 1) {
1117         if (strcmp(aname, ".DS_Store") == 0)
1118             tryEvalOnly = 1;
1119         if (strcmp(aname, "Contents") == 0)
1120             tryEvalOnly = 1;
1121     }
1122 #endif
1123
1124     if (tryEvalOnly)
1125         code = afs_TryEvalFakeStat(&adp, &fakestate, &treq);
1126     else
1127         code = afs_EvalFakeStat(&adp, &fakestate, &treq);
1128     if (tryEvalOnly && adp->mvstat == 1)
1129         code = ENOENT;
1130     if (code)
1131         goto done;
1132
1133     *avcp = NULL;               /* Since some callers don't initialize it */
1134
1135     /* come back to here if we encounter a non-existent object in a read-only
1136      * volume's directory */
1137
1138   redo:
1139     *avcp = NULL;               /* Since some callers don't initialize it */
1140     bulkcode = 0;
1141
1142     if (!(adp->states & CStatd)) {
1143         if ((code = afs_VerifyVCache2(adp, &treq))) {
1144             goto done;
1145         }
1146     } else
1147         code = 0;
1148
1149     /* watch for ".." in a volume root */
1150     if (adp->mvstat == 2 && aname[0] == '.' && aname[1] == '.' && !aname[2]) {
1151         /* looking up ".." in root via special hacks */
1152         if (adp->mvid == (struct VenusFid *)0 || adp->mvid->Fid.Volume == 0) {
1153 #ifdef  AFS_OSF_ENV
1154             extern struct vcache *afs_globalVp;
1155             if (adp == afs_globalVp) {
1156                 struct vnode *rvp = AFSTOV(adp);
1157 /*
1158                 ndp->ni_vp = rvp->v_vfsp->vfs_vnodecovered;
1159                 ndp->ni_dvp = ndp->ni_vp;
1160                 VN_HOLD(*avcp);
1161 */
1162                 code = ENODEV;
1163                 goto done;
1164             }
1165 #endif
1166             code = ENODEV;
1167             goto done;
1168         }
1169         /* otherwise we have the fid here, so we use it */
1170         tvc = afs_GetVCache(adp->mvid, &treq, NULL, NULL);
1171         afs_Trace3(afs_iclSetp, CM_TRACE_GETVCDOTDOT, ICL_TYPE_FID, adp->mvid,
1172                    ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, code);
1173         *avcp = tvc;
1174         code = (tvc ? 0 : ENOENT);
1175         hit = 1;
1176         if (tvc && !VREFCOUNT(tvc)) {
1177             osi_Panic("TT1");
1178         }
1179         if (code) {
1180             /*printf("LOOKUP GETVCDOTDOT -> %d\n", code); */
1181         }
1182         goto done;
1183     }
1184
1185     /* now check the access */
1186     if (treq.uid != adp->last_looker) {
1187         if (!afs_AccessOK(adp, PRSFS_LOOKUP, &treq, CHECK_MODE_BITS)) {
1188             *avcp = NULL;
1189             code = EACCES;
1190             goto done;
1191         } else
1192             adp->last_looker = treq.uid;
1193     }
1194
1195     /* Check for read access as well.  We need read access in order to
1196      * stat files, but not to stat subdirectories. */
1197     if (!afs_AccessOK(adp, PRSFS_LOOKUP, &treq, CHECK_MODE_BITS))
1198         no_read_access = 1;
1199
1200     /* special case lookup of ".".  Can we check for it sooner in this code,
1201      * for instance, way up before "redo:" ??
1202      * I'm not fiddling with the LRUQ here, either, perhaps I should, or else 
1203      * invent a lightweight version of GetVCache.
1204      */
1205     if (aname[0] == '.' && !aname[1]) { /* special case */
1206         ObtainReadLock(&afs_xvcache);
1207         osi_vnhold(adp, 0);
1208         ReleaseReadLock(&afs_xvcache);
1209         code = 0;
1210         *avcp = tvc = adp;
1211         hit = 1;
1212         if (adp && !VREFCOUNT(adp)) {
1213             osi_Panic("TT2");
1214         }
1215         goto done;
1216     }
1217
1218     Check_AtSys(adp, aname, &sysState, &treq);
1219     tname = sysState.name;
1220
1221     /* 1st Check_AtSys and lookup by tname is required here, for now,
1222      * because the dnlc is *not* told to remove entries for the parent
1223      * dir of file/dir op that afs_LocalHero likes, but dnlc is informed
1224      * if the cached entry for the parent dir is invalidated for a
1225      * non-local change.
1226      * Otherwise, we'd be able to do a dnlc lookup on an entry ending
1227      * w/@sys and know the dnlc was consistent with reality. */
1228     tvc = osi_dnlc_lookup(adp, tname, WRITE_LOCK);
1229     *avcp = tvc;                /* maybe wasn't initialized, but it is now */
1230     if (tvc) {
1231         if (no_read_access && vType(tvc) != VDIR && vType(tvc) != VLNK) {
1232             /* need read access on dir to stat non-directory / non-link */
1233             afs_PutVCache(tvc);
1234             *avcp = NULL;
1235             code = EACCES;
1236             goto done;
1237         }
1238 #ifdef AFS_LINUX22_ENV
1239         if (tvc->mvstat == 2) { /* we don't trust the dnlc for root vcaches */
1240             AFS_RELE(tvc);
1241             *avcp = 0;
1242         } else {
1243             code = 0;
1244             hit = 1;
1245             goto done;
1246         }
1247 #else /* non - LINUX */
1248         code = 0;
1249         hit = 1;
1250         goto done;
1251 #endif /* linux22 */
1252     }
1253
1254     {                           /* sub-block just to reduce stack usage */
1255         register struct dcache *tdc;
1256         afs_size_t dirOffset, dirLen;
1257         ino_t theDir;
1258         struct VenusFid tfid;
1259
1260         /* now we have to lookup the next fid */
1261         tdc =
1262             afs_GetDCache(adp, (afs_size_t) 0, &treq, &dirOffset, &dirLen, 1);
1263         if (!tdc) {
1264             *avcp = NULL;       /* redundant, but harmless */
1265             code = EIO;
1266             goto done;
1267         }
1268
1269         /* now we will just call dir package with appropriate inode.
1270          * Dirs are always fetched in their entirety for now */
1271         ObtainReadLock(&adp->lock);
1272         ObtainReadLock(&tdc->lock);
1273
1274         /*
1275          * Make sure that the data in the cache is current. There are two
1276          * cases we need to worry about:
1277          * 1. The cache data is being fetched by another process.
1278          * 2. The cache data is no longer valid
1279          */
1280         while ((adp->states & CStatd)
1281                && (tdc->dflags & DFFetching)
1282                && hsame(adp->m.DataVersion, tdc->f.versionNo)) {
1283             ReleaseReadLock(&tdc->lock);
1284             ReleaseReadLock(&adp->lock);
1285             afs_osi_Sleep(&tdc->validPos);
1286             ObtainReadLock(&adp->lock);
1287             ObtainReadLock(&tdc->lock);
1288         }
1289         if (!(adp->states & CStatd)
1290             || !hsame(adp->m.DataVersion, tdc->f.versionNo)) {
1291             ReleaseReadLock(&tdc->lock);
1292             ReleaseReadLock(&adp->lock);
1293             afs_PutDCache(tdc);
1294             goto redo;
1295         }
1296
1297         /* Save the version number for when we call osi_dnlc_enter */
1298         hset(versionNo, tdc->f.versionNo);
1299
1300         /*
1301          * check for, and handle "@sys" if it's there.  We should be able
1302          * to avoid the alloc and the strcpy with a little work, but it's
1303          * not pressing.  If there aren't any remote users (ie, via the 
1304          * NFS translator), we have a slightly easier job.
1305          * the faster way to do this is to check for *aname == '@' and if 
1306          * it's there, check for @sys, otherwise, assume there's no @sys 
1307          * then, if the lookup fails, check for .*@sys...
1308          */
1309         /* above now implemented by Check_AtSys and Next_AtSys */
1310
1311         /* lookup the name in the appropriate dir, and return a cache entry
1312          * on the resulting fid */
1313         theDir = tdc->f.inode;
1314         code =
1315             afs_dir_LookupOffset(&theDir, sysState.name, &tfid.Fid,
1316                                  &dirCookie);
1317
1318         /* If the first lookup doesn't succeed, maybe it's got @sys in the name */
1319         while (code == ENOENT && Next_AtSys(adp, &treq, &sysState))
1320             code =
1321                 afs_dir_LookupOffset(&theDir, sysState.name, &tfid.Fid,
1322                                      &dirCookie);
1323         tname = sysState.name;
1324
1325         ReleaseReadLock(&tdc->lock);
1326         afs_PutDCache(tdc);
1327
1328         if (code == ENOENT && afs_IsDynroot(adp) && dynrootRetry) {
1329             ReleaseReadLock(&adp->lock);
1330             dynrootRetry = 0;
1331             if (tname[0] == '.')
1332                 afs_LookupAFSDB(tname + 1);
1333             else
1334                 afs_LookupAFSDB(tname);
1335             if (tname && tname != aname)
1336                 osi_FreeLargeSpace(tname);
1337             goto redo;
1338         } else {
1339             ReleaseReadLock(&adp->lock);
1340         }
1341
1342         /* new fid has same cell and volume */
1343         tfid.Cell = adp->fid.Cell;
1344         tfid.Fid.Volume = adp->fid.Fid.Volume;
1345         afs_Trace4(afs_iclSetp, CM_TRACE_LOOKUP, ICL_TYPE_POINTER, adp,
1346                    ICL_TYPE_STRING, tname, ICL_TYPE_FID, &tfid,
1347                    ICL_TYPE_INT32, code);
1348
1349         if (code) {
1350             if (code != ENOENT) {
1351                 printf("LOOKUP dirLookupOff -> %d\n", code);
1352             }
1353             goto done;
1354         }
1355
1356         /* prefetch some entries, if the dir is currently open.  The variable
1357          * dirCookie tells us where to start prefetching from.
1358          */
1359         if (AFSDOBULK && adp->opens > 0 && !(adp->states & CForeign)
1360             && !afs_IsDynroot(adp)) {
1361             afs_int32 retry;
1362             /* if the entry is not in the cache, or is in the cache,
1363              * but hasn't been statd, then do a bulk stat operation.
1364              */
1365             do {
1366                 retry = 0;
1367                 ObtainReadLock(&afs_xvcache);
1368                 tvc = afs_FindVCache(&tfid, &retry, 0 /* !stats,!lru */ );
1369                 ReleaseReadLock(&afs_xvcache);
1370             } while (tvc && retry);
1371
1372             if (!tvc || !(tvc->states & CStatd))
1373                 bulkcode = afs_DoBulkStat(adp, dirCookie, &treq);
1374             else
1375                 bulkcode = 0;
1376
1377             /* if the vcache isn't usable, release it */
1378             if (tvc && !(tvc->states & CStatd)) {
1379                 afs_PutVCache(tvc);
1380                 tvc = NULL;
1381             }
1382         } else {
1383             tvc = NULL;
1384             bulkcode = 0;
1385         }
1386
1387         /* now get the status info, if we don't already have it */
1388         /* This is kind of weird, but we might wind up accidentally calling
1389          * RXAFS_Lookup because we happened upon a file which legitimately
1390          * has a 0 uniquifier. That is the result of allowing unique to wrap
1391          * to 0. This was fixed in AFS 3.4. For CForeign, Unique == 0 means that
1392          * the file has not yet been looked up.
1393          */
1394         if (!tvc) {
1395             afs_int32 cached = 0;
1396             if (!tfid.Fid.Unique && (adp->states & CForeign)) {
1397                 tvc = afs_LookupVCache(&tfid, &treq, &cached, adp, tname);
1398             }
1399             if (!tvc && !bulkcode) {    /* lookup failed or wasn't called */
1400                 tvc = afs_GetVCache(&tfid, &treq, &cached, NULL);
1401             }
1402         }                       /* if !tvc */
1403     }                           /* sub-block just to reduce stack usage */
1404
1405     if (tvc) {
1406         int force_eval = afs_fakestat_enable ? 0 : 1;
1407
1408         if (adp->states & CForeign)
1409             tvc->states |= CForeign;
1410         tvc->parentVnode = adp->fid.Fid.Vnode;
1411         tvc->parentUnique = adp->fid.Fid.Unique;
1412         tvc->states &= ~CBulkStat;
1413
1414         if (afs_fakestat_enable == 2 && tvc->mvstat == 1) {
1415             ObtainSharedLock(&tvc->lock, 680);
1416             if (!tvc->linkData) {
1417                 UpgradeSToWLock(&tvc->lock, 681);
1418                 code = afs_HandleLink(tvc, &treq);
1419                 ConvertWToRLock(&tvc->lock);
1420             } else {
1421                 ConvertSToRLock(&tvc->lock);
1422                 code = 0;
1423             }
1424             if (!code && !afs_strchr(tvc->linkData, ':'))
1425                 force_eval = 1;
1426             ReleaseReadLock(&tvc->lock);
1427         }
1428 #if defined(UKERNEL) && defined(AFS_WEB_ENHANCEMENTS)
1429         if (!(flags & AFS_LOOKUP_NOEVAL))
1430             /* don't eval mount points */
1431 #endif /* UKERNEL && AFS_WEB_ENHANCEMENTS */
1432             if (tvc->mvstat == 1 && force_eval) {
1433                 /* a mt point, possibly unevaluated */
1434                 struct volume *tvolp;
1435
1436                 ObtainWriteLock(&tvc->lock, 133);
1437                 code = EvalMountPoint(tvc, adp, &tvolp, &treq);
1438                 ReleaseWriteLock(&tvc->lock);
1439
1440                 if (code) {
1441                     afs_PutVCache(tvc);
1442                     if (tvolp)
1443                         afs_PutVolume(tvolp, WRITE_LOCK);
1444                     goto done;
1445                 }
1446
1447                 /* next, we want to continue using the target of the mt point */
1448                 if (tvc->mvid && (tvc->states & CMValid)) {
1449                     struct vcache *uvc;
1450                     /* now lookup target, to set .. pointer */
1451                     afs_Trace2(afs_iclSetp, CM_TRACE_LOOKUP1,
1452                                ICL_TYPE_POINTER, tvc, ICL_TYPE_FID,
1453                                &tvc->fid);
1454                     uvc = tvc;  /* remember for later */
1455
1456                     if (tvolp && (tvolp->states & VForeign)) {
1457                         /* XXXX tvolp has ref cnt on but not locked! XXX */
1458                         tvc =
1459                             afs_GetRootVCache(tvc->mvid, &treq, NULL, tvolp);
1460                     } else {
1461                         tvc = afs_GetVCache(tvc->mvid, &treq, NULL, NULL);
1462                     }
1463                     afs_PutVCache(uvc); /* we're done with it */
1464
1465                     if (!tvc) {
1466                         code = ENOENT;
1467                         if (tvolp) {
1468                             afs_PutVolume(tvolp, WRITE_LOCK);
1469                         }
1470                         goto done;
1471                     }
1472
1473                     /* now, if we came via a new mt pt (say because of a new
1474                      * release of a R/O volume), we must reevaluate the ..
1475                      * ptr to point back to the appropriate place */
1476                     if (tvolp) {
1477                         ObtainWriteLock(&tvc->lock, 134);
1478                         if (tvc->mvid == NULL) {
1479                             tvc->mvid = (struct VenusFid *)
1480                                 osi_AllocSmallSpace(sizeof(struct VenusFid));
1481                         }
1482                         /* setup backpointer */
1483                         *tvc->mvid = tvolp->dotdot;
1484                         ReleaseWriteLock(&tvc->lock);
1485                         afs_PutVolume(tvolp, WRITE_LOCK);
1486                     }
1487                 } else {
1488                     afs_PutVCache(tvc);
1489                     code = ENOENT;
1490                     if (tvolp)
1491                         afs_PutVolume(tvolp, WRITE_LOCK);
1492                     goto done;
1493                 }
1494             }
1495         *avcp = tvc;
1496         if (tvc && !VREFCOUNT(tvc)) {
1497             osi_Panic("TT3");
1498         }
1499         code = 0;
1500     } else {
1501         /* if we get here, we found something in a directory that couldn't
1502          * be located (a Multics "connection failure").  If the volume is
1503          * read-only, we try flushing this entry from the cache and trying
1504          * again. */
1505         if (pass == 0) {
1506             struct volume *tv;
1507             tv = afs_GetVolume(&adp->fid, &treq, READ_LOCK);
1508             if (tv) {
1509                 if (tv->states & VRO) {
1510                     pass = 1;   /* try this *once* */
1511                     ObtainWriteLock(&afs_xcbhash, 495);
1512                     afs_DequeueCallback(adp);
1513                     /* re-stat to get later version */
1514                     adp->states &= ~CStatd;
1515                     ReleaseWriteLock(&afs_xcbhash);
1516                     osi_dnlc_purgedp(adp);
1517                     afs_PutVolume(tv, READ_LOCK);
1518                     goto redo;
1519                 }
1520                 afs_PutVolume(tv, READ_LOCK);
1521             }
1522         }
1523         code = ENOENT;
1524     }
1525
1526   done:
1527     /* put the network buffer back, if need be */
1528     if (tname != aname && tname)
1529         osi_FreeLargeSpace(tname);
1530     if (code == 0) {
1531 #ifdef  AFS_OSF_ENV
1532         /* Handle RENAME; only need to check rename "."  */
1533         if (opflag == RENAME && wantparent && *ndp->ni_next == 0) {
1534             if (!FidCmp(&(tvc->fid), &(adp->fid))) {
1535                 afs_PutVCache(*avcp);
1536                 *avcp = NULL;
1537                 afs_PutFakeStat(&fakestate);
1538                 return afs_CheckCode(EISDIR, &treq, 18);
1539             }
1540         }
1541 #endif /* AFS_OSF_ENV */
1542
1543         if (afs_mariner)
1544             afs_AddMarinerName(aname, tvc);
1545
1546 #if defined(UKERNEL) && defined(AFS_WEB_ENHANCEMENTS)
1547         if (!(flags & AFS_LOOKUP_NOEVAL))
1548             /* Here we don't enter the name into the DNLC because we want the
1549              * evaluated mount dir to be there (the vcache for the mounted volume)
1550              * rather than the vc of the mount point itself.  we can still find the
1551              * mount point's vc in the vcache by its fid. */
1552 #endif /* UKERNEL && AFS_WEB_ENHANCEMENTS */
1553             if (!hit) {
1554                 osi_dnlc_enter(adp, aname, tvc, &versionNo);
1555             } else {
1556 #ifdef AFS_LINUX20_ENV
1557                 /* So Linux inode cache is up to date. */
1558                 code = afs_VerifyVCache(tvc, &treq);
1559 #else
1560                 afs_PutFakeStat(&fakestate);
1561                 return 0;       /* can't have been any errors if hit and !code */
1562 #endif
1563             }
1564     }
1565     if (bulkcode)
1566         code = bulkcode;
1567     else
1568         code = afs_CheckCode(code, &treq, 19);
1569     if (code) {
1570         /* If there is an error, make sure *avcp is null.
1571          * Alphas panic otherwise - defect 10719.
1572          */
1573         *avcp = NULL;
1574     }
1575
1576     afs_PutFakeStat(&fakestate);
1577     return code;
1578 }