xref: /freebsd/sys/kern/vfs_lookup.c (revision da5137abdf463bb5fee85061958a14dd12bc043e)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)vfs_lookup.c	8.4 (Berkeley) 2/16/94
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_capsicum.h"
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/dirent.h>
48 #include <sys/kernel.h>
49 #include <sys/capsicum.h>
50 #include <sys/fcntl.h>
51 #include <sys/jail.h>
52 #include <sys/lock.h>
53 #include <sys/mutex.h>
54 #include <sys/namei.h>
55 #include <sys/vnode.h>
56 #include <sys/mount.h>
57 #include <sys/filedesc.h>
58 #include <sys/proc.h>
59 #include <sys/sdt.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysctl.h>
62 #ifdef KTRACE
63 #include <sys/ktrace.h>
64 #endif
65 #ifdef INVARIANTS
66 #include <machine/_inttypes.h>
67 #endif
68 
69 #include <security/audit/audit.h>
70 #include <security/mac/mac_framework.h>
71 
72 #include <vm/uma.h>
73 
74 #define	NAMEI_DIAGNOSTIC 1
75 #undef NAMEI_DIAGNOSTIC
76 
77 SDT_PROVIDER_DEFINE(vfs);
78 SDT_PROBE_DEFINE4(vfs, namei, lookup, entry, "struct vnode *", "char *",
79     "unsigned long", "bool");
80 SDT_PROBE_DEFINE4(vfs, namei, lookup, return, "int", "struct vnode *", "bool",
81     "struct nameidata");
82 
83 /* Allocation zone for namei. */
84 uma_zone_t namei_zone;
85 
86 /* Placeholder vnode for mp traversal. */
87 static struct vnode *vp_crossmp;
88 
89 static int
90 crossmp_vop_islocked(struct vop_islocked_args *ap)
91 {
92 
93 	return (LK_SHARED);
94 }
95 
96 static int
97 crossmp_vop_lock1(struct vop_lock1_args *ap)
98 {
99 	struct vnode *vp;
100 	struct lock *lk __diagused;
101 	const char *file __diagused;
102 	int flags, line __diagused;
103 
104 	vp = ap->a_vp;
105 	lk = vp->v_vnlock;
106 	flags = ap->a_flags;
107 	file = ap->a_file;
108 	line = ap->a_line;
109 
110 	if ((flags & LK_SHARED) == 0)
111 		panic("invalid lock request for crossmp");
112 
113 	WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER, file, line,
114 	    flags & LK_INTERLOCK ? &VI_MTX(vp)->lock_object : NULL);
115 	WITNESS_LOCK(&lk->lock_object, 0, file, line);
116 	if ((flags & LK_INTERLOCK) != 0)
117 		VI_UNLOCK(vp);
118 	LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, ap->a_file, line);
119 	return (0);
120 }
121 
122 static int
123 crossmp_vop_unlock(struct vop_unlock_args *ap)
124 {
125 	struct vnode *vp;
126 	struct lock *lk __diagused;
127 
128 	vp = ap->a_vp;
129 	lk = vp->v_vnlock;
130 
131 	WITNESS_UNLOCK(&lk->lock_object, 0, LOCK_FILE, LOCK_LINE);
132 	LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, LOCK_FILE,
133 	    LOCK_LINE);
134 	return (0);
135 }
136 
137 static struct vop_vector crossmp_vnodeops = {
138 	.vop_default =		&default_vnodeops,
139 	.vop_islocked =		crossmp_vop_islocked,
140 	.vop_lock1 =		crossmp_vop_lock1,
141 	.vop_unlock =		crossmp_vop_unlock,
142 };
143 /*
144  * VFS_VOP_VECTOR_REGISTER(crossmp_vnodeops) is not used here since the vnode
145  * gets allocated early. See nameiinit for the direct call below.
146  */
147 
148 struct nameicap_tracker {
149 	struct vnode *dp;
150 	TAILQ_ENTRY(nameicap_tracker) nm_link;
151 };
152 
153 /* Zone for cap mode tracker elements used for dotdot capability checks. */
154 MALLOC_DEFINE(M_NAMEITRACKER, "namei_tracker", "namei tracking for dotdot");
155 
156 static void
157 nameiinit(void *dummy __unused)
158 {
159 
160 	namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
161 	    UMA_ALIGN_PTR, 0);
162 	vfs_vector_op_register(&crossmp_vnodeops);
163 	getnewvnode("crossmp", NULL, &crossmp_vnodeops, &vp_crossmp);
164 }
165 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
166 
167 static int lookup_cap_dotdot = 1;
168 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot, CTLFLAG_RWTUN,
169     &lookup_cap_dotdot, 0,
170     "enables \"..\" components in path lookup in capability mode");
171 static int lookup_cap_dotdot_nonlocal = 1;
172 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot_nonlocal, CTLFLAG_RWTUN,
173     &lookup_cap_dotdot_nonlocal, 0,
174     "enables \"..\" components in path lookup in capability mode "
175     "on non-local mount");
176 
177 static void
178 nameicap_tracker_add(struct nameidata *ndp, struct vnode *dp)
179 {
180 	struct nameicap_tracker *nt;
181 
182 	if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0 || dp->v_type != VDIR)
183 		return;
184 	nt = TAILQ_LAST(&ndp->ni_cap_tracker, nameicap_tracker_head);
185 	if (nt != NULL && nt->dp == dp)
186 		return;
187 	nt = malloc(sizeof(*nt), M_NAMEITRACKER, M_WAITOK);
188 	vhold(dp);
189 	nt->dp = dp;
190 	TAILQ_INSERT_TAIL(&ndp->ni_cap_tracker, nt, nm_link);
191 }
192 
193 static void
194 nameicap_cleanup_from(struct nameidata *ndp, struct nameicap_tracker *first)
195 {
196 	struct nameicap_tracker *nt, *nt1;
197 
198 	nt = first;
199 	TAILQ_FOREACH_FROM_SAFE(nt, &ndp->ni_cap_tracker, nm_link, nt1) {
200 		TAILQ_REMOVE(&ndp->ni_cap_tracker, nt, nm_link);
201 		vdrop(nt->dp);
202 		free(nt, M_NAMEITRACKER);
203 	}
204 }
205 
206 static void
207 nameicap_cleanup(struct nameidata *ndp)
208 {
209 	KASSERT(TAILQ_EMPTY(&ndp->ni_cap_tracker) ||
210 	    (ndp->ni_lcf & NI_LCF_CAP_DOTDOT) != 0, ("not strictrelative"));
211 	nameicap_cleanup_from(ndp, NULL);
212 }
213 
214 /*
215  * For dotdot lookups in capability mode, only allow the component
216  * lookup to succeed if the resulting directory was already traversed
217  * during the operation.  This catches situations where already
218  * traversed directory is moved to different parent, and then we walk
219  * over it with dotdots.
220  *
221  * Also allow to force failure of dotdot lookups for non-local
222  * filesystems, where external agents might assist local lookups to
223  * escape the compartment.
224  */
225 static int
226 nameicap_check_dotdot(struct nameidata *ndp, struct vnode *dp)
227 {
228 	struct nameicap_tracker *nt;
229 	struct mount *mp;
230 
231 	if (dp == NULL || dp->v_type != VDIR || (ndp->ni_lcf &
232 	    NI_LCF_STRICTRELATIVE) == 0)
233 		return (0);
234 	if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0)
235 		return (ENOTCAPABLE);
236 	mp = dp->v_mount;
237 	if (lookup_cap_dotdot_nonlocal == 0 && mp != NULL &&
238 	    (mp->mnt_flag & MNT_LOCAL) == 0)
239 		return (ENOTCAPABLE);
240 	TAILQ_FOREACH_REVERSE(nt, &ndp->ni_cap_tracker, nameicap_tracker_head,
241 	    nm_link) {
242 		if (dp == nt->dp) {
243 			nt = TAILQ_NEXT(nt, nm_link);
244 			if (nt != NULL)
245 				nameicap_cleanup_from(ndp, nt);
246 			return (0);
247 		}
248 	}
249 	return (ENOTCAPABLE);
250 }
251 
252 static void
253 namei_cleanup_cnp(struct componentname *cnp)
254 {
255 
256 	uma_zfree(namei_zone, cnp->cn_pnbuf);
257 #ifdef DIAGNOSTIC
258 	cnp->cn_pnbuf = NULL;
259 	cnp->cn_nameptr = NULL;
260 #endif
261 }
262 
263 static int
264 namei_handle_root(struct nameidata *ndp, struct vnode **dpp)
265 {
266 	struct componentname *cnp;
267 
268 	cnp = &ndp->ni_cnd;
269 	if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0) {
270 #ifdef KTRACE
271 		if (KTRPOINT(curthread, KTR_CAPFAIL))
272 			ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
273 #endif
274 		return (ENOTCAPABLE);
275 	}
276 	while (*(cnp->cn_nameptr) == '/') {
277 		cnp->cn_nameptr++;
278 		ndp->ni_pathlen--;
279 	}
280 	*dpp = ndp->ni_rootdir;
281 	vrefact(*dpp);
282 	return (0);
283 }
284 
285 static int
286 namei_setup(struct nameidata *ndp, struct vnode **dpp, struct pwd **pwdp)
287 {
288 	struct componentname *cnp;
289 	struct file *dfp;
290 	struct thread *td;
291 	struct pwd *pwd;
292 	cap_rights_t rights;
293 	int error;
294 	bool startdir_used;
295 
296 	cnp = &ndp->ni_cnd;
297 	td = curthread;
298 
299 	startdir_used = false;
300 	*pwdp = NULL;
301 	*dpp = NULL;
302 
303 #ifdef CAPABILITY_MODE
304 	/*
305 	 * In capability mode, lookups must be restricted to happen in
306 	 * the subtree with the root specified by the file descriptor:
307 	 * - The root must be real file descriptor, not the pseudo-descriptor
308 	 *   AT_FDCWD.
309 	 * - The passed path must be relative and not absolute.
310 	 * - If lookup_cap_dotdot is disabled, path must not contain the
311 	 *   '..' components.
312 	 * - If lookup_cap_dotdot is enabled, we verify that all '..'
313 	 *   components lookups result in the directories which were
314 	 *   previously walked by us, which prevents an escape from
315 	 *   the relative root.
316 	 */
317 	if (IN_CAPABILITY_MODE(td) && (cnp->cn_flags & NOCAPCHECK) == 0) {
318 		ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
319 		ndp->ni_resflags |= NIRES_STRICTREL;
320 		if (ndp->ni_dirfd == AT_FDCWD) {
321 #ifdef KTRACE
322 			if (KTRPOINT(td, KTR_CAPFAIL))
323 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
324 #endif
325 			return (ECAPMODE);
326 		}
327 	}
328 #endif
329 	error = 0;
330 
331 	/*
332 	 * Get starting point for the translation.
333 	 */
334 	pwd = pwd_hold(td);
335 	/*
336 	 * The reference on ni_rootdir is acquired in the block below to avoid
337 	 * back-to-back atomics for absolute lookups.
338 	 */
339 	ndp->ni_rootdir = pwd->pwd_rdir;
340 	ndp->ni_topdir = pwd->pwd_jdir;
341 
342 	if (cnp->cn_pnbuf[0] == '/') {
343 		ndp->ni_resflags |= NIRES_ABS;
344 		error = namei_handle_root(ndp, dpp);
345 	} else {
346 		if (ndp->ni_startdir != NULL) {
347 			*dpp = ndp->ni_startdir;
348 			startdir_used = true;
349 		} else if (ndp->ni_dirfd == AT_FDCWD) {
350 			*dpp = pwd->pwd_cdir;
351 			vrefact(*dpp);
352 		} else {
353 			rights = *ndp->ni_rightsneeded;
354 			cap_rights_set_one(&rights, CAP_LOOKUP);
355 
356 			if (cnp->cn_flags & AUDITVNODE1)
357 				AUDIT_ARG_ATFD1(ndp->ni_dirfd);
358 			if (cnp->cn_flags & AUDITVNODE2)
359 				AUDIT_ARG_ATFD2(ndp->ni_dirfd);
360 			/*
361 			 * Effectively inlined fgetvp_rights, because
362 			 * we need to inspect the file as well as
363 			 * grabbing the vnode.  No check for O_PATH,
364 			 * files to implement its semantic.
365 			 */
366 			error = fget_cap(td, ndp->ni_dirfd, &rights,
367 			    &dfp, &ndp->ni_filecaps);
368 			if (error != 0) {
369 				/*
370 				 * Preserve the error; it should either be EBADF
371 				 * or capability-related, both of which can be
372 				 * safely returned to the caller.
373 				 */
374 			} else {
375 				if (dfp->f_ops == &badfileops) {
376 					error = EBADF;
377 				} else if (dfp->f_vnode == NULL) {
378 					error = ENOTDIR;
379 				} else {
380 					*dpp = dfp->f_vnode;
381 					vref(*dpp);
382 
383 					if ((dfp->f_flag & FSEARCH) != 0)
384 						cnp->cn_flags |= NOEXECCHECK;
385 				}
386 				fdrop(dfp, td);
387 			}
388 #ifdef CAPABILITIES
389 			/*
390 			 * If file descriptor doesn't have all rights,
391 			 * all lookups relative to it must also be
392 			 * strictly relative.
393 			 */
394 			CAP_ALL(&rights);
395 			if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights,
396 			    &rights) ||
397 			    ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
398 			    ndp->ni_filecaps.fc_nioctls != -1) {
399 				ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
400 				ndp->ni_resflags |= NIRES_STRICTREL;
401 			}
402 #endif
403 		}
404 		if (error == 0 && (*dpp)->v_type != VDIR &&
405 		    (cnp->cn_pnbuf[0] != '\0' ||
406 		    (cnp->cn_flags & EMPTYPATH) == 0))
407 			error = ENOTDIR;
408 	}
409 	if (error == 0 && (cnp->cn_flags & RBENEATH) != 0) {
410 		if (cnp->cn_pnbuf[0] == '/') {
411 			error = ENOTCAPABLE;
412 		} else if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) == 0) {
413 			ndp->ni_lcf |= NI_LCF_STRICTRELATIVE |
414 			    NI_LCF_CAP_DOTDOT;
415 		}
416 	}
417 
418 	/*
419 	 * If we are auditing the kernel pathname, save the user pathname.
420 	 */
421 	if (cnp->cn_flags & AUDITVNODE1)
422 		AUDIT_ARG_UPATH1_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
423 	if (cnp->cn_flags & AUDITVNODE2)
424 		AUDIT_ARG_UPATH2_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
425 	if (ndp->ni_startdir != NULL && !startdir_used)
426 		vrele(ndp->ni_startdir);
427 	if (error != 0) {
428 		if (*dpp != NULL)
429 			vrele(*dpp);
430 		pwd_drop(pwd);
431 		return (error);
432 	}
433 	if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0 &&
434 	    lookup_cap_dotdot != 0)
435 		ndp->ni_lcf |= NI_LCF_CAP_DOTDOT;
436 	SDT_PROBE4(vfs, namei, lookup, entry, *dpp, cnp->cn_pnbuf,
437 	    cnp->cn_flags, false);
438 	*pwdp = pwd;
439 	return (0);
440 }
441 
442 static int
443 namei_getpath(struct nameidata *ndp)
444 {
445 	struct componentname *cnp;
446 	int error;
447 
448 	cnp = &ndp->ni_cnd;
449 
450 	/*
451 	 * Get a buffer for the name to be translated, and copy the
452 	 * name into the buffer.
453 	 */
454 	cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
455 	if (ndp->ni_segflg == UIO_SYSSPACE) {
456 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
457 		    &ndp->ni_pathlen);
458 	} else {
459 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
460 		    &ndp->ni_pathlen);
461 	}
462 
463 	if (__predict_false(error != 0))
464 		return (error);
465 
466 	cnp->cn_nameptr = cnp->cn_pnbuf;
467 	return (0);
468 }
469 
470 static int
471 namei_emptypath(struct nameidata *ndp)
472 {
473 	struct componentname *cnp;
474 	struct pwd *pwd;
475 	struct vnode *dp;
476 	int error;
477 
478 	cnp = &ndp->ni_cnd;
479 	MPASS(*cnp->cn_pnbuf == '\0');
480 	MPASS((cnp->cn_flags & EMPTYPATH) != 0);
481 	MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
482 
483 	ndp->ni_resflags |= NIRES_EMPTYPATH;
484 	error = namei_setup(ndp, &dp, &pwd);
485 	if (error != 0) {
486 		namei_cleanup_cnp(cnp);
487 		goto errout;
488 	}
489 
490 	/*
491 	 * Usecount on dp already provided by namei_setup.
492 	 */
493 	ndp->ni_vp = dp;
494 	namei_cleanup_cnp(cnp);
495 	pwd_drop(pwd);
496 	NDVALIDATE(ndp);
497 	if ((cnp->cn_flags & LOCKLEAF) != 0) {
498 		VOP_LOCK(dp, (cnp->cn_flags & LOCKSHARED) != 0 ?
499 		    LK_SHARED : LK_EXCLUSIVE);
500 		if (VN_IS_DOOMED(dp)) {
501 			vput(dp);
502 			error = ENOENT;
503 			goto errout;
504 		}
505 	}
506 	SDT_PROBE4(vfs, namei, lookup, return, 0, ndp->ni_vp, false, ndp);
507 	return (0);
508 
509 errout:
510 	SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
511 	return (error);
512 }
513 
514 static int __noinline
515 namei_follow_link(struct nameidata *ndp)
516 {
517 	char *cp;
518 	struct iovec aiov;
519 	struct uio auio;
520 	struct componentname *cnp;
521 	struct thread *td;
522 	int error, linklen;
523 
524 	error = 0;
525 	cnp = &ndp->ni_cnd;
526 	td = curthread;
527 
528 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
529 		error = ELOOP;
530 		goto out;
531 	}
532 #ifdef MAC
533 	if ((cnp->cn_flags & NOMACCHECK) == 0) {
534 		error = mac_vnode_check_readlink(td->td_ucred, ndp->ni_vp);
535 		if (error != 0)
536 			goto out;
537 	}
538 #endif
539 	if (ndp->ni_pathlen > 1)
540 		cp = uma_zalloc(namei_zone, M_WAITOK);
541 	else
542 		cp = cnp->cn_pnbuf;
543 	aiov.iov_base = cp;
544 	aiov.iov_len = MAXPATHLEN;
545 	auio.uio_iov = &aiov;
546 	auio.uio_iovcnt = 1;
547 	auio.uio_offset = 0;
548 	auio.uio_rw = UIO_READ;
549 	auio.uio_segflg = UIO_SYSSPACE;
550 	auio.uio_td = td;
551 	auio.uio_resid = MAXPATHLEN;
552 	error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
553 	if (error != 0) {
554 		if (ndp->ni_pathlen > 1)
555 			uma_zfree(namei_zone, cp);
556 		goto out;
557 	}
558 	linklen = MAXPATHLEN - auio.uio_resid;
559 	if (linklen == 0) {
560 		if (ndp->ni_pathlen > 1)
561 			uma_zfree(namei_zone, cp);
562 		error = ENOENT;
563 		goto out;
564 	}
565 	if (linklen + ndp->ni_pathlen > MAXPATHLEN) {
566 		if (ndp->ni_pathlen > 1)
567 			uma_zfree(namei_zone, cp);
568 		error = ENAMETOOLONG;
569 		goto out;
570 	}
571 	if (ndp->ni_pathlen > 1) {
572 		bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
573 		uma_zfree(namei_zone, cnp->cn_pnbuf);
574 		cnp->cn_pnbuf = cp;
575 	} else
576 		cnp->cn_pnbuf[linklen] = '\0';
577 	ndp->ni_pathlen += linklen;
578 out:
579 	return (error);
580 }
581 
582 /*
583  * Convert a pathname into a pointer to a locked vnode.
584  *
585  * The FOLLOW flag is set when symbolic links are to be followed
586  * when they occur at the end of the name translation process.
587  * Symbolic links are always followed for all other pathname
588  * components other than the last.
589  *
590  * The segflg defines whether the name is to be copied from user
591  * space or kernel space.
592  *
593  * Overall outline of namei:
594  *
595  *	copy in name
596  *	get starting directory
597  *	while (!done && !error) {
598  *		call lookup to search path.
599  *		if symbolic link, massage name in buffer and continue
600  *	}
601  */
602 int
603 namei(struct nameidata *ndp)
604 {
605 	struct vnode *dp;	/* the directory we are searching */
606 	struct componentname *cnp;
607 	struct thread *td;
608 	struct pwd *pwd;
609 	int error;
610 	enum cache_fpl_status status;
611 
612 	cnp = &ndp->ni_cnd;
613 	td = curthread;
614 #ifdef INVARIANTS
615 	KASSERT((ndp->ni_debugflags & NAMEI_DBG_CALLED) == 0,
616 	    ("%s: repeated call to namei without NDREINIT", __func__));
617 	KASSERT(ndp->ni_debugflags == NAMEI_DBG_INITED,
618 	    ("%s: bad debugflags %d", __func__, ndp->ni_debugflags));
619 	ndp->ni_debugflags |= NAMEI_DBG_CALLED;
620 	if (ndp->ni_startdir != NULL)
621 		ndp->ni_debugflags |= NAMEI_DBG_HADSTARTDIR;
622 	if (cnp->cn_flags & FAILIFEXISTS) {
623 		KASSERT(cnp->cn_nameiop == CREATE,
624 		    ("%s: FAILIFEXISTS passed for op %d", __func__, cnp->cn_nameiop));
625 		/*
626 		 * The limitation below is to restrict hairy corner cases.
627 		 */
628 		KASSERT((cnp->cn_flags & (LOCKPARENT | LOCKLEAF)) == LOCKPARENT,
629 		    ("%s: FAILIFEXISTS must be passed with LOCKPARENT and without LOCKLEAF",
630 		    __func__));
631 	}
632 	/*
633 	 * For NDVALIDATE.
634 	 *
635 	 * While NDINIT may seem like a more natural place to do it, there are
636 	 * callers which directly modify flags past invoking init.
637 	 */
638 	cnp->cn_origflags = cnp->cn_flags;
639 #endif
640 	ndp->ni_cnd.cn_cred = td->td_ucred;
641 	KASSERT(ndp->ni_resflags == 0, ("%s: garbage in ni_resflags: %x\n",
642 	    __func__, ndp->ni_resflags));
643 	KASSERT(cnp->cn_cred && td->td_proc, ("namei: bad cred/proc"));
644 	KASSERT((cnp->cn_flags & NAMEI_INTERNAL_FLAGS) == 0,
645 	    ("namei: unexpected flags: %" PRIx64 "\n",
646 	    cnp->cn_flags & NAMEI_INTERNAL_FLAGS));
647 	if (cnp->cn_flags & NOCACHE)
648 		KASSERT(cnp->cn_nameiop != LOOKUP,
649 		    ("%s: NOCACHE passed with LOOKUP", __func__));
650 	MPASS(ndp->ni_startdir == NULL || ndp->ni_startdir->v_type == VDIR ||
651 	    ndp->ni_startdir->v_type == VBAD);
652 
653 	ndp->ni_lcf = 0;
654 	ndp->ni_loopcnt = 0;
655 	ndp->ni_vp = NULL;
656 
657 	error = namei_getpath(ndp);
658 	if (__predict_false(error != 0)) {
659 		namei_cleanup_cnp(cnp);
660 		SDT_PROBE4(vfs, namei, lookup, return, error, NULL,
661 		    false, ndp);
662 		return (error);
663 	}
664 
665 #ifdef KTRACE
666 	if (KTRPOINT(td, KTR_NAMEI)) {
667 		ktrnamei(cnp->cn_pnbuf);
668 	}
669 #endif
670 	TSNAMEI(curthread->td_proc->p_pid, cnp->cn_pnbuf);
671 
672 	/*
673 	 * First try looking up the target without locking any vnodes.
674 	 *
675 	 * We may need to start from scratch or pick up where it left off.
676 	 */
677 	error = cache_fplookup(ndp, &status, &pwd);
678 	switch (status) {
679 	case CACHE_FPL_STATUS_UNSET:
680 		__assert_unreachable();
681 		break;
682 	case CACHE_FPL_STATUS_HANDLED:
683 		if (error == 0)
684 			NDVALIDATE(ndp);
685 		return (error);
686 	case CACHE_FPL_STATUS_PARTIAL:
687 		TAILQ_INIT(&ndp->ni_cap_tracker);
688 		dp = ndp->ni_startdir;
689 		break;
690 	case CACHE_FPL_STATUS_DESTROYED:
691 		ndp->ni_loopcnt = 0;
692 		error = namei_getpath(ndp);
693 		if (__predict_false(error != 0)) {
694 			namei_cleanup_cnp(cnp);
695 			return (error);
696 		}
697 		/* FALLTHROUGH */
698 	case CACHE_FPL_STATUS_ABORTED:
699 		TAILQ_INIT(&ndp->ni_cap_tracker);
700 		MPASS(ndp->ni_lcf == 0);
701 		if (*cnp->cn_pnbuf == '\0') {
702 			if ((cnp->cn_flags & EMPTYPATH) != 0) {
703 				return (namei_emptypath(ndp));
704 			}
705 			namei_cleanup_cnp(cnp);
706 			SDT_PROBE4(vfs, namei, lookup, return, ENOENT, NULL,
707 			    false, ndp);
708 			return (ENOENT);
709 		}
710 		error = namei_setup(ndp, &dp, &pwd);
711 		if (error != 0) {
712 			namei_cleanup_cnp(cnp);
713 			return (error);
714 		}
715 		break;
716 	}
717 
718 	/*
719 	 * Locked lookup.
720 	 */
721 	for (;;) {
722 		ndp->ni_startdir = dp;
723 		error = vfs_lookup(ndp);
724 		if (error != 0)
725 			goto out;
726 
727 		/*
728 		 * If not a symbolic link, we're done.
729 		 */
730 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
731 			SDT_PROBE4(vfs, namei, lookup, return, error,
732 			    (error == 0 ? ndp->ni_vp : NULL), false, ndp);
733 			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0) {
734 				namei_cleanup_cnp(cnp);
735 			} else
736 				cnp->cn_flags |= HASBUF;
737 			nameicap_cleanup(ndp);
738 			pwd_drop(pwd);
739 			if (error == 0)
740 				NDVALIDATE(ndp);
741 			return (error);
742 		}
743 		error = namei_follow_link(ndp);
744 		if (error != 0)
745 			break;
746 		vput(ndp->ni_vp);
747 		dp = ndp->ni_dvp;
748 		/*
749 		 * Check if root directory should replace current directory.
750 		 */
751 		cnp->cn_nameptr = cnp->cn_pnbuf;
752 		if (*(cnp->cn_nameptr) == '/') {
753 			vrele(dp);
754 			error = namei_handle_root(ndp, &dp);
755 			if (error != 0)
756 				goto out;
757 		}
758 	}
759 	vput(ndp->ni_vp);
760 	ndp->ni_vp = NULL;
761 	vrele(ndp->ni_dvp);
762 out:
763 	MPASS(error != 0);
764 	SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
765 	namei_cleanup_cnp(cnp);
766 	nameicap_cleanup(ndp);
767 	pwd_drop(pwd);
768 	return (error);
769 }
770 
771 static int
772 compute_cn_lkflags(struct mount *mp, int lkflags, int cnflags)
773 {
774 
775 	if (mp == NULL || ((lkflags & LK_SHARED) &&
776 	    !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
777 		lkflags &= ~LK_SHARED;
778 		lkflags |= LK_EXCLUSIVE;
779 	}
780 	lkflags |= LK_NODDLKTREAT;
781 	return (lkflags);
782 }
783 
784 static __inline int
785 needs_exclusive_leaf(struct mount *mp, int flags)
786 {
787 
788 	/*
789 	 * Intermediate nodes can use shared locks, we only need to
790 	 * force an exclusive lock for leaf nodes.
791 	 */
792 	if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
793 		return (0);
794 
795 	/* Always use exclusive locks if LOCKSHARED isn't set. */
796 	if (!(flags & LOCKSHARED))
797 		return (1);
798 
799 	/*
800 	 * For lookups during open(), if the mount point supports
801 	 * extended shared operations, then use a shared lock for the
802 	 * leaf node, otherwise use an exclusive lock.
803 	 */
804 	if ((flags & ISOPEN) != 0)
805 		return (!MNT_EXTENDED_SHARED(mp));
806 
807 	/*
808 	 * Lookup requests outside of open() that specify LOCKSHARED
809 	 * only need a shared lock on the leaf vnode.
810 	 */
811 	return (0);
812 }
813 
814 /*
815  * Various filesystems expect to be able to copy a name component with length
816  * bounded by NAME_MAX into a directory entry buffer of size MAXNAMLEN.  Make
817  * sure that these are the same size.
818  */
819 _Static_assert(MAXNAMLEN == NAME_MAX,
820     "MAXNAMLEN and NAME_MAX have different values");
821 
822 static int __noinline
823 vfs_lookup_degenerate(struct nameidata *ndp, struct vnode *dp, int wantparent)
824 {
825 	struct componentname *cnp;
826 	struct mount *mp;
827 	int error;
828 
829 	cnp = &ndp->ni_cnd;
830 
831 	cnp->cn_flags |= ISLASTCN;
832 
833 	mp = atomic_load_ptr(&dp->v_mount);
834 	if (needs_exclusive_leaf(mp, cnp->cn_flags)) {
835 		cnp->cn_lkflags &= ~LK_SHARED;
836 		cnp->cn_lkflags |= LK_EXCLUSIVE;
837 	}
838 
839 	vn_lock(dp,
840 	    compute_cn_lkflags(mp, cnp->cn_lkflags | LK_RETRY,
841 	    cnp->cn_flags));
842 
843 	if (dp->v_type != VDIR) {
844 		error = ENOTDIR;
845 		goto bad;
846 	}
847 	if (cnp->cn_nameiop != LOOKUP) {
848 		error = EISDIR;
849 		goto bad;
850 	}
851 	if (wantparent) {
852 		ndp->ni_dvp = dp;
853 		VREF(dp);
854 	}
855 	ndp->ni_vp = dp;
856 	cnp->cn_namelen = 0;
857 
858 	if (cnp->cn_flags & AUDITVNODE1)
859 		AUDIT_ARG_VNODE1(dp);
860 	else if (cnp->cn_flags & AUDITVNODE2)
861 		AUDIT_ARG_VNODE2(dp);
862 
863 	if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
864 		VOP_UNLOCK(dp);
865 	/* XXX This should probably move to the top of function. */
866 	if (cnp->cn_flags & SAVESTART)
867 		panic("lookup: SAVESTART");
868 	return (0);
869 bad:
870 	VOP_UNLOCK(dp);
871 	return (error);
872 }
873 
874 /*
875  * FAILIFEXISTS handling.
876  *
877  * XXX namei called with LOCKPARENT but not LOCKLEAF has the strange
878  * behaviour of leaving the vnode unlocked if the target is the same
879  * vnode as the parent.
880  */
881 static int __noinline
882 vfs_lookup_failifexists(struct nameidata *ndp)
883 {
884 	struct componentname *cnp __diagused;
885 
886 	cnp = &ndp->ni_cnd;
887 
888 	MPASS((cnp->cn_flags & ISSYMLINK) == 0);
889 	if (ndp->ni_vp == ndp->ni_dvp)
890 		vrele(ndp->ni_dvp);
891 	else
892 		vput(ndp->ni_dvp);
893 	vrele(ndp->ni_vp);
894 	ndp->ni_dvp = NULL;
895 	ndp->ni_vp = NULL;
896 	NDFREE_PNBUF(ndp);
897 	return (EEXIST);
898 }
899 
900 /*
901  * Search a pathname.
902  * This is a very central and rather complicated routine.
903  *
904  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
905  * The starting directory is taken from ni_startdir. The pathname is
906  * descended until done, or a symbolic link is encountered. The variable
907  * ni_more is clear if the path is completed; it is set to one if a
908  * symbolic link needing interpretation is encountered.
909  *
910  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
911  * whether the name is to be looked up, created, renamed, or deleted.
912  * When CREATE, RENAME, or DELETE is specified, information usable in
913  * creating, renaming, or deleting a directory entry may be calculated.
914  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
915  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
916  * returned unlocked. Otherwise the parent directory is not returned. If
917  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
918  * the target is returned locked, otherwise it is returned unlocked.
919  * When creating or renaming and LOCKPARENT is specified, the target may not
920  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
921  *
922  * Overall outline of lookup:
923  *
924  * dirloop:
925  *	identify next component of name at ndp->ni_ptr
926  *	handle degenerate case where name is null string
927  *	if .. and crossing mount points and on mounted filesys, find parent
928  *	call VOP_LOOKUP routine for next component name
929  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
930  *	    component vnode returned in ni_vp (if it exists), locked.
931  *	if result vnode is mounted on and crossing mount points,
932  *	    find mounted on vnode
933  *	if more components of name, do next level at dirloop
934  *	return the answer in ni_vp, locked if LOCKLEAF set
935  *	    if LOCKPARENT set, return locked parent in ni_dvp
936  *	    if WANTPARENT set, return unlocked parent in ni_dvp
937  */
938 int
939 vfs_lookup(struct nameidata *ndp)
940 {
941 	char *cp;			/* pointer into pathname argument */
942 	char *prev_ni_next;		/* saved ndp->ni_next */
943 	char *nulchar;			/* location of '\0' in cn_pnbuf */
944 	char *lastchar;			/* location of the last character */
945 	struct vnode *dp = NULL;	/* the directory we are searching */
946 	struct vnode *tdp;		/* saved dp */
947 	struct mount *mp;		/* mount table entry */
948 	struct prison *pr;
949 	size_t prev_ni_pathlen;		/* saved ndp->ni_pathlen */
950 	int docache;			/* == 0 do not cache last component */
951 	int wantparent;			/* 1 => wantparent or lockparent flag */
952 	int rdonly;			/* lookup read-only flag bit */
953 	int error = 0;
954 	int dpunlocked = 0;		/* dp has already been unlocked */
955 	int relookup = 0;		/* do not consume the path component */
956 	struct componentname *cnp = &ndp->ni_cnd;
957 	int lkflags_save;
958 	int ni_dvp_unlocked;
959 
960 	/*
961 	 * Setup: break out flag bits into variables.
962 	 */
963 	ni_dvp_unlocked = 0;
964 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
965 	KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
966 	    ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
967 	/*
968 	 * When set to zero, docache causes the last component of the
969 	 * pathname to be deleted from the cache and the full lookup
970 	 * of the name to be done (via VOP_CACHEDLOOKUP()). Often
971 	 * filesystems need some pre-computed values that are made
972 	 * during the full lookup, for instance UFS sets dp->i_offset.
973 	 *
974 	 * The docache variable is set to zero when requested by the
975 	 * NOCACHE flag and for all modifying operations except CREATE.
976 	 */
977 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
978 	if (cnp->cn_nameiop == DELETE ||
979 	    (wantparent && cnp->cn_nameiop != CREATE &&
980 	     cnp->cn_nameiop != LOOKUP))
981 		docache = 0;
982 	rdonly = cnp->cn_flags & RDONLY;
983 	cnp->cn_flags &= ~ISSYMLINK;
984 	ndp->ni_dvp = NULL;
985 
986 	cnp->cn_lkflags = LK_SHARED;
987 	dp = ndp->ni_startdir;
988 	ndp->ni_startdir = NULLVP;
989 
990 	/*
991 	 * Leading slashes, if any, are supposed to be skipped by the caller.
992 	 */
993 	MPASS(cnp->cn_nameptr[0] != '/');
994 
995 	/*
996 	 * Check for degenerate name (e.g. / or "") which is a way of talking
997 	 * about a directory, e.g. like "/." or ".".
998 	 */
999 	if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
1000 		error = vfs_lookup_degenerate(ndp, dp, wantparent);
1001 		if (error == 0)
1002 			goto success_right_lock;
1003 		goto bad_unlocked;
1004 	}
1005 
1006 	/*
1007 	 * Nul-out trailing slashes (e.g., "foo///" -> "foo").
1008 	 *
1009 	 * This must be done before VOP_LOOKUP() because some fs's don't know
1010 	 * about trailing slashes.  Remember if there were trailing slashes to
1011 	 * handle symlinks, existing non-directories and non-existing files
1012 	 * that won't be directories specially later.
1013 	 */
1014 	MPASS(ndp->ni_pathlen >= 2);
1015 	lastchar = &cnp->cn_nameptr[ndp->ni_pathlen - 2];
1016 	if (*lastchar == '/') {
1017 		while (lastchar >= cnp->cn_pnbuf) {
1018 			*lastchar = '\0';
1019 			lastchar--;
1020 			ndp->ni_pathlen--;
1021 			if (*lastchar != '/') {
1022 				break;
1023 			}
1024 		}
1025 		cnp->cn_flags |= TRAILINGSLASH;
1026 	}
1027 
1028 	/*
1029 	 * We use shared locks until we hit the parent of the last cn then
1030 	 * we adjust based on the requesting flags.
1031 	 */
1032 	vn_lock(dp,
1033 	    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY,
1034 	    cnp->cn_flags));
1035 
1036 dirloop:
1037 	/*
1038 	 * Search a new directory.
1039 	 *
1040 	 * The last component of the filename is left accessible via
1041 	 * cnp->cn_nameptr for callers that need the name. Callers needing
1042 	 * the name set the SAVENAME flag. When done, they assume
1043 	 * responsibility for freeing the pathname buffer.
1044 	 *
1045 	 * Store / as a temporary sentinel so that we only have one character
1046 	 * to test for. Pathnames tend to be short so this should not be
1047 	 * resulting in cache misses.
1048 	 */
1049 	nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
1050 	KASSERT(*nulchar == '\0',
1051 	    ("%s: expected nul at %p; string [%s]\n", __func__, nulchar,
1052 	    cnp->cn_pnbuf));
1053 	*nulchar = '/';
1054 	for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
1055 		KASSERT(*cp != '\0',
1056 		    ("%s: encountered unexpected nul; string [%s]\n", __func__,
1057 		    cnp->cn_nameptr));
1058 		continue;
1059 	}
1060 	*nulchar = '\0';
1061 	cnp->cn_namelen = cp - cnp->cn_nameptr;
1062 	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
1063 		error = ENAMETOOLONG;
1064 		goto bad;
1065 	}
1066 #ifdef NAMEI_DIAGNOSTIC
1067 	{ char c = *cp;
1068 	*cp = '\0';
1069 	printf("{%s}: ", cnp->cn_nameptr);
1070 	*cp = c; }
1071 #endif
1072 	prev_ni_pathlen = ndp->ni_pathlen;
1073 	ndp->ni_pathlen -= cnp->cn_namelen;
1074 	KASSERT(ndp->ni_pathlen <= PATH_MAX,
1075 	    ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
1076 	prev_ni_next = ndp->ni_next;
1077 	ndp->ni_next = cp;
1078 
1079 	/*
1080 	 * Something else should be clearing this.
1081 	 */
1082 	cnp->cn_flags &= ~(ISDOTDOT|ISLASTCN);
1083 
1084 	cnp->cn_flags |= MAKEENTRY;
1085 	if (*cp == '\0' && docache == 0)
1086 		cnp->cn_flags &= ~MAKEENTRY;
1087 	if (cnp->cn_namelen == 2 &&
1088 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
1089 		cnp->cn_flags |= ISDOTDOT;
1090 	if (*ndp->ni_next == 0) {
1091 		cnp->cn_flags |= ISLASTCN;
1092 
1093 		if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
1094 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))) {
1095 			error = EINVAL;
1096 			goto bad;
1097 		}
1098 	}
1099 
1100 	nameicap_tracker_add(ndp, dp);
1101 
1102 	/*
1103 	 * Make sure degenerate names don't get here, their handling was
1104 	 * previously found in this spot.
1105 	 */
1106 	MPASS(cnp->cn_nameptr[0] != '\0');
1107 
1108 	/*
1109 	 * Handle "..": five special cases.
1110 	 * 0. If doing a capability lookup and lookup_cap_dotdot is
1111 	 *    disabled, return ENOTCAPABLE.
1112 	 * 1. Return an error if this is the last component of
1113 	 *    the name and the operation is DELETE or RENAME.
1114 	 * 2. If at root directory (e.g. after chroot)
1115 	 *    or at absolute root directory
1116 	 *    then ignore it so can't get out.
1117 	 * 3. If this vnode is the root of a mounted
1118 	 *    filesystem, then replace it with the
1119 	 *    vnode which was mounted on so we take the
1120 	 *    .. in the other filesystem.
1121 	 * 4. If the vnode is the top directory of
1122 	 *    the jail or chroot, don't let them out.
1123 	 * 5. If doing a capability lookup and lookup_cap_dotdot is
1124 	 *    enabled, return ENOTCAPABLE if the lookup would escape
1125 	 *    from the initial file descriptor directory.  Checks are
1126 	 *    done by ensuring that namei() already traversed the
1127 	 *    result of dotdot lookup.
1128 	 */
1129 	if (cnp->cn_flags & ISDOTDOT) {
1130 		if ((ndp->ni_lcf & (NI_LCF_STRICTRELATIVE | NI_LCF_CAP_DOTDOT))
1131 		    == NI_LCF_STRICTRELATIVE) {
1132 #ifdef KTRACE
1133 			if (KTRPOINT(curthread, KTR_CAPFAIL))
1134 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1135 #endif
1136 			error = ENOTCAPABLE;
1137 			goto bad;
1138 		}
1139 		if ((cnp->cn_flags & ISLASTCN) != 0 &&
1140 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1141 			error = EINVAL;
1142 			goto bad;
1143 		}
1144 		for (;;) {
1145 			for (pr = cnp->cn_cred->cr_prison; pr != NULL;
1146 			     pr = pr->pr_parent)
1147 				if (dp == pr->pr_root)
1148 					break;
1149 			if (dp == ndp->ni_rootdir ||
1150 			    dp == ndp->ni_topdir ||
1151 			    dp == rootvnode ||
1152 			    pr != NULL ||
1153 			    ((dp->v_vflag & VV_ROOT) != 0 &&
1154 			     (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
1155 				ndp->ni_dvp = dp;
1156 				ndp->ni_vp = dp;
1157 				VREF(dp);
1158 				goto nextname;
1159 			}
1160 			if ((dp->v_vflag & VV_ROOT) == 0)
1161 				break;
1162 			if (VN_IS_DOOMED(dp)) {	/* forced unmount */
1163 				error = ENOENT;
1164 				goto bad;
1165 			}
1166 			tdp = dp;
1167 			dp = dp->v_mount->mnt_vnodecovered;
1168 			VREF(dp);
1169 			vput(tdp);
1170 			vn_lock(dp,
1171 			    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
1172 			    LK_RETRY, ISDOTDOT));
1173 			error = nameicap_check_dotdot(ndp, dp);
1174 			if (error != 0) {
1175 #ifdef KTRACE
1176 				if (KTRPOINT(curthread, KTR_CAPFAIL))
1177 					ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1178 #endif
1179 				goto bad;
1180 			}
1181 		}
1182 	}
1183 
1184 	/*
1185 	 * We now have a segment name to search for, and a directory to search.
1186 	 */
1187 unionlookup:
1188 #ifdef MAC
1189 	error = mac_vnode_check_lookup(cnp->cn_cred, dp, cnp);
1190 	if (__predict_false(error))
1191 		goto bad;
1192 #endif
1193 	ndp->ni_dvp = dp;
1194 	ndp->ni_vp = NULL;
1195 	ASSERT_VOP_LOCKED(dp, "lookup");
1196 	/*
1197 	 * If we have a shared lock we may need to upgrade the lock for the
1198 	 * last operation.
1199 	 */
1200 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
1201 	    dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
1202 		vn_lock(dp, LK_UPGRADE|LK_RETRY);
1203 	if (VN_IS_DOOMED(dp)) {
1204 		error = ENOENT;
1205 		goto bad;
1206 	}
1207 	/*
1208 	 * If we're looking up the last component and we need an exclusive
1209 	 * lock, adjust our lkflags.
1210 	 */
1211 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
1212 		cnp->cn_lkflags = LK_EXCLUSIVE;
1213 #ifdef NAMEI_DIAGNOSTIC
1214 	vn_printf(dp, "lookup in ");
1215 #endif
1216 	lkflags_save = cnp->cn_lkflags;
1217 	cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags,
1218 	    cnp->cn_flags);
1219 	error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
1220 	cnp->cn_lkflags = lkflags_save;
1221 	if (error != 0) {
1222 		KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
1223 #ifdef NAMEI_DIAGNOSTIC
1224 		printf("not found\n");
1225 #endif
1226 		if ((error == ENOENT) &&
1227 		    (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
1228 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
1229 			tdp = dp;
1230 			dp = dp->v_mount->mnt_vnodecovered;
1231 			VREF(dp);
1232 			vput(tdp);
1233 			vn_lock(dp,
1234 			    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
1235 			    LK_RETRY, cnp->cn_flags));
1236 			nameicap_tracker_add(ndp, dp);
1237 			goto unionlookup;
1238 		}
1239 
1240 		if (error == ERELOOKUP) {
1241 			vref(dp);
1242 			ndp->ni_vp = dp;
1243 			error = 0;
1244 			relookup = 1;
1245 			goto good;
1246 		}
1247 
1248 		if (error != EJUSTRETURN)
1249 			goto bad;
1250 		/*
1251 		 * At this point, we know we're at the end of the
1252 		 * pathname.  If creating / renaming, we can consider
1253 		 * allowing the file or directory to be created / renamed,
1254 		 * provided we're not on a read-only filesystem.
1255 		 */
1256 		if (rdonly) {
1257 			error = EROFS;
1258 			goto bad;
1259 		}
1260 		/* trailing slash only allowed for directories */
1261 		if ((cnp->cn_flags & TRAILINGSLASH) &&
1262 		    !(cnp->cn_flags & WILLBEDIR)) {
1263 			error = ENOENT;
1264 			goto bad;
1265 		}
1266 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1267 			VOP_UNLOCK(dp);
1268 		/*
1269 		 * We return with ni_vp NULL to indicate that the entry
1270 		 * doesn't currently exist, leaving a pointer to the
1271 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1272 		 */
1273 		if (cnp->cn_flags & SAVESTART) {
1274 			ndp->ni_startdir = ndp->ni_dvp;
1275 			VREF(ndp->ni_startdir);
1276 		}
1277 		goto success;
1278 	}
1279 
1280 good:
1281 #ifdef NAMEI_DIAGNOSTIC
1282 	printf("found\n");
1283 #endif
1284 	dp = ndp->ni_vp;
1285 
1286 	/*
1287 	 * Check to see if the vnode has been mounted on;
1288 	 * if so find the root of the mounted filesystem.
1289 	 */
1290 	while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
1291 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
1292 		if (vfs_busy(mp, 0))
1293 			continue;
1294 		vput(dp);
1295 		if (dp != ndp->ni_dvp)
1296 			vput(ndp->ni_dvp);
1297 		else
1298 			vrele(ndp->ni_dvp);
1299 		vrefact(vp_crossmp);
1300 		ndp->ni_dvp = vp_crossmp;
1301 		error = VFS_ROOT(mp, compute_cn_lkflags(mp, cnp->cn_lkflags,
1302 		    cnp->cn_flags), &tdp);
1303 		vfs_unbusy(mp);
1304 		if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
1305 			panic("vp_crossmp exclusively locked or reclaimed");
1306 		if (error) {
1307 			dpunlocked = 1;
1308 			goto bad2;
1309 		}
1310 		ndp->ni_vp = dp = tdp;
1311 	}
1312 
1313 	/*
1314 	 * Check for symbolic link
1315 	 */
1316 	if ((dp->v_type == VLNK) &&
1317 	    ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
1318 	     *ndp->ni_next == '/')) {
1319 		cnp->cn_flags |= ISSYMLINK;
1320 		if (VN_IS_DOOMED(dp)) {
1321 			/*
1322 			 * We can't know whether the directory was mounted with
1323 			 * NOSYMFOLLOW, so we can't follow safely.
1324 			 */
1325 			error = ENOENT;
1326 			goto bad2;
1327 		}
1328 		if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
1329 			error = EACCES;
1330 			goto bad2;
1331 		}
1332 		/*
1333 		 * Symlink code always expects an unlocked dvp.
1334 		 */
1335 		if (ndp->ni_dvp != ndp->ni_vp) {
1336 			VOP_UNLOCK(ndp->ni_dvp);
1337 			ni_dvp_unlocked = 1;
1338 		}
1339 		goto success;
1340 	}
1341 
1342 nextname:
1343 	/*
1344 	 * Not a symbolic link that we will follow.  Continue with the
1345 	 * next component if there is any; otherwise, we're done.
1346 	 */
1347 	KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1348 	    ("lookup: invalid path state."));
1349 	if (relookup) {
1350 		relookup = 0;
1351 		ndp->ni_pathlen = prev_ni_pathlen;
1352 		ndp->ni_next = prev_ni_next;
1353 		if (ndp->ni_dvp != dp)
1354 			vput(ndp->ni_dvp);
1355 		else
1356 			vrele(ndp->ni_dvp);
1357 		goto dirloop;
1358 	}
1359 	if (cnp->cn_flags & ISDOTDOT) {
1360 		error = nameicap_check_dotdot(ndp, ndp->ni_vp);
1361 		if (error != 0) {
1362 #ifdef KTRACE
1363 			if (KTRPOINT(curthread, KTR_CAPFAIL))
1364 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1365 #endif
1366 			goto bad2;
1367 		}
1368 	}
1369 	if (*ndp->ni_next == '/') {
1370 		cnp->cn_nameptr = ndp->ni_next;
1371 		while (*cnp->cn_nameptr == '/') {
1372 			cnp->cn_nameptr++;
1373 			ndp->ni_pathlen--;
1374 		}
1375 		if (ndp->ni_dvp != dp)
1376 			vput(ndp->ni_dvp);
1377 		else
1378 			vrele(ndp->ni_dvp);
1379 		goto dirloop;
1380 	}
1381 	/*
1382 	 * If we're processing a path with a trailing slash,
1383 	 * check that the end result is a directory.
1384 	 */
1385 	if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1386 		error = ENOTDIR;
1387 		goto bad2;
1388 	}
1389 	/*
1390 	 * Disallow directory write attempts on read-only filesystems.
1391 	 */
1392 	if (rdonly &&
1393 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1394 		error = EROFS;
1395 		goto bad2;
1396 	}
1397 	if (cnp->cn_flags & SAVESTART) {
1398 		ndp->ni_startdir = ndp->ni_dvp;
1399 		VREF(ndp->ni_startdir);
1400 	}
1401 	if (!wantparent) {
1402 		ni_dvp_unlocked = 2;
1403 		if (ndp->ni_dvp != dp)
1404 			vput(ndp->ni_dvp);
1405 		else
1406 			vrele(ndp->ni_dvp);
1407 	} else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1408 		VOP_UNLOCK(ndp->ni_dvp);
1409 		ni_dvp_unlocked = 1;
1410 	}
1411 
1412 	if (cnp->cn_flags & AUDITVNODE1)
1413 		AUDIT_ARG_VNODE1(dp);
1414 	else if (cnp->cn_flags & AUDITVNODE2)
1415 		AUDIT_ARG_VNODE2(dp);
1416 
1417 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1418 		VOP_UNLOCK(dp);
1419 success:
1420 	/*
1421 	 * FIXME: for lookups which only cross a mount point to fetch the
1422 	 * root vnode, ni_dvp will be set to vp_crossmp. This can be a problem
1423 	 * if either WANTPARENT or LOCKPARENT is set.
1424 	 */
1425 	/*
1426 	 * Because of shared lookup we may have the vnode shared locked, but
1427 	 * the caller may want it to be exclusively locked.
1428 	 */
1429 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1430 	    VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1431 		vn_lock(dp, LK_UPGRADE | LK_RETRY);
1432 		if (VN_IS_DOOMED(dp)) {
1433 			error = ENOENT;
1434 			goto bad2;
1435 		}
1436 	}
1437 success_right_lock:
1438 	if (ndp->ni_vp != NULL) {
1439 		if ((cnp->cn_flags & ISDOTDOT) == 0)
1440 			nameicap_tracker_add(ndp, ndp->ni_vp);
1441 		if ((cnp->cn_flags & (FAILIFEXISTS | ISSYMLINK)) == FAILIFEXISTS)
1442 			return (vfs_lookup_failifexists(ndp));
1443 	}
1444 	return (0);
1445 
1446 bad2:
1447 	if (ni_dvp_unlocked != 2) {
1448 		if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1449 			vput(ndp->ni_dvp);
1450 		else
1451 			vrele(ndp->ni_dvp);
1452 	}
1453 bad:
1454 	if (!dpunlocked)
1455 		vput(dp);
1456 bad_unlocked:
1457 	ndp->ni_vp = NULL;
1458 	return (error);
1459 }
1460 
1461 /*
1462  * relookup - lookup a path name component
1463  *    Used by lookup to re-acquire things.
1464  */
1465 int
1466 vfs_relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
1467 {
1468 	struct vnode *dp = NULL;		/* the directory we are searching */
1469 	int rdonly;			/* lookup read-only flag bit */
1470 	int error = 0;
1471 
1472 	KASSERT(cnp->cn_flags & ISLASTCN,
1473 	    ("relookup: Not given last component."));
1474 	/*
1475 	 * Setup: break out flag bits into variables.
1476 	 */
1477 	KASSERT((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) != 0,
1478 	    ("relookup: parent not wanted"));
1479 	rdonly = cnp->cn_flags & RDONLY;
1480 	cnp->cn_flags &= ~ISSYMLINK;
1481 	dp = dvp;
1482 	cnp->cn_lkflags = LK_EXCLUSIVE;
1483 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1484 
1485 	/*
1486 	 * Search a new directory.
1487 	 *
1488 	 * The last component of the filename is left accessible via
1489 	 * cnp->cn_nameptr for callers that need the name. Callers needing
1490 	 * the name set the SAVENAME flag. When done, they assume
1491 	 * responsibility for freeing the pathname buffer.
1492 	 */
1493 #ifdef NAMEI_DIAGNOSTIC
1494 	printf("{%s}: ", cnp->cn_nameptr);
1495 #endif
1496 
1497 	/*
1498 	 * Check for "" which represents the root directory after slash
1499 	 * removal.
1500 	 */
1501 	if (cnp->cn_nameptr[0] == '\0') {
1502 		/*
1503 		 * Support only LOOKUP for "/" because lookup()
1504 		 * can't succeed for CREATE, DELETE and RENAME.
1505 		 */
1506 		KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1507 		KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1508 
1509 		if (!(cnp->cn_flags & LOCKLEAF))
1510 			VOP_UNLOCK(dp);
1511 		*vpp = dp;
1512 		/* XXX This should probably move to the top of function. */
1513 		if (cnp->cn_flags & SAVESTART)
1514 			panic("lookup: SAVESTART");
1515 		return (0);
1516 	}
1517 
1518 	if (cnp->cn_flags & ISDOTDOT)
1519 		panic ("relookup: lookup on dot-dot");
1520 
1521 	/*
1522 	 * We now have a segment name to search for, and a directory to search.
1523 	 */
1524 #ifdef NAMEI_DIAGNOSTIC
1525 	vn_printf(dp, "search in ");
1526 #endif
1527 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1528 		KASSERT(*vpp == NULL, ("leaf should be empty"));
1529 		if (error != EJUSTRETURN)
1530 			goto bad;
1531 		/*
1532 		 * If creating and at end of pathname, then can consider
1533 		 * allowing file to be created.
1534 		 */
1535 		if (rdonly) {
1536 			error = EROFS;
1537 			goto bad;
1538 		}
1539 		/* ASSERT(dvp == ndp->ni_startdir) */
1540 		if (cnp->cn_flags & SAVESTART)
1541 			VREF(dvp);
1542 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1543 			VOP_UNLOCK(dp);
1544 		/*
1545 		 * We return with ni_vp NULL to indicate that the entry
1546 		 * doesn't currently exist, leaving a pointer to the
1547 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1548 		 */
1549 		return (0);
1550 	}
1551 
1552 	dp = *vpp;
1553 
1554 	/*
1555 	 * Disallow directory write attempts on read-only filesystems.
1556 	 */
1557 	if (rdonly &&
1558 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1559 		if (dvp == dp)
1560 			vrele(dvp);
1561 		else
1562 			vput(dvp);
1563 		error = EROFS;
1564 		goto bad;
1565 	}
1566 	/*
1567 	 * Set the parent lock/ref state to the requested state.
1568 	 */
1569 	if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp)
1570 		VOP_UNLOCK(dvp);
1571 	/*
1572 	 * Check for symbolic link
1573 	 */
1574 	KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1575 	    ("relookup: symlink found.\n"));
1576 
1577 	/* ASSERT(dvp == ndp->ni_startdir) */
1578 	if (cnp->cn_flags & SAVESTART)
1579 		VREF(dvp);
1580 
1581 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1582 		VOP_UNLOCK(dp);
1583 	return (0);
1584 bad:
1585 	vput(dp);
1586 	*vpp = NULL;
1587 	return (error);
1588 }
1589 
1590 /*
1591  * Free data allocated by namei(); see namei(9) for details.
1592  */
1593 void
1594 NDFREE_PNBUF(struct nameidata *ndp)
1595 {
1596 
1597 	if ((ndp->ni_cnd.cn_flags & HASBUF) != 0) {
1598 		MPASS((ndp->ni_cnd.cn_flags & (SAVENAME | SAVESTART)) != 0);
1599 		uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
1600 		ndp->ni_cnd.cn_flags &= ~HASBUF;
1601 	}
1602 }
1603 
1604 /*
1605  * NDFREE_PNBUF replacement for callers that know there is no buffer.
1606  *
1607  * This is a hack. Preferably the VFS layer would not produce anything more
1608  * than it was asked to do. Unfortunately several non-LOOKUP cases can add the
1609  * HASBUF flag to the result. Even then an interface could be implemented where
1610  * the caller specifies what they expected to see in the result and what they
1611  * are going to take care of.
1612  *
1613  * In the meantime provide this kludge as a trivial replacement for NDFREE_PNBUF
1614  * calls scattered throughout the kernel where we know for a fact the flag must not
1615  * be seen.
1616  */
1617 #ifdef INVARIANTS
1618 void
1619 NDFREE_NOTHING(struct nameidata *ndp)
1620 {
1621 	struct componentname *cnp;
1622 
1623 	cnp = &ndp->ni_cnd;
1624 	KASSERT(cnp->cn_nameiop == LOOKUP, ("%s: got non-LOOKUP op %d\n",
1625 	    __func__, cnp->cn_nameiop));
1626 	KASSERT((cnp->cn_flags & (SAVENAME | HASBUF)) == 0,
1627 	    ("%s: bad flags \%" PRIx64 "\n", __func__, cnp->cn_flags));
1628 }
1629 #endif
1630 
1631 void
1632 (NDFREE)(struct nameidata *ndp, const u_int flags)
1633 {
1634 	int unlock_dvp;
1635 	int unlock_vp;
1636 
1637 	unlock_dvp = 0;
1638 	unlock_vp = 0;
1639 
1640 	if (!(flags & NDF_NO_FREE_PNBUF)) {
1641 		NDFREE_PNBUF(ndp);
1642 	}
1643 	if (!(flags & NDF_NO_VP_UNLOCK) &&
1644 	    (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
1645 		unlock_vp = 1;
1646 	if (!(flags & NDF_NO_DVP_UNLOCK) &&
1647 	    (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
1648 	    ndp->ni_dvp != ndp->ni_vp)
1649 		unlock_dvp = 1;
1650 	if (!(flags & NDF_NO_VP_RELE) && ndp->ni_vp) {
1651 		if (unlock_vp) {
1652 			vput(ndp->ni_vp);
1653 			unlock_vp = 0;
1654 		} else
1655 			vrele(ndp->ni_vp);
1656 		ndp->ni_vp = NULL;
1657 	}
1658 	if (unlock_vp)
1659 		VOP_UNLOCK(ndp->ni_vp);
1660 	if (!(flags & NDF_NO_DVP_RELE) &&
1661 	    (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
1662 		if (unlock_dvp) {
1663 			vput(ndp->ni_dvp);
1664 			unlock_dvp = 0;
1665 		} else
1666 			vrele(ndp->ni_dvp);
1667 		ndp->ni_dvp = NULL;
1668 	}
1669 	if (unlock_dvp)
1670 		VOP_UNLOCK(ndp->ni_dvp);
1671 	if (!(flags & NDF_NO_STARTDIR_RELE) &&
1672 	    (ndp->ni_cnd.cn_flags & SAVESTART)) {
1673 		vrele(ndp->ni_startdir);
1674 		ndp->ni_startdir = NULL;
1675 	}
1676 }
1677 
1678 #ifdef INVARIANTS
1679 /*
1680  * Validate the final state of ndp after the lookup.
1681  *
1682  * Historically filesystems were allowed to modify cn_flags. Most notably they
1683  * can add SAVENAME to the request, resulting in HASBUF and pushing subsequent
1684  * clean up to the consumer. In practice this seems to only concern != LOOKUP
1685  * operations.
1686  *
1687  * As a step towards stricter API contract this routine validates the state to
1688  * clean up. Note validation is a work in progress with the intent of becoming
1689  * stricter over time.
1690  */
1691 #define NDMODIFYINGFLAGS (LOCKLEAF | LOCKPARENT | WANTPARENT | SAVENAME | SAVESTART | HASBUF)
1692 void
1693 NDVALIDATE(struct nameidata *ndp)
1694 {
1695 	struct componentname *cnp;
1696 	uint64_t used, orig;
1697 
1698 	cnp = &ndp->ni_cnd;
1699 	orig = cnp->cn_origflags;
1700 	used = cnp->cn_flags;
1701 	switch (cnp->cn_nameiop) {
1702 	case LOOKUP:
1703 		/*
1704 		 * For plain lookup we require strict conformance -- nothing
1705 		 * to clean up if it was not requested by the caller.
1706 		 */
1707 		orig &= NDMODIFYINGFLAGS;
1708 		used &= NDMODIFYINGFLAGS;
1709 		if ((orig & (SAVENAME | SAVESTART)) != 0)
1710 			orig |= HASBUF;
1711 		if (orig != used) {
1712 			goto out_mismatch;
1713 		}
1714 		break;
1715 	case CREATE:
1716 	case DELETE:
1717 	case RENAME:
1718 		/*
1719 		 * Some filesystems set SAVENAME to provoke HASBUF, accomodate
1720 		 * for it until it gets fixed.
1721 		 */
1722 		orig &= NDMODIFYINGFLAGS;
1723 		orig |= (SAVENAME | HASBUF);
1724 		used &= NDMODIFYINGFLAGS;
1725 		used |= (SAVENAME | HASBUF);
1726 		if (orig != used) {
1727 			goto out_mismatch;
1728 		}
1729 		break;
1730 	}
1731 	return;
1732 out_mismatch:
1733 	panic("%s: mismatched flags for op %d: added %" PRIx64 ", "
1734 	    "removed %" PRIx64" (%" PRIx64" != %" PRIx64"; stored %" PRIx64" != %" PRIx64")",
1735 	    __func__, cnp->cn_nameiop, used & ~orig, orig &~ used,
1736 	    orig, used, cnp->cn_origflags, cnp->cn_flags);
1737 }
1738 #endif
1739 
1740 /*
1741  * Determine if there is a suitable alternate filename under the specified
1742  * prefix for the specified path.  If the create flag is set, then the
1743  * alternate prefix will be used so long as the parent directory exists.
1744  * This is used by the various compatibility ABIs so that Linux binaries prefer
1745  * files under /compat/linux for example.  The chosen path (whether under
1746  * the prefix or under /) is returned in a kernel malloc'd buffer pointed
1747  * to by pathbuf.  The caller is responsible for free'ing the buffer from
1748  * the M_TEMP bucket if one is returned.
1749  */
1750 int
1751 kern_alternate_path(const char *prefix, const char *path, enum uio_seg pathseg,
1752     char **pathbuf, int create, int dirfd)
1753 {
1754 	struct nameidata nd, ndroot;
1755 	char *ptr, *buf, *cp;
1756 	size_t len, sz;
1757 	int error;
1758 
1759 	buf = (char *) malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1760 	*pathbuf = buf;
1761 
1762 	/* Copy the prefix into the new pathname as a starting point. */
1763 	len = strlcpy(buf, prefix, MAXPATHLEN);
1764 	if (len >= MAXPATHLEN) {
1765 		*pathbuf = NULL;
1766 		free(buf, M_TEMP);
1767 		return (EINVAL);
1768 	}
1769 	sz = MAXPATHLEN - len;
1770 	ptr = buf + len;
1771 
1772 	/* Append the filename to the prefix. */
1773 	if (pathseg == UIO_SYSSPACE)
1774 		error = copystr(path, ptr, sz, &len);
1775 	else
1776 		error = copyinstr(path, ptr, sz, &len);
1777 
1778 	if (error) {
1779 		*pathbuf = NULL;
1780 		free(buf, M_TEMP);
1781 		return (error);
1782 	}
1783 
1784 	/* Only use a prefix with absolute pathnames. */
1785 	if (*ptr != '/') {
1786 		error = EINVAL;
1787 		goto keeporig;
1788 	}
1789 
1790 	if (dirfd != AT_FDCWD) {
1791 		/*
1792 		 * We want the original because the "prefix" is
1793 		 * included in the already opened dirfd.
1794 		 */
1795 		bcopy(ptr, buf, len);
1796 		return (0);
1797 	}
1798 
1799 	/*
1800 	 * We know that there is a / somewhere in this pathname.
1801 	 * Search backwards for it, to find the file's parent dir
1802 	 * to see if it exists in the alternate tree. If it does,
1803 	 * and we want to create a file (cflag is set). We don't
1804 	 * need to worry about the root comparison in this case.
1805 	 */
1806 
1807 	if (create) {
1808 		for (cp = &ptr[len] - 1; *cp != '/'; cp--);
1809 		*cp = '\0';
1810 
1811 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, buf);
1812 		error = namei(&nd);
1813 		*cp = '/';
1814 		if (error != 0)
1815 			goto keeporig;
1816 	} else {
1817 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, buf);
1818 
1819 		error = namei(&nd);
1820 		if (error != 0)
1821 			goto keeporig;
1822 
1823 		/*
1824 		 * We now compare the vnode of the prefix to the one
1825 		 * vnode asked. If they resolve to be the same, then we
1826 		 * ignore the match so that the real root gets used.
1827 		 * This avoids the problem of traversing "../.." to find the
1828 		 * root directory and never finding it, because "/" resolves
1829 		 * to the emulation root directory. This is expensive :-(
1830 		 */
1831 		NDINIT(&ndroot, LOOKUP, FOLLOW, UIO_SYSSPACE, prefix);
1832 
1833 		/* We shouldn't ever get an error from this namei(). */
1834 		error = namei(&ndroot);
1835 		if (error == 0) {
1836 			if (nd.ni_vp == ndroot.ni_vp)
1837 				error = ENOENT;
1838 
1839 			NDFREE_PNBUF(&ndroot);
1840 			vrele(ndroot.ni_vp);
1841 		}
1842 	}
1843 
1844 	NDFREE_PNBUF(&nd);
1845 	vrele(nd.ni_vp);
1846 
1847 keeporig:
1848 	/* If there was an error, use the original path name. */
1849 	if (error)
1850 		bcopy(ptr, buf, len);
1851 	return (error);
1852 }
1853