]> CyberLeo.Net >> Repos - FreeBSD/releng/9.1.git/blob - sys/kern/vfs_lookup.c
MFC r241096:
[FreeBSD/releng/9.1.git] / sys / kern / vfs_lookup.c
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)vfs_lookup.c        8.4 (Berkeley) 2/16/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_capsicum.h"
41 #include "opt_kdtrace.h"
42 #include "opt_ktrace.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/capability.h>
48 #include <sys/fcntl.h>
49 #include <sys/jail.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/namei.h>
53 #include <sys/vnode.h>
54 #include <sys/mount.h>
55 #include <sys/filedesc.h>
56 #include <sys/proc.h>
57 #include <sys/sdt.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
60 #ifdef KTRACE
61 #include <sys/ktrace.h>
62 #endif
63
64 #include <security/audit/audit.h>
65 #include <security/mac/mac_framework.h>
66
67 #include <vm/uma.h>
68
69 #define NAMEI_DIAGNOSTIC 1
70 #undef NAMEI_DIAGNOSTIC
71
72 SDT_PROVIDER_DECLARE(vfs);
73 SDT_PROBE_DEFINE3(vfs, namei, lookup, entry, entry, "struct vnode *", "char *",
74     "unsigned long");
75 SDT_PROBE_DEFINE2(vfs, namei, lookup, return, return, "int", "struct vnode *");
76
77 /*
78  * Allocation zone for namei
79  */
80 uma_zone_t namei_zone;
81 /*
82  * Placeholder vnode for mp traversal
83  */
84 static struct vnode *vp_crossmp;
85
86 static void
87 nameiinit(void *dummy __unused)
88 {
89
90         namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
91             UMA_ALIGN_PTR, 0);
92         getnewvnode("crossmp", NULL, &dead_vnodeops, &vp_crossmp);
93         vn_lock(vp_crossmp, LK_EXCLUSIVE);
94         VN_LOCK_ASHARE(vp_crossmp);
95         VOP_UNLOCK(vp_crossmp, 0);
96 }
97 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
98
99 static int lookup_shared = 1;
100 SYSCTL_INT(_vfs, OID_AUTO, lookup_shared, CTLFLAG_RW, &lookup_shared, 0,
101     "Enables/Disables shared locks for path name translation");
102 TUNABLE_INT("vfs.lookup_shared", &lookup_shared);
103
104 /*
105  * Convert a pathname into a pointer to a locked vnode.
106  *
107  * The FOLLOW flag is set when symbolic links are to be followed
108  * when they occur at the end of the name translation process.
109  * Symbolic links are always followed for all other pathname
110  * components other than the last.
111  *
112  * The segflg defines whether the name is to be copied from user
113  * space or kernel space.
114  *
115  * Overall outline of namei:
116  *
117  *      copy in name
118  *      get starting directory
119  *      while (!done && !error) {
120  *              call lookup to search path.
121  *              if symbolic link, massage name in buffer and continue
122  *      }
123  */
124 int
125 namei(struct nameidata *ndp)
126 {
127         struct filedesc *fdp;   /* pointer to file descriptor state */
128         char *cp;               /* pointer into pathname argument */
129         struct vnode *dp;       /* the directory we are searching */
130         struct iovec aiov;              /* uio for reading symbolic links */
131         struct uio auio;
132         int error, linklen;
133         struct componentname *cnp = &ndp->ni_cnd;
134         struct thread *td = cnp->cn_thread;
135         struct proc *p = td->td_proc;
136         int vfslocked;
137
138         KASSERT((cnp->cn_flags & MPSAFE) != 0 || mtx_owned(&Giant) != 0,
139             ("NOT MPSAFE and Giant not held"));
140         ndp->ni_cnd.cn_cred = ndp->ni_cnd.cn_thread->td_ucred;
141         KASSERT(cnp->cn_cred && p, ("namei: bad cred/proc"));
142         KASSERT((cnp->cn_nameiop & (~OPMASK)) == 0,
143             ("namei: nameiop contaminated with flags"));
144         KASSERT((cnp->cn_flags & OPMASK) == 0,
145             ("namei: flags contaminated with nameiops"));
146         if (!lookup_shared)
147                 cnp->cn_flags &= ~LOCKSHARED;
148         fdp = p->p_fd;
149
150         /* We will set this ourselves if we need it. */
151         cnp->cn_flags &= ~TRAILINGSLASH;
152
153         /*
154          * Get a buffer for the name to be translated, and copy the
155          * name into the buffer.
156          */
157         if ((cnp->cn_flags & HASBUF) == 0)
158                 cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
159         if (ndp->ni_segflg == UIO_SYSSPACE)
160                 error = copystr(ndp->ni_dirp, cnp->cn_pnbuf,
161                             MAXPATHLEN, (size_t *)&ndp->ni_pathlen);
162         else
163                 error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
164                             MAXPATHLEN, (size_t *)&ndp->ni_pathlen);
165
166         if (error == 0) {
167                 /*
168                  * If we are auditing the kernel pathname, save the user
169                  * pathname.
170                  */
171                 if (cnp->cn_flags & AUDITVNODE1)
172                         AUDIT_ARG_UPATH1(td, cnp->cn_pnbuf);
173                 if (cnp->cn_flags & AUDITVNODE2)
174                         AUDIT_ARG_UPATH2(td, cnp->cn_pnbuf);
175         }
176
177         /*
178          * Don't allow empty pathnames.
179          */
180         if (!error && *cnp->cn_pnbuf == '\0')
181                 error = ENOENT;
182
183 #ifdef CAPABILITY_MODE
184         /*
185          * In capability mode, lookups must be "strictly relative" (i.e.
186          * not an absolute path, and not containing '..' components) to
187          * a real file descriptor, not the pseudo-descriptor AT_FDCWD.
188          */
189         if (IN_CAPABILITY_MODE(td)) {
190                 ndp->ni_strictrelative = 1;
191                 if (ndp->ni_dirfd == AT_FDCWD)
192                         error = ECAPMODE;
193         }
194 #endif
195         if (error) {
196                 uma_zfree(namei_zone, cnp->cn_pnbuf);
197 #ifdef DIAGNOSTIC
198                 cnp->cn_pnbuf = NULL;
199                 cnp->cn_nameptr = NULL;
200 #endif
201                 ndp->ni_vp = NULL;
202                 return (error);
203         }
204         ndp->ni_loopcnt = 0;
205 #ifdef KTRACE
206         if (KTRPOINT(td, KTR_NAMEI)) {
207                 KASSERT(cnp->cn_thread == curthread,
208                     ("namei not using curthread"));
209                 ktrnamei(cnp->cn_pnbuf);
210         }
211 #endif
212         /*
213          * Get starting point for the translation.
214          */
215         FILEDESC_SLOCK(fdp);
216         ndp->ni_rootdir = fdp->fd_rdir;
217         ndp->ni_topdir = fdp->fd_jdir;
218
219         dp = NULL;
220         if (cnp->cn_pnbuf[0] != '/') {
221                 if (ndp->ni_startdir != NULL) {
222                         dp = ndp->ni_startdir;
223                         error = 0;
224                 } else if (ndp->ni_dirfd != AT_FDCWD) {
225                         if (cnp->cn_flags & AUDITVNODE1)
226                                 AUDIT_ARG_ATFD1(ndp->ni_dirfd);
227                         if (cnp->cn_flags & AUDITVNODE2)
228                                 AUDIT_ARG_ATFD2(ndp->ni_dirfd);
229                         error = fgetvp_rights(td, ndp->ni_dirfd,
230                             ndp->ni_rightsneeded | CAP_LOOKUP,
231                             &(ndp->ni_baserights), &dp);
232 #ifdef CAPABILITIES
233                         /*
234                          * Lookups relative to a capability must also be
235                          * strictly relative.
236                          *
237                          * Note that a capability with rights CAP_MASK_VALID
238                          * is treated exactly like a regular file descriptor.
239                          */
240                         if (ndp->ni_baserights != CAP_MASK_VALID)
241                                 ndp->ni_strictrelative = 1;
242 #endif
243                 }
244                 if (error != 0 || dp != NULL) {
245                         FILEDESC_SUNLOCK(fdp);
246                         if (error == 0 && dp->v_type != VDIR) {
247                                 vfslocked = VFS_LOCK_GIANT(dp->v_mount);
248                                 vrele(dp);
249                                 VFS_UNLOCK_GIANT(vfslocked);
250                                 error = ENOTDIR;
251                         }
252                 }
253                 if (error) {
254                         uma_zfree(namei_zone, cnp->cn_pnbuf);
255 #ifdef DIAGNOSTIC
256                         cnp->cn_pnbuf = NULL;
257                         cnp->cn_nameptr = NULL;
258 #endif
259                         return (error);
260                 }
261         }
262         if (dp == NULL) {
263                 dp = fdp->fd_cdir;
264                 VREF(dp);
265                 FILEDESC_SUNLOCK(fdp);
266                 if (ndp->ni_startdir != NULL) {
267                         vfslocked = VFS_LOCK_GIANT(ndp->ni_startdir->v_mount);
268                         vrele(ndp->ni_startdir);
269                         VFS_UNLOCK_GIANT(vfslocked);
270                 }
271         }
272         SDT_PROBE(vfs, namei, lookup, entry, dp, cnp->cn_pnbuf,
273             cnp->cn_flags, 0, 0);
274         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
275         for (;;) {
276                 /*
277                  * Check if root directory should replace current directory.
278                  * Done at start of translation and after symbolic link.
279                  */
280                 cnp->cn_nameptr = cnp->cn_pnbuf;
281                 if (*(cnp->cn_nameptr) == '/') {
282                         vrele(dp);
283                         VFS_UNLOCK_GIANT(vfslocked);
284                         if (ndp->ni_strictrelative != 0)
285                                 return (ENOTCAPABLE);
286                         while (*(cnp->cn_nameptr) == '/') {
287                                 cnp->cn_nameptr++;
288                                 ndp->ni_pathlen--;
289                         }
290                         dp = ndp->ni_rootdir;
291                         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
292                         VREF(dp);
293                 }
294                 if (vfslocked)
295                         ndp->ni_cnd.cn_flags |= GIANTHELD;
296                 ndp->ni_startdir = dp;
297                 error = lookup(ndp);
298                 if (error) {
299                         uma_zfree(namei_zone, cnp->cn_pnbuf);
300 #ifdef DIAGNOSTIC
301                         cnp->cn_pnbuf = NULL;
302                         cnp->cn_nameptr = NULL;
303 #endif
304                         SDT_PROBE(vfs, namei, lookup, return, error, NULL, 0,
305                             0, 0);
306                         return (error);
307                 }
308                 vfslocked = (ndp->ni_cnd.cn_flags & GIANTHELD) != 0;
309                 ndp->ni_cnd.cn_flags &= ~GIANTHELD;
310                 /*
311                  * If not a symbolic link, we're done.
312                  */
313                 if ((cnp->cn_flags & ISSYMLINK) == 0) {
314                         if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0) {
315                                 uma_zfree(namei_zone, cnp->cn_pnbuf);
316 #ifdef DIAGNOSTIC
317                                 cnp->cn_pnbuf = NULL;
318                                 cnp->cn_nameptr = NULL;
319 #endif
320                         } else
321                                 cnp->cn_flags |= HASBUF;
322
323                         if ((cnp->cn_flags & MPSAFE) == 0) {
324                                 VFS_UNLOCK_GIANT(vfslocked);
325                         } else if (vfslocked)
326                                 ndp->ni_cnd.cn_flags |= GIANTHELD;
327                         SDT_PROBE(vfs, namei, lookup, return, 0, ndp->ni_vp,
328                             0, 0, 0);
329                         return (0);
330                 }
331                 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
332                         error = ELOOP;
333                         break;
334                 }
335 #ifdef MAC
336                 if ((cnp->cn_flags & NOMACCHECK) == 0) {
337                         error = mac_vnode_check_readlink(td->td_ucred,
338                             ndp->ni_vp);
339                         if (error)
340                                 break;
341                 }
342 #endif
343                 if (ndp->ni_pathlen > 1)
344                         cp = uma_zalloc(namei_zone, M_WAITOK);
345                 else
346                         cp = cnp->cn_pnbuf;
347                 aiov.iov_base = cp;
348                 aiov.iov_len = MAXPATHLEN;
349                 auio.uio_iov = &aiov;
350                 auio.uio_iovcnt = 1;
351                 auio.uio_offset = 0;
352                 auio.uio_rw = UIO_READ;
353                 auio.uio_segflg = UIO_SYSSPACE;
354                 auio.uio_td = (struct thread *)0;
355                 auio.uio_resid = MAXPATHLEN;
356                 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
357                 if (error) {
358                         if (ndp->ni_pathlen > 1)
359                                 uma_zfree(namei_zone, cp);
360                         break;
361                 }
362                 linklen = MAXPATHLEN - auio.uio_resid;
363                 if (linklen == 0) {
364                         if (ndp->ni_pathlen > 1)
365                                 uma_zfree(namei_zone, cp);
366                         error = ENOENT;
367                         break;
368                 }
369                 if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
370                         if (ndp->ni_pathlen > 1)
371                                 uma_zfree(namei_zone, cp);
372                         error = ENAMETOOLONG;
373                         break;
374                 }
375                 if (ndp->ni_pathlen > 1) {
376                         bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
377                         uma_zfree(namei_zone, cnp->cn_pnbuf);
378                         cnp->cn_pnbuf = cp;
379                 } else
380                         cnp->cn_pnbuf[linklen] = '\0';
381                 ndp->ni_pathlen += linklen;
382                 vput(ndp->ni_vp);
383                 dp = ndp->ni_dvp;
384         }
385         uma_zfree(namei_zone, cnp->cn_pnbuf);
386 #ifdef DIAGNOSTIC
387         cnp->cn_pnbuf = NULL;
388         cnp->cn_nameptr = NULL;
389 #endif
390         vput(ndp->ni_vp);
391         ndp->ni_vp = NULL;
392         vrele(ndp->ni_dvp);
393         VFS_UNLOCK_GIANT(vfslocked);
394         SDT_PROBE(vfs, namei, lookup, return, error, NULL, 0, 0, 0);
395         return (error);
396 }
397
398 static int
399 compute_cn_lkflags(struct mount *mp, int lkflags)
400 {
401
402         if (mp == NULL || 
403             ((lkflags & LK_SHARED) && !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
404                 lkflags &= ~LK_SHARED;
405                 lkflags |= LK_EXCLUSIVE;
406         }
407         return (lkflags);
408 }
409
410 static __inline int
411 needs_exclusive_leaf(struct mount *mp, int flags)
412 {
413
414         /*
415          * Intermediate nodes can use shared locks, we only need to
416          * force an exclusive lock for leaf nodes.
417          */
418         if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
419                 return (0);
420
421         /* Always use exclusive locks if LOCKSHARED isn't set. */
422         if (!(flags & LOCKSHARED))
423                 return (1);
424
425         /*
426          * For lookups during open(), if the mount point supports
427          * extended shared operations, then use a shared lock for the
428          * leaf node, otherwise use an exclusive lock.
429          */
430         if (flags & ISOPEN) {
431                 if (mp != NULL &&
432                     (mp->mnt_kern_flag & MNTK_EXTENDED_SHARED))
433                         return (0);
434                 else
435                         return (1);
436         }
437
438         /*
439          * Lookup requests outside of open() that specify LOCKSHARED
440          * only need a shared lock on the leaf vnode.
441          */
442         return (0);
443 }
444
445 /*
446  * Search a pathname.
447  * This is a very central and rather complicated routine.
448  *
449  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
450  * The starting directory is taken from ni_startdir. The pathname is
451  * descended until done, or a symbolic link is encountered. The variable
452  * ni_more is clear if the path is completed; it is set to one if a
453  * symbolic link needing interpretation is encountered.
454  *
455  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
456  * whether the name is to be looked up, created, renamed, or deleted.
457  * When CREATE, RENAME, or DELETE is specified, information usable in
458  * creating, renaming, or deleting a directory entry may be calculated.
459  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
460  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
461  * returned unlocked. Otherwise the parent directory is not returned. If
462  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
463  * the target is returned locked, otherwise it is returned unlocked.
464  * When creating or renaming and LOCKPARENT is specified, the target may not
465  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
466  *
467  * Overall outline of lookup:
468  *
469  * dirloop:
470  *      identify next component of name at ndp->ni_ptr
471  *      handle degenerate case where name is null string
472  *      if .. and crossing mount points and on mounted filesys, find parent
473  *      call VOP_LOOKUP routine for next component name
474  *          directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
475  *          component vnode returned in ni_vp (if it exists), locked.
476  *      if result vnode is mounted on and crossing mount points,
477  *          find mounted on vnode
478  *      if more components of name, do next level at dirloop
479  *      return the answer in ni_vp, locked if LOCKLEAF set
480  *          if LOCKPARENT set, return locked parent in ni_dvp
481  *          if WANTPARENT set, return unlocked parent in ni_dvp
482  */
483 int
484 lookup(struct nameidata *ndp)
485 {
486         char *cp;               /* pointer into pathname argument */
487         struct vnode *dp = 0;   /* the directory we are searching */
488         struct vnode *tdp;              /* saved dp */
489         struct mount *mp;               /* mount table entry */
490         struct prison *pr;
491         int docache;                    /* == 0 do not cache last component */
492         int wantparent;                 /* 1 => wantparent or lockparent flag */
493         int rdonly;                     /* lookup read-only flag bit */
494         int error = 0;
495         int dpunlocked = 0;             /* dp has already been unlocked */
496         struct componentname *cnp = &ndp->ni_cnd;
497         int vfslocked;                  /* VFS Giant state for child */
498         int dvfslocked;                 /* VFS Giant state for parent */
499         int tvfslocked;
500         int lkflags_save;
501         int ni_dvp_unlocked;
502         
503         /*
504          * Setup: break out flag bits into variables.
505          */
506         dvfslocked = (ndp->ni_cnd.cn_flags & GIANTHELD) != 0;
507         vfslocked = 0;
508         ni_dvp_unlocked = 0;
509         ndp->ni_cnd.cn_flags &= ~GIANTHELD;
510         wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
511         KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
512             ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
513         docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
514         if (cnp->cn_nameiop == DELETE ||
515             (wantparent && cnp->cn_nameiop != CREATE &&
516              cnp->cn_nameiop != LOOKUP))
517                 docache = 0;
518         rdonly = cnp->cn_flags & RDONLY;
519         cnp->cn_flags &= ~ISSYMLINK;
520         ndp->ni_dvp = NULL;
521         /*
522          * We use shared locks until we hit the parent of the last cn then
523          * we adjust based on the requesting flags.
524          */
525         if (lookup_shared)
526                 cnp->cn_lkflags = LK_SHARED;
527         else
528                 cnp->cn_lkflags = LK_EXCLUSIVE;
529         dp = ndp->ni_startdir;
530         ndp->ni_startdir = NULLVP;
531         vn_lock(dp,
532             compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY));
533
534 dirloop:
535         /*
536          * Search a new directory.
537          *
538          * The last component of the filename is left accessible via
539          * cnp->cn_nameptr for callers that need the name. Callers needing
540          * the name set the SAVENAME flag. When done, they assume
541          * responsibility for freeing the pathname buffer.
542          */
543         cnp->cn_consume = 0;
544         for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
545                 continue;
546         cnp->cn_namelen = cp - cnp->cn_nameptr;
547         if (cnp->cn_namelen > NAME_MAX) {
548                 error = ENAMETOOLONG;
549                 goto bad;
550         }
551 #ifdef NAMEI_DIAGNOSTIC
552         { char c = *cp;
553         *cp = '\0';
554         printf("{%s}: ", cnp->cn_nameptr);
555         *cp = c; }
556 #endif
557         ndp->ni_pathlen -= cnp->cn_namelen;
558         ndp->ni_next = cp;
559
560         /*
561          * Replace multiple slashes by a single slash and trailing slashes
562          * by a null.  This must be done before VOP_LOOKUP() because some
563          * fs's don't know about trailing slashes.  Remember if there were
564          * trailing slashes to handle symlinks, existing non-directories
565          * and non-existing files that won't be directories specially later.
566          */
567         while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
568                 cp++;
569                 ndp->ni_pathlen--;
570                 if (*cp == '\0') {
571                         *ndp->ni_next = '\0';
572                         cnp->cn_flags |= TRAILINGSLASH;
573                 }
574         }
575         ndp->ni_next = cp;
576
577         cnp->cn_flags |= MAKEENTRY;
578         if (*cp == '\0' && docache == 0)
579                 cnp->cn_flags &= ~MAKEENTRY;
580         if (cnp->cn_namelen == 2 &&
581             cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
582                 cnp->cn_flags |= ISDOTDOT;
583         else
584                 cnp->cn_flags &= ~ISDOTDOT;
585         if (*ndp->ni_next == 0)
586                 cnp->cn_flags |= ISLASTCN;
587         else
588                 cnp->cn_flags &= ~ISLASTCN;
589
590         if ((cnp->cn_flags & ISLASTCN) != 0 &&
591             cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
592             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
593                 error = EINVAL;
594                 goto bad;
595         }
596
597         /*
598          * Check for degenerate name (e.g. / or "")
599          * which is a way of talking about a directory,
600          * e.g. like "/." or ".".
601          */
602         if (cnp->cn_nameptr[0] == '\0') {
603                 if (dp->v_type != VDIR) {
604                         error = ENOTDIR;
605                         goto bad;
606                 }
607                 if (cnp->cn_nameiop != LOOKUP) {
608                         error = EISDIR;
609                         goto bad;
610                 }
611                 if (wantparent) {
612                         ndp->ni_dvp = dp;
613                         VREF(dp);
614                 }
615                 ndp->ni_vp = dp;
616
617                 if (cnp->cn_flags & AUDITVNODE1)
618                         AUDIT_ARG_VNODE1(dp);
619                 else if (cnp->cn_flags & AUDITVNODE2)
620                         AUDIT_ARG_VNODE2(dp);
621
622                 if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
623                         VOP_UNLOCK(dp, 0);
624                 /* XXX This should probably move to the top of function. */
625                 if (cnp->cn_flags & SAVESTART)
626                         panic("lookup: SAVESTART");
627                 goto success;
628         }
629
630         /*
631          * Handle "..": five special cases.
632          * 0. If doing a capability lookup, return ENOTCAPABLE (this is a
633          *    fairly conservative design choice, but it's the only one that we
634          *    are satisfied guarantees the property we're looking for).
635          * 1. Return an error if this is the last component of
636          *    the name and the operation is DELETE or RENAME.
637          * 2. If at root directory (e.g. after chroot)
638          *    or at absolute root directory
639          *    then ignore it so can't get out.
640          * 3. If this vnode is the root of a mounted
641          *    filesystem, then replace it with the
642          *    vnode which was mounted on so we take the
643          *    .. in the other filesystem.
644          * 4. If the vnode is the top directory of
645          *    the jail or chroot, don't let them out.
646          */
647         if (cnp->cn_flags & ISDOTDOT) {
648                 if (ndp->ni_strictrelative != 0) {
649                         error = ENOTCAPABLE;
650                         goto bad;
651                 }
652                 if ((cnp->cn_flags & ISLASTCN) != 0 &&
653                     (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
654                         error = EINVAL;
655                         goto bad;
656                 }
657                 for (;;) {
658                         for (pr = cnp->cn_cred->cr_prison; pr != NULL;
659                              pr = pr->pr_parent)
660                                 if (dp == pr->pr_root)
661                                         break;
662                         if (dp == ndp->ni_rootdir || 
663                             dp == ndp->ni_topdir || 
664                             dp == rootvnode ||
665                             pr != NULL ||
666                             ((dp->v_vflag & VV_ROOT) != 0 &&
667                              (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
668                                 ndp->ni_dvp = dp;
669                                 ndp->ni_vp = dp;
670                                 vfslocked = VFS_LOCK_GIANT(dp->v_mount);
671                                 VREF(dp);
672                                 goto nextname;
673                         }
674                         if ((dp->v_vflag & VV_ROOT) == 0)
675                                 break;
676                         if (dp->v_iflag & VI_DOOMED) {  /* forced unmount */
677                                 error = ENOENT;
678                                 goto bad;
679                         }
680                         tdp = dp;
681                         dp = dp->v_mount->mnt_vnodecovered;
682                         tvfslocked = dvfslocked;
683                         dvfslocked = VFS_LOCK_GIANT(dp->v_mount);
684                         VREF(dp);
685                         vput(tdp);
686                         VFS_UNLOCK_GIANT(tvfslocked);
687                         vn_lock(dp,
688                             compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
689                             LK_RETRY));
690                 }
691         }
692
693         /*
694          * We now have a segment name to search for, and a directory to search.
695          */
696 unionlookup:
697 #ifdef MAC
698         if ((cnp->cn_flags & NOMACCHECK) == 0) {
699                 error = mac_vnode_check_lookup(cnp->cn_thread->td_ucred, dp,
700                     cnp);
701                 if (error)
702                         goto bad;
703         }
704 #endif
705         ndp->ni_dvp = dp;
706         ndp->ni_vp = NULL;
707         ASSERT_VOP_LOCKED(dp, "lookup");
708         VNASSERT(vfslocked == 0, dp, ("lookup: vfslocked %d", vfslocked));
709         /*
710          * If we have a shared lock we may need to upgrade the lock for the
711          * last operation.
712          */
713         if (dp != vp_crossmp &&
714             VOP_ISLOCKED(dp) == LK_SHARED &&
715             (cnp->cn_flags & ISLASTCN) && (cnp->cn_flags & LOCKPARENT))
716                 vn_lock(dp, LK_UPGRADE|LK_RETRY);
717         /*
718          * If we're looking up the last component and we need an exclusive
719          * lock, adjust our lkflags.
720          */
721         if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
722                 cnp->cn_lkflags = LK_EXCLUSIVE;
723 #ifdef NAMEI_DIAGNOSTIC
724         vprint("lookup in", dp);
725 #endif
726         lkflags_save = cnp->cn_lkflags;
727         cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags);
728         if ((error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp)) != 0) {
729                 cnp->cn_lkflags = lkflags_save;
730                 KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
731 #ifdef NAMEI_DIAGNOSTIC
732                 printf("not found\n");
733 #endif
734                 if ((error == ENOENT) &&
735                     (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
736                     (dp->v_mount->mnt_flag & MNT_UNION)) {
737                         tdp = dp;
738                         dp = dp->v_mount->mnt_vnodecovered;
739                         tvfslocked = dvfslocked;
740                         dvfslocked = VFS_LOCK_GIANT(dp->v_mount);
741                         VREF(dp);
742                         vput(tdp);
743                         VFS_UNLOCK_GIANT(tvfslocked);
744                         vn_lock(dp,
745                             compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
746                             LK_RETRY));
747                         goto unionlookup;
748                 }
749
750                 if (error != EJUSTRETURN)
751                         goto bad;
752                 /*
753                  * At this point, we know we're at the end of the
754                  * pathname.  If creating / renaming, we can consider
755                  * allowing the file or directory to be created / renamed,
756                  * provided we're not on a read-only filesystem.
757                  */
758                 if (rdonly) {
759                         error = EROFS;
760                         goto bad;
761                 }
762                 /* trailing slash only allowed for directories */
763                 if ((cnp->cn_flags & TRAILINGSLASH) &&
764                     !(cnp->cn_flags & WILLBEDIR)) {
765                         error = ENOENT;
766                         goto bad;
767                 }
768                 if ((cnp->cn_flags & LOCKPARENT) == 0)
769                         VOP_UNLOCK(dp, 0);
770                 /*
771                  * We return with ni_vp NULL to indicate that the entry
772                  * doesn't currently exist, leaving a pointer to the
773                  * (possibly locked) directory vnode in ndp->ni_dvp.
774                  */
775                 if (cnp->cn_flags & SAVESTART) {
776                         ndp->ni_startdir = ndp->ni_dvp;
777                         VREF(ndp->ni_startdir);
778                 }
779                 goto success;
780         } else
781                 cnp->cn_lkflags = lkflags_save;
782 #ifdef NAMEI_DIAGNOSTIC
783         printf("found\n");
784 #endif
785         /*
786          * Take into account any additional components consumed by
787          * the underlying filesystem.
788          */
789         if (cnp->cn_consume > 0) {
790                 cnp->cn_nameptr += cnp->cn_consume;
791                 ndp->ni_next += cnp->cn_consume;
792                 ndp->ni_pathlen -= cnp->cn_consume;
793                 cnp->cn_consume = 0;
794         }
795
796         dp = ndp->ni_vp;
797         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
798
799         /*
800          * Check to see if the vnode has been mounted on;
801          * if so find the root of the mounted filesystem.
802          */
803         while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
804                (cnp->cn_flags & NOCROSSMOUNT) == 0) {
805                 if (vfs_busy(mp, 0))
806                         continue;
807                 vput(dp);
808                 VFS_UNLOCK_GIANT(vfslocked);
809                 vfslocked = VFS_LOCK_GIANT(mp);
810                 if (dp != ndp->ni_dvp)
811                         vput(ndp->ni_dvp);
812                 else
813                         vrele(ndp->ni_dvp);
814                 VFS_UNLOCK_GIANT(dvfslocked);
815                 dvfslocked = 0;
816                 vref(vp_crossmp);
817                 ndp->ni_dvp = vp_crossmp;
818                 error = VFS_ROOT(mp, compute_cn_lkflags(mp, cnp->cn_lkflags),
819                     &tdp);
820                 vfs_unbusy(mp);
821                 if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
822                         panic("vp_crossmp exclusively locked or reclaimed");
823                 if (error) {
824                         dpunlocked = 1;
825                         goto bad2;
826                 }
827                 ndp->ni_vp = dp = tdp;
828         }
829
830         /*
831          * Check for symbolic link
832          */
833         if ((dp->v_type == VLNK) &&
834             ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
835              *ndp->ni_next == '/')) {
836                 cnp->cn_flags |= ISSYMLINK;
837                 if (dp->v_iflag & VI_DOOMED) {
838                         /*
839                          * We can't know whether the directory was mounted with
840                          * NOSYMFOLLOW, so we can't follow safely.
841                          */
842                         error = ENOENT;
843                         goto bad2;
844                 }
845                 if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
846                         error = EACCES;
847                         goto bad2;
848                 }
849                 /*
850                  * Symlink code always expects an unlocked dvp.
851                  */
852                 if (ndp->ni_dvp != ndp->ni_vp) {
853                         VOP_UNLOCK(ndp->ni_dvp, 0);
854                         ni_dvp_unlocked = 1;
855                 }
856                 goto success;
857         }
858
859 nextname:
860         /*
861          * Not a symbolic link that we will follow.  Continue with the
862          * next component if there is any; otherwise, we're done.
863          */
864         KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
865             ("lookup: invalid path state."));
866         if (*ndp->ni_next == '/') {
867                 cnp->cn_nameptr = ndp->ni_next;
868                 while (*cnp->cn_nameptr == '/') {
869                         cnp->cn_nameptr++;
870                         ndp->ni_pathlen--;
871                 }
872                 if (ndp->ni_dvp != dp)
873                         vput(ndp->ni_dvp);
874                 else
875                         vrele(ndp->ni_dvp);
876                 VFS_UNLOCK_GIANT(dvfslocked);
877                 dvfslocked = vfslocked; /* dp becomes dvp in dirloop */
878                 vfslocked = 0;
879                 goto dirloop;
880         }
881         /*
882          * If we're processing a path with a trailing slash,
883          * check that the end result is a directory.
884          */
885         if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
886                 error = ENOTDIR;
887                 goto bad2;
888         }
889         /*
890          * Disallow directory write attempts on read-only filesystems.
891          */
892         if (rdonly &&
893             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
894                 error = EROFS;
895                 goto bad2;
896         }
897         if (cnp->cn_flags & SAVESTART) {
898                 ndp->ni_startdir = ndp->ni_dvp;
899                 VREF(ndp->ni_startdir);
900         }
901         if (!wantparent) {
902                 ni_dvp_unlocked = 2;
903                 if (ndp->ni_dvp != dp)
904                         vput(ndp->ni_dvp);
905                 else
906                         vrele(ndp->ni_dvp);
907                 VFS_UNLOCK_GIANT(dvfslocked);
908                 dvfslocked = 0;
909         } else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
910                 VOP_UNLOCK(ndp->ni_dvp, 0);
911                 ni_dvp_unlocked = 1;
912         }
913
914         if (cnp->cn_flags & AUDITVNODE1)
915                 AUDIT_ARG_VNODE1(dp);
916         else if (cnp->cn_flags & AUDITVNODE2)
917                 AUDIT_ARG_VNODE2(dp);
918
919         if ((cnp->cn_flags & LOCKLEAF) == 0)
920                 VOP_UNLOCK(dp, 0);
921 success:
922         /*
923          * Because of lookup_shared we may have the vnode shared locked, but
924          * the caller may want it to be exclusively locked.
925          */
926         if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
927             VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
928                 vn_lock(dp, LK_UPGRADE | LK_RETRY);
929                 if (dp->v_iflag & VI_DOOMED) {
930                         error = ENOENT;
931                         goto bad2;
932                 }
933         }
934         if (vfslocked && dvfslocked)
935                 VFS_UNLOCK_GIANT(dvfslocked);   /* Only need one */
936         if (vfslocked || dvfslocked)
937                 ndp->ni_cnd.cn_flags |= GIANTHELD;
938         return (0);
939
940 bad2:
941         if (ni_dvp_unlocked != 2) {
942                 if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
943                         vput(ndp->ni_dvp);
944                 else
945                         vrele(ndp->ni_dvp);
946         }
947 bad:
948         if (!dpunlocked)
949                 vput(dp);
950         VFS_UNLOCK_GIANT(vfslocked);
951         VFS_UNLOCK_GIANT(dvfslocked);
952         ndp->ni_cnd.cn_flags &= ~GIANTHELD;
953         ndp->ni_vp = NULL;
954         return (error);
955 }
956
957 /*
958  * relookup - lookup a path name component
959  *    Used by lookup to re-acquire things.
960  */
961 int
962 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
963 {
964         struct vnode *dp = 0;           /* the directory we are searching */
965         int wantparent;                 /* 1 => wantparent or lockparent flag */
966         int rdonly;                     /* lookup read-only flag bit */
967         int error = 0;
968
969         KASSERT(cnp->cn_flags & ISLASTCN,
970             ("relookup: Not given last component."));
971         /*
972          * Setup: break out flag bits into variables.
973          */
974         wantparent = cnp->cn_flags & (LOCKPARENT|WANTPARENT);
975         KASSERT(wantparent, ("relookup: parent not wanted."));
976         rdonly = cnp->cn_flags & RDONLY;
977         cnp->cn_flags &= ~ISSYMLINK;
978         dp = dvp;
979         cnp->cn_lkflags = LK_EXCLUSIVE;
980         vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
981
982         /*
983          * Search a new directory.
984          *
985          * The last component of the filename is left accessible via
986          * cnp->cn_nameptr for callers that need the name. Callers needing
987          * the name set the SAVENAME flag. When done, they assume
988          * responsibility for freeing the pathname buffer.
989          */
990 #ifdef NAMEI_DIAGNOSTIC
991         printf("{%s}: ", cnp->cn_nameptr);
992 #endif
993
994         /*
995          * Check for "" which represents the root directory after slash
996          * removal.
997          */
998         if (cnp->cn_nameptr[0] == '\0') {
999                 /*
1000                  * Support only LOOKUP for "/" because lookup()
1001                  * can't succeed for CREATE, DELETE and RENAME.
1002                  */
1003                 KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1004                 KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1005
1006                 if (!(cnp->cn_flags & LOCKLEAF))
1007                         VOP_UNLOCK(dp, 0);
1008                 *vpp = dp;
1009                 /* XXX This should probably move to the top of function. */
1010                 if (cnp->cn_flags & SAVESTART)
1011                         panic("lookup: SAVESTART");
1012                 return (0);
1013         }
1014
1015         if (cnp->cn_flags & ISDOTDOT)
1016                 panic ("relookup: lookup on dot-dot");
1017
1018         /*
1019          * We now have a segment name to search for, and a directory to search.
1020          */
1021 #ifdef NAMEI_DIAGNOSTIC
1022         vprint("search in:", dp);
1023 #endif
1024         if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1025                 KASSERT(*vpp == NULL, ("leaf should be empty"));
1026                 if (error != EJUSTRETURN)
1027                         goto bad;
1028                 /*
1029                  * If creating and at end of pathname, then can consider
1030                  * allowing file to be created.
1031                  */
1032                 if (rdonly) {
1033                         error = EROFS;
1034                         goto bad;
1035                 }
1036                 /* ASSERT(dvp == ndp->ni_startdir) */
1037                 if (cnp->cn_flags & SAVESTART)
1038                         VREF(dvp);
1039                 if ((cnp->cn_flags & LOCKPARENT) == 0)
1040                         VOP_UNLOCK(dp, 0);
1041                 /*
1042                  * We return with ni_vp NULL to indicate that the entry
1043                  * doesn't currently exist, leaving a pointer to the
1044                  * (possibly locked) directory vnode in ndp->ni_dvp.
1045                  */
1046                 return (0);
1047         }
1048
1049         dp = *vpp;
1050
1051         /*
1052          * Disallow directory write attempts on read-only filesystems.
1053          */
1054         if (rdonly &&
1055             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1056                 if (dvp == dp)
1057                         vrele(dvp);
1058                 else
1059                         vput(dvp);
1060                 error = EROFS;
1061                 goto bad;
1062         }
1063         /*
1064          * Set the parent lock/ref state to the requested state.
1065          */
1066         if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp) {
1067                 if (wantparent)
1068                         VOP_UNLOCK(dvp, 0);
1069                 else
1070                         vput(dvp);
1071         } else if (!wantparent)
1072                 vrele(dvp);
1073         /*
1074          * Check for symbolic link
1075          */
1076         KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1077             ("relookup: symlink found.\n"));
1078
1079         /* ASSERT(dvp == ndp->ni_startdir) */
1080         if (cnp->cn_flags & SAVESTART)
1081                 VREF(dvp);
1082         
1083         if ((cnp->cn_flags & LOCKLEAF) == 0)
1084                 VOP_UNLOCK(dp, 0);
1085         return (0);
1086 bad:
1087         vput(dp);
1088         *vpp = NULL;
1089         return (error);
1090 }
1091
1092 /*
1093  * Free data allocated by namei(); see namei(9) for details.
1094  */
1095 void
1096 NDFREE(struct nameidata *ndp, const u_int flags)
1097 {
1098         int unlock_dvp;
1099         int unlock_vp;
1100
1101         unlock_dvp = 0;
1102         unlock_vp = 0;
1103
1104         if (!(flags & NDF_NO_FREE_PNBUF) &&
1105             (ndp->ni_cnd.cn_flags & HASBUF)) {
1106                 uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
1107                 ndp->ni_cnd.cn_flags &= ~HASBUF;
1108         }
1109         if (!(flags & NDF_NO_VP_UNLOCK) &&
1110             (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
1111                 unlock_vp = 1;
1112         if (!(flags & NDF_NO_VP_RELE) && ndp->ni_vp) {
1113                 if (unlock_vp) {
1114                         vput(ndp->ni_vp);
1115                         unlock_vp = 0;
1116                 } else
1117                         vrele(ndp->ni_vp);
1118                 ndp->ni_vp = NULL;
1119         }
1120         if (unlock_vp)
1121                 VOP_UNLOCK(ndp->ni_vp, 0);
1122         if (!(flags & NDF_NO_DVP_UNLOCK) &&
1123             (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
1124             ndp->ni_dvp != ndp->ni_vp)
1125                 unlock_dvp = 1;
1126         if (!(flags & NDF_NO_DVP_RELE) &&
1127             (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
1128                 if (unlock_dvp) {
1129                         vput(ndp->ni_dvp);
1130                         unlock_dvp = 0;
1131                 } else
1132                         vrele(ndp->ni_dvp);
1133                 ndp->ni_dvp = NULL;
1134         }
1135         if (unlock_dvp)
1136                 VOP_UNLOCK(ndp->ni_dvp, 0);
1137         if (!(flags & NDF_NO_STARTDIR_RELE) &&
1138             (ndp->ni_cnd.cn_flags & SAVESTART)) {
1139                 vrele(ndp->ni_startdir);
1140                 ndp->ni_startdir = NULL;
1141         }
1142 }
1143
1144 /*
1145  * Determine if there is a suitable alternate filename under the specified
1146  * prefix for the specified path.  If the create flag is set, then the
1147  * alternate prefix will be used so long as the parent directory exists.
1148  * This is used by the various compatiblity ABIs so that Linux binaries prefer
1149  * files under /compat/linux for example.  The chosen path (whether under
1150  * the prefix or under /) is returned in a kernel malloc'd buffer pointed
1151  * to by pathbuf.  The caller is responsible for free'ing the buffer from
1152  * the M_TEMP bucket if one is returned.
1153  */
1154 int
1155 kern_alternate_path(struct thread *td, const char *prefix, const char *path,
1156     enum uio_seg pathseg, char **pathbuf, int create, int dirfd)
1157 {
1158         struct nameidata nd, ndroot;
1159         char *ptr, *buf, *cp;
1160         size_t len, sz;
1161         int error;
1162
1163         buf = (char *) malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1164         *pathbuf = buf;
1165
1166         /* Copy the prefix into the new pathname as a starting point. */
1167         len = strlcpy(buf, prefix, MAXPATHLEN);
1168         if (len >= MAXPATHLEN) {
1169                 *pathbuf = NULL;
1170                 free(buf, M_TEMP);
1171                 return (EINVAL);
1172         }
1173         sz = MAXPATHLEN - len;
1174         ptr = buf + len;
1175
1176         /* Append the filename to the prefix. */
1177         if (pathseg == UIO_SYSSPACE)
1178                 error = copystr(path, ptr, sz, &len);
1179         else
1180                 error = copyinstr(path, ptr, sz, &len);
1181
1182         if (error) {
1183                 *pathbuf = NULL;
1184                 free(buf, M_TEMP);
1185                 return (error);
1186         }
1187
1188         /* Only use a prefix with absolute pathnames. */
1189         if (*ptr != '/') {
1190                 error = EINVAL;
1191                 goto keeporig;
1192         }
1193
1194         if (dirfd != AT_FDCWD) {
1195                 /*
1196                  * We want the original because the "prefix" is
1197                  * included in the already opened dirfd.
1198                  */
1199                 bcopy(ptr, buf, len);
1200                 return (0);
1201         }
1202
1203         /*
1204          * We know that there is a / somewhere in this pathname.
1205          * Search backwards for it, to find the file's parent dir
1206          * to see if it exists in the alternate tree. If it does,
1207          * and we want to create a file (cflag is set). We don't
1208          * need to worry about the root comparison in this case.
1209          */
1210
1211         if (create) {
1212                 for (cp = &ptr[len] - 1; *cp != '/'; cp--);
1213                 *cp = '\0';
1214
1215                 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, buf, td);
1216                 error = namei(&nd);
1217                 *cp = '/';
1218                 if (error != 0)
1219                         goto keeporig;
1220         } else {
1221                 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, buf, td);
1222
1223                 error = namei(&nd);
1224                 if (error != 0)
1225                         goto keeporig;
1226
1227                 /*
1228                  * We now compare the vnode of the prefix to the one
1229                  * vnode asked. If they resolve to be the same, then we
1230                  * ignore the match so that the real root gets used.
1231                  * This avoids the problem of traversing "../.." to find the
1232                  * root directory and never finding it, because "/" resolves
1233                  * to the emulation root directory. This is expensive :-(
1234                  */
1235                 NDINIT(&ndroot, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, prefix,
1236                     td);
1237
1238                 /* We shouldn't ever get an error from this namei(). */
1239                 error = namei(&ndroot);
1240                 if (error == 0) {
1241                         if (nd.ni_vp == ndroot.ni_vp)
1242                                 error = ENOENT;
1243
1244                         NDFREE(&ndroot, NDF_ONLY_PNBUF);
1245                         vrele(ndroot.ni_vp);
1246                         VFS_UNLOCK_GIANT(NDHASGIANT(&ndroot));
1247                 }
1248         }
1249
1250         NDFREE(&nd, NDF_ONLY_PNBUF);
1251         vrele(nd.ni_vp);
1252         VFS_UNLOCK_GIANT(NDHASGIANT(&nd));
1253
1254 keeporig:
1255         /* If there was an error, use the original path name. */
1256         if (error)
1257                 bcopy(ptr, buf, len);
1258         return (error);
1259 }