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