]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - sys/kern/vfs_lookup.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.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         /*
167          * Don't allow empty pathnames.
168          */
169         if (!error && *cnp->cn_pnbuf == '\0')
170                 error = ENOENT;
171
172 #ifdef CAPABILITY_MODE
173         /*
174          * In capability mode, lookups must be "strictly relative" (i.e.
175          * not an absolute path, and not containing '..' components) to
176          * a real file descriptor, not the pseudo-descriptor AT_FDCWD.
177          */
178         if (IN_CAPABILITY_MODE(td)) {
179                 ndp->ni_strictrelative = 1;
180                 if (ndp->ni_dirfd == AT_FDCWD)
181                         error = ECAPMODE;
182         }
183 #endif
184         if (error) {
185                 uma_zfree(namei_zone, cnp->cn_pnbuf);
186 #ifdef DIAGNOSTIC
187                 cnp->cn_pnbuf = NULL;
188                 cnp->cn_nameptr = NULL;
189 #endif
190                 ndp->ni_vp = NULL;
191                 return (error);
192         }
193         ndp->ni_loopcnt = 0;
194 #ifdef KTRACE
195         if (KTRPOINT(td, KTR_NAMEI)) {
196                 KASSERT(cnp->cn_thread == curthread,
197                     ("namei not using curthread"));
198                 ktrnamei(cnp->cn_pnbuf);
199         }
200 #endif
201         /*
202          * Get starting point for the translation.
203          */
204         FILEDESC_SLOCK(fdp);
205         ndp->ni_rootdir = fdp->fd_rdir;
206         ndp->ni_topdir = fdp->fd_jdir;
207
208         /*
209          * If we are auditing the kernel pathname, save the user pathname.
210          */
211         if (cnp->cn_flags & AUDITVNODE1)
212                 AUDIT_ARG_UPATH1(td, ndp->ni_dirfd, cnp->cn_pnbuf);
213         if (cnp->cn_flags & AUDITVNODE2)
214                 AUDIT_ARG_UPATH2(td, ndp->ni_dirfd, cnp->cn_pnbuf);
215
216         dp = NULL;
217         if (cnp->cn_pnbuf[0] != '/') {
218                 if (ndp->ni_startdir != NULL) {
219                         dp = ndp->ni_startdir;
220                         error = 0;
221                 } else if (ndp->ni_dirfd != AT_FDCWD) {
222                         if (cnp->cn_flags & AUDITVNODE1)
223                                 AUDIT_ARG_ATFD1(ndp->ni_dirfd);
224                         if (cnp->cn_flags & AUDITVNODE2)
225                                 AUDIT_ARG_ATFD2(ndp->ni_dirfd);
226                         error = fgetvp_rights(td, ndp->ni_dirfd,
227                             ndp->ni_rightsneeded | CAP_LOOKUP,
228                             &(ndp->ni_baserights), &dp);
229 #ifdef CAPABILITIES
230                         /*
231                          * Lookups relative to a capability must also be
232                          * strictly relative.
233                          *
234                          * Note that a capability with rights CAP_MASK_VALID
235                          * is treated exactly like a regular file descriptor.
236                          */
237                         if (ndp->ni_baserights != CAP_MASK_VALID)
238                                 ndp->ni_strictrelative = 1;
239 #endif
240                 }
241                 if (error != 0 || dp != NULL) {
242                         FILEDESC_SUNLOCK(fdp);
243                         if (error == 0 && dp->v_type != VDIR) {
244                                 vfslocked = VFS_LOCK_GIANT(dp->v_mount);
245                                 vrele(dp);
246                                 VFS_UNLOCK_GIANT(vfslocked);
247                                 error = ENOTDIR;
248                         }
249                 }
250                 if (error) {
251                         uma_zfree(namei_zone, cnp->cn_pnbuf);
252 #ifdef DIAGNOSTIC
253                         cnp->cn_pnbuf = NULL;
254                         cnp->cn_nameptr = NULL;
255 #endif
256                         return (error);
257                 }
258         }
259         if (dp == NULL) {
260                 dp = fdp->fd_cdir;
261                 VREF(dp);
262                 FILEDESC_SUNLOCK(fdp);
263                 if (ndp->ni_startdir != NULL) {
264                         vfslocked = VFS_LOCK_GIANT(ndp->ni_startdir->v_mount);
265                         vrele(ndp->ni_startdir);
266                         VFS_UNLOCK_GIANT(vfslocked);
267                 }
268         }
269         SDT_PROBE(vfs, namei, lookup, entry, dp, cnp->cn_pnbuf,
270             cnp->cn_flags, 0, 0);
271         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
272         for (;;) {
273                 /*
274                  * Check if root directory should replace current directory.
275                  * Done at start of translation and after symbolic link.
276                  */
277                 cnp->cn_nameptr = cnp->cn_pnbuf;
278                 if (*(cnp->cn_nameptr) == '/') {
279                         vrele(dp);
280                         VFS_UNLOCK_GIANT(vfslocked);
281                         if (ndp->ni_strictrelative != 0)
282                                 return (ENOTCAPABLE);
283                         while (*(cnp->cn_nameptr) == '/') {
284                                 cnp->cn_nameptr++;
285                                 ndp->ni_pathlen--;
286                         }
287                         dp = ndp->ni_rootdir;
288                         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
289                         VREF(dp);
290                 }
291                 if (vfslocked)
292                         ndp->ni_cnd.cn_flags |= GIANTHELD;
293                 ndp->ni_startdir = dp;
294                 error = lookup(ndp);
295                 if (error) {
296                         uma_zfree(namei_zone, cnp->cn_pnbuf);
297 #ifdef DIAGNOSTIC
298                         cnp->cn_pnbuf = NULL;
299                         cnp->cn_nameptr = NULL;
300 #endif
301                         SDT_PROBE(vfs, namei, lookup, return, error, NULL, 0,
302                             0, 0);
303                         return (error);
304                 }
305                 vfslocked = (ndp->ni_cnd.cn_flags & GIANTHELD) != 0;
306                 ndp->ni_cnd.cn_flags &= ~GIANTHELD;
307                 /*
308                  * If not a symbolic link, we're done.
309                  */
310                 if ((cnp->cn_flags & ISSYMLINK) == 0) {
311                         if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0) {
312                                 uma_zfree(namei_zone, cnp->cn_pnbuf);
313 #ifdef DIAGNOSTIC
314                                 cnp->cn_pnbuf = NULL;
315                                 cnp->cn_nameptr = NULL;
316 #endif
317                         } else
318                                 cnp->cn_flags |= HASBUF;
319
320                         if ((cnp->cn_flags & MPSAFE) == 0) {
321                                 VFS_UNLOCK_GIANT(vfslocked);
322                         } else if (vfslocked)
323                                 ndp->ni_cnd.cn_flags |= GIANTHELD;
324                         SDT_PROBE(vfs, namei, lookup, return, 0, ndp->ni_vp,
325                             0, 0, 0);
326                         return (0);
327                 }
328                 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
329                         error = ELOOP;
330                         break;
331                 }
332 #ifdef MAC
333                 if ((cnp->cn_flags & NOMACCHECK) == 0) {
334                         error = mac_vnode_check_readlink(td->td_ucred,
335                             ndp->ni_vp);
336                         if (error)
337                                 break;
338                 }
339 #endif
340                 if (ndp->ni_pathlen > 1)
341                         cp = uma_zalloc(namei_zone, M_WAITOK);
342                 else
343                         cp = cnp->cn_pnbuf;
344                 aiov.iov_base = cp;
345                 aiov.iov_len = MAXPATHLEN;
346                 auio.uio_iov = &aiov;
347                 auio.uio_iovcnt = 1;
348                 auio.uio_offset = 0;
349                 auio.uio_rw = UIO_READ;
350                 auio.uio_segflg = UIO_SYSSPACE;
351                 auio.uio_td = td;
352                 auio.uio_resid = MAXPATHLEN;
353                 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
354                 if (error) {
355                         if (ndp->ni_pathlen > 1)
356                                 uma_zfree(namei_zone, cp);
357                         break;
358                 }
359                 linklen = MAXPATHLEN - auio.uio_resid;
360                 if (linklen == 0) {
361                         if (ndp->ni_pathlen > 1)
362                                 uma_zfree(namei_zone, cp);
363                         error = ENOENT;
364                         break;
365                 }
366                 if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
367                         if (ndp->ni_pathlen > 1)
368                                 uma_zfree(namei_zone, cp);
369                         error = ENAMETOOLONG;
370                         break;
371                 }
372                 if (ndp->ni_pathlen > 1) {
373                         bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
374                         uma_zfree(namei_zone, cnp->cn_pnbuf);
375                         cnp->cn_pnbuf = cp;
376                 } else
377                         cnp->cn_pnbuf[linklen] = '\0';
378                 ndp->ni_pathlen += linklen;
379                 vput(ndp->ni_vp);
380                 dp = ndp->ni_dvp;
381         }
382         uma_zfree(namei_zone, cnp->cn_pnbuf);
383 #ifdef DIAGNOSTIC
384         cnp->cn_pnbuf = NULL;
385         cnp->cn_nameptr = NULL;
386 #endif
387         vput(ndp->ni_vp);
388         ndp->ni_vp = NULL;
389         vrele(ndp->ni_dvp);
390         VFS_UNLOCK_GIANT(vfslocked);
391         SDT_PROBE(vfs, namei, lookup, return, error, NULL, 0, 0, 0);
392         return (error);
393 }
394
395 static int
396 compute_cn_lkflags(struct mount *mp, int lkflags, int cnflags)
397 {
398
399         if (mp == NULL || ((lkflags & LK_SHARED) &&
400             (!(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED) ||
401             ((cnflags & ISDOTDOT) &&
402             (mp->mnt_kern_flag & MNTK_LOOKUP_EXCL_DOTDOT))))) {
403                 lkflags &= ~LK_SHARED;
404                 lkflags |= LK_EXCLUSIVE;
405         }
406         return (lkflags);
407 }
408
409 static __inline int
410 needs_exclusive_leaf(struct mount *mp, int flags)
411 {
412
413         /*
414          * Intermediate nodes can use shared locks, we only need to
415          * force an exclusive lock for leaf nodes.
416          */
417         if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
418                 return (0);
419
420         /* Always use exclusive locks if LOCKSHARED isn't set. */
421         if (!(flags & LOCKSHARED))
422                 return (1);
423
424         /*
425          * For lookups during open(), if the mount point supports
426          * extended shared operations, then use a shared lock for the
427          * leaf node, otherwise use an exclusive lock.
428          */
429         if (flags & ISOPEN) {
430                 if (mp != NULL &&
431                     (mp->mnt_kern_flag & MNTK_EXTENDED_SHARED))
432                         return (0);
433                 else
434                         return (1);
435         }
436
437         /*
438          * Lookup requests outside of open() that specify LOCKSHARED
439          * only need a shared lock on the leaf vnode.
440          */
441         return (0);
442 }
443
444 /*
445  * Search a pathname.
446  * This is a very central and rather complicated routine.
447  *
448  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
449  * The starting directory is taken from ni_startdir. The pathname is
450  * descended until done, or a symbolic link is encountered. The variable
451  * ni_more is clear if the path is completed; it is set to one if a
452  * symbolic link needing interpretation is encountered.
453  *
454  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
455  * whether the name is to be looked up, created, renamed, or deleted.
456  * When CREATE, RENAME, or DELETE is specified, information usable in
457  * creating, renaming, or deleting a directory entry may be calculated.
458  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
459  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
460  * returned unlocked. Otherwise the parent directory is not returned. If
461  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
462  * the target is returned locked, otherwise it is returned unlocked.
463  * When creating or renaming and LOCKPARENT is specified, the target may not
464  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
465  *
466  * Overall outline of lookup:
467  *
468  * dirloop:
469  *      identify next component of name at ndp->ni_ptr
470  *      handle degenerate case where name is null string
471  *      if .. and crossing mount points and on mounted filesys, find parent
472  *      call VOP_LOOKUP routine for next component name
473  *          directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
474  *          component vnode returned in ni_vp (if it exists), locked.
475  *      if result vnode is mounted on and crossing mount points,
476  *          find mounted on vnode
477  *      if more components of name, do next level at dirloop
478  *      return the answer in ni_vp, locked if LOCKLEAF set
479  *          if LOCKPARENT set, return locked parent in ni_dvp
480  *          if WANTPARENT set, return unlocked parent in ni_dvp
481  */
482 int
483 lookup(struct nameidata *ndp)
484 {
485         char *cp;               /* pointer into pathname argument */
486         struct vnode *dp = 0;   /* the directory we are searching */
487         struct vnode *tdp;              /* saved dp */
488         struct mount *mp;               /* mount table entry */
489         struct prison *pr;
490         int docache;                    /* == 0 do not cache last component */
491         int wantparent;                 /* 1 => wantparent or lockparent flag */
492         int rdonly;                     /* lookup read-only flag bit */
493         int error = 0;
494         int dpunlocked = 0;             /* dp has already been unlocked */
495         struct componentname *cnp = &ndp->ni_cnd;
496         int vfslocked;                  /* VFS Giant state for child */
497         int dvfslocked;                 /* VFS Giant state for parent */
498         int tvfslocked;
499         int lkflags_save;
500         int ni_dvp_unlocked;
501         
502         /*
503          * Setup: break out flag bits into variables.
504          */
505         dvfslocked = (ndp->ni_cnd.cn_flags & GIANTHELD) != 0;
506         vfslocked = 0;
507         ni_dvp_unlocked = 0;
508         ndp->ni_cnd.cn_flags &= ~GIANTHELD;
509         wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
510         KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
511             ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
512         docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
513         if (cnp->cn_nameiop == DELETE ||
514             (wantparent && cnp->cn_nameiop != CREATE &&
515              cnp->cn_nameiop != LOOKUP))
516                 docache = 0;
517         rdonly = cnp->cn_flags & RDONLY;
518         cnp->cn_flags &= ~ISSYMLINK;
519         ndp->ni_dvp = NULL;
520         /*
521          * We use shared locks until we hit the parent of the last cn then
522          * we adjust based on the requesting flags.
523          */
524         if (lookup_shared)
525                 cnp->cn_lkflags = LK_SHARED;
526         else
527                 cnp->cn_lkflags = LK_EXCLUSIVE;
528         dp = ndp->ni_startdir;
529         ndp->ni_startdir = NULLVP;
530         vn_lock(dp,
531             compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY,
532             cnp->cn_flags));
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, ISDOTDOT));
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         if ((dp->v_iflag & VI_DOOMED) != 0) {
718                 error = ENOENT;
719                 goto bad;
720         }
721         /*
722          * If we're looking up the last component and we need an exclusive
723          * lock, adjust our lkflags.
724          */
725         if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
726                 cnp->cn_lkflags = LK_EXCLUSIVE;
727 #ifdef NAMEI_DIAGNOSTIC
728         vprint("lookup in", dp);
729 #endif
730         lkflags_save = cnp->cn_lkflags;
731         cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags,
732             cnp->cn_flags);
733         if ((error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp)) != 0) {
734                 cnp->cn_lkflags = lkflags_save;
735                 KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
736 #ifdef NAMEI_DIAGNOSTIC
737                 printf("not found\n");
738 #endif
739                 if ((error == ENOENT) &&
740                     (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
741                     (dp->v_mount->mnt_flag & MNT_UNION)) {
742                         tdp = dp;
743                         dp = dp->v_mount->mnt_vnodecovered;
744                         tvfslocked = dvfslocked;
745                         dvfslocked = VFS_LOCK_GIANT(dp->v_mount);
746                         VREF(dp);
747                         vput(tdp);
748                         VFS_UNLOCK_GIANT(tvfslocked);
749                         vn_lock(dp,
750                             compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
751                             LK_RETRY, cnp->cn_flags));
752                         goto unionlookup;
753                 }
754
755                 if (error != EJUSTRETURN)
756                         goto bad;
757                 /*
758                  * At this point, we know we're at the end of the
759                  * pathname.  If creating / renaming, we can consider
760                  * allowing the file or directory to be created / renamed,
761                  * provided we're not on a read-only filesystem.
762                  */
763                 if (rdonly) {
764                         error = EROFS;
765                         goto bad;
766                 }
767                 /* trailing slash only allowed for directories */
768                 if ((cnp->cn_flags & TRAILINGSLASH) &&
769                     !(cnp->cn_flags & WILLBEDIR)) {
770                         error = ENOENT;
771                         goto bad;
772                 }
773                 if ((cnp->cn_flags & LOCKPARENT) == 0)
774                         VOP_UNLOCK(dp, 0);
775                 /*
776                  * We return with ni_vp NULL to indicate that the entry
777                  * doesn't currently exist, leaving a pointer to the
778                  * (possibly locked) directory vnode in ndp->ni_dvp.
779                  */
780                 if (cnp->cn_flags & SAVESTART) {
781                         ndp->ni_startdir = ndp->ni_dvp;
782                         VREF(ndp->ni_startdir);
783                 }
784                 goto success;
785         } else
786                 cnp->cn_lkflags = lkflags_save;
787 #ifdef NAMEI_DIAGNOSTIC
788         printf("found\n");
789 #endif
790         /*
791          * Take into account any additional components consumed by
792          * the underlying filesystem.
793          */
794         if (cnp->cn_consume > 0) {
795                 cnp->cn_nameptr += cnp->cn_consume;
796                 ndp->ni_next += cnp->cn_consume;
797                 ndp->ni_pathlen -= cnp->cn_consume;
798                 cnp->cn_consume = 0;
799         }
800
801         dp = ndp->ni_vp;
802         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
803
804         /*
805          * Check to see if the vnode has been mounted on;
806          * if so find the root of the mounted filesystem.
807          */
808         while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
809                (cnp->cn_flags & NOCROSSMOUNT) == 0) {
810                 if (vfs_busy(mp, 0))
811                         continue;
812                 vput(dp);
813                 VFS_UNLOCK_GIANT(vfslocked);
814                 vfslocked = VFS_LOCK_GIANT(mp);
815                 if (dp != ndp->ni_dvp)
816                         vput(ndp->ni_dvp);
817                 else
818                         vrele(ndp->ni_dvp);
819                 VFS_UNLOCK_GIANT(dvfslocked);
820                 dvfslocked = 0;
821                 vref(vp_crossmp);
822                 ndp->ni_dvp = vp_crossmp;
823                 error = VFS_ROOT(mp, compute_cn_lkflags(mp, cnp->cn_lkflags,
824                     cnp->cn_flags), &tdp);
825                 vfs_unbusy(mp);
826                 if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
827                         panic("vp_crossmp exclusively locked or reclaimed");
828                 if (error) {
829                         dpunlocked = 1;
830                         goto bad2;
831                 }
832                 ndp->ni_vp = dp = tdp;
833         }
834
835         /*
836          * Check for symbolic link
837          */
838         if ((dp->v_type == VLNK) &&
839             ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
840              *ndp->ni_next == '/')) {
841                 cnp->cn_flags |= ISSYMLINK;
842                 if (dp->v_iflag & VI_DOOMED) {
843                         /*
844                          * We can't know whether the directory was mounted with
845                          * NOSYMFOLLOW, so we can't follow safely.
846                          */
847                         error = ENOENT;
848                         goto bad2;
849                 }
850                 if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
851                         error = EACCES;
852                         goto bad2;
853                 }
854                 /*
855                  * Symlink code always expects an unlocked dvp.
856                  */
857                 if (ndp->ni_dvp != ndp->ni_vp) {
858                         VOP_UNLOCK(ndp->ni_dvp, 0);
859                         ni_dvp_unlocked = 1;
860                 }
861                 goto success;
862         }
863
864 nextname:
865         /*
866          * Not a symbolic link that we will follow.  Continue with the
867          * next component if there is any; otherwise, we're done.
868          */
869         KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
870             ("lookup: invalid path state."));
871         if (*ndp->ni_next == '/') {
872                 cnp->cn_nameptr = ndp->ni_next;
873                 while (*cnp->cn_nameptr == '/') {
874                         cnp->cn_nameptr++;
875                         ndp->ni_pathlen--;
876                 }
877                 if (ndp->ni_dvp != dp)
878                         vput(ndp->ni_dvp);
879                 else
880                         vrele(ndp->ni_dvp);
881                 VFS_UNLOCK_GIANT(dvfslocked);
882                 dvfslocked = vfslocked; /* dp becomes dvp in dirloop */
883                 vfslocked = 0;
884                 goto dirloop;
885         }
886         /*
887          * If we're processing a path with a trailing slash,
888          * check that the end result is a directory.
889          */
890         if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
891                 error = ENOTDIR;
892                 goto bad2;
893         }
894         /*
895          * Disallow directory write attempts on read-only filesystems.
896          */
897         if (rdonly &&
898             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
899                 error = EROFS;
900                 goto bad2;
901         }
902         if (cnp->cn_flags & SAVESTART) {
903                 ndp->ni_startdir = ndp->ni_dvp;
904                 VREF(ndp->ni_startdir);
905         }
906         if (!wantparent) {
907                 ni_dvp_unlocked = 2;
908                 if (ndp->ni_dvp != dp)
909                         vput(ndp->ni_dvp);
910                 else
911                         vrele(ndp->ni_dvp);
912                 VFS_UNLOCK_GIANT(dvfslocked);
913                 dvfslocked = 0;
914         } else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
915                 VOP_UNLOCK(ndp->ni_dvp, 0);
916                 ni_dvp_unlocked = 1;
917         }
918
919         if (cnp->cn_flags & AUDITVNODE1)
920                 AUDIT_ARG_VNODE1(dp);
921         else if (cnp->cn_flags & AUDITVNODE2)
922                 AUDIT_ARG_VNODE2(dp);
923
924         if ((cnp->cn_flags & LOCKLEAF) == 0)
925                 VOP_UNLOCK(dp, 0);
926 success:
927         /*
928          * Because of lookup_shared we may have the vnode shared locked, but
929          * the caller may want it to be exclusively locked.
930          */
931         if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
932             VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
933                 vn_lock(dp, LK_UPGRADE | LK_RETRY);
934                 if (dp->v_iflag & VI_DOOMED) {
935                         error = ENOENT;
936                         goto bad2;
937                 }
938         }
939         if (vfslocked && dvfslocked)
940                 VFS_UNLOCK_GIANT(dvfslocked);   /* Only need one */
941         if (vfslocked || dvfslocked)
942                 ndp->ni_cnd.cn_flags |= GIANTHELD;
943         return (0);
944
945 bad2:
946         if (ni_dvp_unlocked != 2) {
947                 if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
948                         vput(ndp->ni_dvp);
949                 else
950                         vrele(ndp->ni_dvp);
951         }
952 bad:
953         if (!dpunlocked)
954                 vput(dp);
955         VFS_UNLOCK_GIANT(vfslocked);
956         VFS_UNLOCK_GIANT(dvfslocked);
957         ndp->ni_cnd.cn_flags &= ~GIANTHELD;
958         ndp->ni_vp = NULL;
959         return (error);
960 }
961
962 /*
963  * relookup - lookup a path name component
964  *    Used by lookup to re-acquire things.
965  */
966 int
967 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
968 {
969         struct vnode *dp = 0;           /* the directory we are searching */
970         int wantparent;                 /* 1 => wantparent or lockparent flag */
971         int rdonly;                     /* lookup read-only flag bit */
972         int error = 0;
973
974         KASSERT(cnp->cn_flags & ISLASTCN,
975             ("relookup: Not given last component."));
976         /*
977          * Setup: break out flag bits into variables.
978          */
979         wantparent = cnp->cn_flags & (LOCKPARENT|WANTPARENT);
980         KASSERT(wantparent, ("relookup: parent not wanted."));
981         rdonly = cnp->cn_flags & RDONLY;
982         cnp->cn_flags &= ~ISSYMLINK;
983         dp = dvp;
984         cnp->cn_lkflags = LK_EXCLUSIVE;
985         vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
986
987         /*
988          * Search a new directory.
989          *
990          * The last component of the filename is left accessible via
991          * cnp->cn_nameptr for callers that need the name. Callers needing
992          * the name set the SAVENAME flag. When done, they assume
993          * responsibility for freeing the pathname buffer.
994          */
995 #ifdef NAMEI_DIAGNOSTIC
996         printf("{%s}: ", cnp->cn_nameptr);
997 #endif
998
999         /*
1000          * Check for "" which represents the root directory after slash
1001          * removal.
1002          */
1003         if (cnp->cn_nameptr[0] == '\0') {
1004                 /*
1005                  * Support only LOOKUP for "/" because lookup()
1006                  * can't succeed for CREATE, DELETE and RENAME.
1007                  */
1008                 KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1009                 KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1010
1011                 if (!(cnp->cn_flags & LOCKLEAF))
1012                         VOP_UNLOCK(dp, 0);
1013                 *vpp = dp;
1014                 /* XXX This should probably move to the top of function. */
1015                 if (cnp->cn_flags & SAVESTART)
1016                         panic("lookup: SAVESTART");
1017                 return (0);
1018         }
1019
1020         if (cnp->cn_flags & ISDOTDOT)
1021                 panic ("relookup: lookup on dot-dot");
1022
1023         /*
1024          * We now have a segment name to search for, and a directory to search.
1025          */
1026 #ifdef NAMEI_DIAGNOSTIC
1027         vprint("search in:", dp);
1028 #endif
1029         if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1030                 KASSERT(*vpp == NULL, ("leaf should be empty"));
1031                 if (error != EJUSTRETURN)
1032                         goto bad;
1033                 /*
1034                  * If creating and at end of pathname, then can consider
1035                  * allowing file to be created.
1036                  */
1037                 if (rdonly) {
1038                         error = EROFS;
1039                         goto bad;
1040                 }
1041                 /* ASSERT(dvp == ndp->ni_startdir) */
1042                 if (cnp->cn_flags & SAVESTART)
1043                         VREF(dvp);
1044                 if ((cnp->cn_flags & LOCKPARENT) == 0)
1045                         VOP_UNLOCK(dp, 0);
1046                 /*
1047                  * We return with ni_vp NULL to indicate that the entry
1048                  * doesn't currently exist, leaving a pointer to the
1049                  * (possibly locked) directory vnode in ndp->ni_dvp.
1050                  */
1051                 return (0);
1052         }
1053
1054         dp = *vpp;
1055
1056         /*
1057          * Disallow directory write attempts on read-only filesystems.
1058          */
1059         if (rdonly &&
1060             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1061                 if (dvp == dp)
1062                         vrele(dvp);
1063                 else
1064                         vput(dvp);
1065                 error = EROFS;
1066                 goto bad;
1067         }
1068         /*
1069          * Set the parent lock/ref state to the requested state.
1070          */
1071         if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp) {
1072                 if (wantparent)
1073                         VOP_UNLOCK(dvp, 0);
1074                 else
1075                         vput(dvp);
1076         } else if (!wantparent)
1077                 vrele(dvp);
1078         /*
1079          * Check for symbolic link
1080          */
1081         KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1082             ("relookup: symlink found.\n"));
1083
1084         /* ASSERT(dvp == ndp->ni_startdir) */
1085         if (cnp->cn_flags & SAVESTART)
1086                 VREF(dvp);
1087         
1088         if ((cnp->cn_flags & LOCKLEAF) == 0)
1089                 VOP_UNLOCK(dp, 0);
1090         return (0);
1091 bad:
1092         vput(dp);
1093         *vpp = NULL;
1094         return (error);
1095 }
1096
1097 /*
1098  * Free data allocated by namei(); see namei(9) for details.
1099  */
1100 void
1101 NDFREE(struct nameidata *ndp, const u_int flags)
1102 {
1103         int unlock_dvp;
1104         int unlock_vp;
1105
1106         unlock_dvp = 0;
1107         unlock_vp = 0;
1108
1109         if (!(flags & NDF_NO_FREE_PNBUF) &&
1110             (ndp->ni_cnd.cn_flags & HASBUF)) {
1111                 uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
1112                 ndp->ni_cnd.cn_flags &= ~HASBUF;
1113         }
1114         if (!(flags & NDF_NO_VP_UNLOCK) &&
1115             (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
1116                 unlock_vp = 1;
1117         if (!(flags & NDF_NO_VP_RELE) && ndp->ni_vp) {
1118                 if (unlock_vp) {
1119                         vput(ndp->ni_vp);
1120                         unlock_vp = 0;
1121                 } else
1122                         vrele(ndp->ni_vp);
1123                 ndp->ni_vp = NULL;
1124         }
1125         if (unlock_vp)
1126                 VOP_UNLOCK(ndp->ni_vp, 0);
1127         if (!(flags & NDF_NO_DVP_UNLOCK) &&
1128             (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
1129             ndp->ni_dvp != ndp->ni_vp)
1130                 unlock_dvp = 1;
1131         if (!(flags & NDF_NO_DVP_RELE) &&
1132             (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
1133                 if (unlock_dvp) {
1134                         vput(ndp->ni_dvp);
1135                         unlock_dvp = 0;
1136                 } else
1137                         vrele(ndp->ni_dvp);
1138                 ndp->ni_dvp = NULL;
1139         }
1140         if (unlock_dvp)
1141                 VOP_UNLOCK(ndp->ni_dvp, 0);
1142         if (!(flags & NDF_NO_STARTDIR_RELE) &&
1143             (ndp->ni_cnd.cn_flags & SAVESTART)) {
1144                 vrele(ndp->ni_startdir);
1145                 ndp->ni_startdir = NULL;
1146         }
1147 }
1148
1149 /*
1150  * Determine if there is a suitable alternate filename under the specified
1151  * prefix for the specified path.  If the create flag is set, then the
1152  * alternate prefix will be used so long as the parent directory exists.
1153  * This is used by the various compatiblity ABIs so that Linux binaries prefer
1154  * files under /compat/linux for example.  The chosen path (whether under
1155  * the prefix or under /) is returned in a kernel malloc'd buffer pointed
1156  * to by pathbuf.  The caller is responsible for free'ing the buffer from
1157  * the M_TEMP bucket if one is returned.
1158  */
1159 int
1160 kern_alternate_path(struct thread *td, const char *prefix, const char *path,
1161     enum uio_seg pathseg, char **pathbuf, int create, int dirfd)
1162 {
1163         struct nameidata nd, ndroot;
1164         char *ptr, *buf, *cp;
1165         size_t len, sz;
1166         int error;
1167
1168         buf = (char *) malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1169         *pathbuf = buf;
1170
1171         /* Copy the prefix into the new pathname as a starting point. */
1172         len = strlcpy(buf, prefix, MAXPATHLEN);
1173         if (len >= MAXPATHLEN) {
1174                 *pathbuf = NULL;
1175                 free(buf, M_TEMP);
1176                 return (EINVAL);
1177         }
1178         sz = MAXPATHLEN - len;
1179         ptr = buf + len;
1180
1181         /* Append the filename to the prefix. */
1182         if (pathseg == UIO_SYSSPACE)
1183                 error = copystr(path, ptr, sz, &len);
1184         else
1185                 error = copyinstr(path, ptr, sz, &len);
1186
1187         if (error) {
1188                 *pathbuf = NULL;
1189                 free(buf, M_TEMP);
1190                 return (error);
1191         }
1192
1193         /* Only use a prefix with absolute pathnames. */
1194         if (*ptr != '/') {
1195                 error = EINVAL;
1196                 goto keeporig;
1197         }
1198
1199         if (dirfd != AT_FDCWD) {
1200                 /*
1201                  * We want the original because the "prefix" is
1202                  * included in the already opened dirfd.
1203                  */
1204                 bcopy(ptr, buf, len);
1205                 return (0);
1206         }
1207
1208         /*
1209          * We know that there is a / somewhere in this pathname.
1210          * Search backwards for it, to find the file's parent dir
1211          * to see if it exists in the alternate tree. If it does,
1212          * and we want to create a file (cflag is set). We don't
1213          * need to worry about the root comparison in this case.
1214          */
1215
1216         if (create) {
1217                 for (cp = &ptr[len] - 1; *cp != '/'; cp--);
1218                 *cp = '\0';
1219
1220                 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, buf, td);
1221                 error = namei(&nd);
1222                 *cp = '/';
1223                 if (error != 0)
1224                         goto keeporig;
1225         } else {
1226                 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, buf, td);
1227
1228                 error = namei(&nd);
1229                 if (error != 0)
1230                         goto keeporig;
1231
1232                 /*
1233                  * We now compare the vnode of the prefix to the one
1234                  * vnode asked. If they resolve to be the same, then we
1235                  * ignore the match so that the real root gets used.
1236                  * This avoids the problem of traversing "../.." to find the
1237                  * root directory and never finding it, because "/" resolves
1238                  * to the emulation root directory. This is expensive :-(
1239                  */
1240                 NDINIT(&ndroot, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, prefix,
1241                     td);
1242
1243                 /* We shouldn't ever get an error from this namei(). */
1244                 error = namei(&ndroot);
1245                 if (error == 0) {
1246                         if (nd.ni_vp == ndroot.ni_vp)
1247                                 error = ENOENT;
1248
1249                         NDFREE(&ndroot, NDF_ONLY_PNBUF);
1250                         vrele(ndroot.ni_vp);
1251                         VFS_UNLOCK_GIANT(NDHASGIANT(&ndroot));
1252                 }
1253         }
1254
1255         NDFREE(&nd, NDF_ONLY_PNBUF);
1256         vrele(nd.ni_vp);
1257         VFS_UNLOCK_GIANT(NDHASGIANT(&nd));
1258
1259 keeporig:
1260         /* If there was an error, use the original path name. */
1261         if (error)
1262                 bcopy(ptr, buf, len);
1263         return (error);
1264 }