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