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