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