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