xref: /freebsd/sys/kern/vfs_lookup.c (revision f126d349810fdb512c0b01e101342d430b947488)
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 #ifdef INVARIANTS
78 static void NDVALIDATE_impl(struct nameidata *, int);
79 #define NDVALIDATE(ndp) NDVALIDATE_impl(ndp, __LINE__)
80 #else
81 #define NDVALIDATE(ndp)
82 #endif
83 
84 SDT_PROVIDER_DEFINE(vfs);
85 SDT_PROBE_DEFINE4(vfs, namei, lookup, entry, "struct vnode *", "char *",
86     "unsigned long", "bool");
87 SDT_PROBE_DEFINE4(vfs, namei, lookup, return, "int", "struct vnode *", "bool",
88     "struct nameidata");
89 
90 /* Allocation zone for namei. */
91 uma_zone_t namei_zone;
92 
93 /* Placeholder vnode for mp traversal. */
94 static struct vnode *vp_crossmp;
95 
96 static int
97 crossmp_vop_islocked(struct vop_islocked_args *ap)
98 {
99 
100 	return (LK_SHARED);
101 }
102 
103 static int
104 crossmp_vop_lock1(struct vop_lock1_args *ap)
105 {
106 	struct vnode *vp;
107 	struct lock *lk __diagused;
108 	int flags;
109 
110 	vp = ap->a_vp;
111 	lk = vp->v_vnlock;
112 	flags = ap->a_flags;
113 
114 	KASSERT((flags & (LK_SHARED | LK_NOWAIT)) == (LK_SHARED | LK_NOWAIT),
115 	    ("%s: invalid lock request 0x%x for crossmp", __func__, flags));
116 
117 	if ((flags & LK_INTERLOCK) != 0)
118 		VI_UNLOCK(vp);
119 	LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, ap->a_file, ap->a_line);
120 	return (0);
121 }
122 
123 static int
124 crossmp_vop_unlock(struct vop_unlock_args *ap)
125 {
126 	struct vnode *vp;
127 	struct lock *lk __diagused;
128 
129 	vp = ap->a_vp;
130 	lk = vp->v_vnlock;
131 
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 	cnp->cn_pnbuf = NULL;
258 	cnp->cn_nameptr = NULL;
259 }
260 
261 static int
262 namei_handle_root(struct nameidata *ndp, struct vnode **dpp)
263 {
264 	struct componentname *cnp;
265 
266 	cnp = &ndp->ni_cnd;
267 	if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0) {
268 #ifdef KTRACE
269 		if (KTRPOINT(curthread, KTR_CAPFAIL))
270 			ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
271 #endif
272 		return (ENOTCAPABLE);
273 	}
274 	while (*(cnp->cn_nameptr) == '/') {
275 		cnp->cn_nameptr++;
276 		ndp->ni_pathlen--;
277 	}
278 	*dpp = ndp->ni_rootdir;
279 	vrefact(*dpp);
280 	return (0);
281 }
282 
283 static int
284 namei_setup(struct nameidata *ndp, struct vnode **dpp, struct pwd **pwdp)
285 {
286 	struct componentname *cnp;
287 	struct thread *td;
288 	struct pwd *pwd;
289 	int error;
290 	bool startdir_used;
291 
292 	cnp = &ndp->ni_cnd;
293 	td = curthread;
294 
295 	startdir_used = false;
296 	*pwdp = NULL;
297 	*dpp = NULL;
298 
299 #ifdef CAPABILITY_MODE
300 	/*
301 	 * In capability mode, lookups must be restricted to happen in
302 	 * the subtree with the root specified by the file descriptor:
303 	 * - The root must be real file descriptor, not the pseudo-descriptor
304 	 *   AT_FDCWD.
305 	 * - The passed path must be relative and not absolute.
306 	 * - If lookup_cap_dotdot is disabled, path must not contain the
307 	 *   '..' components.
308 	 * - If lookup_cap_dotdot is enabled, we verify that all '..'
309 	 *   components lookups result in the directories which were
310 	 *   previously walked by us, which prevents an escape from
311 	 *   the relative root.
312 	 */
313 	if (IN_CAPABILITY_MODE(td) && (cnp->cn_flags & NOCAPCHECK) == 0) {
314 		ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
315 		ndp->ni_resflags |= NIRES_STRICTREL;
316 		if (ndp->ni_dirfd == AT_FDCWD) {
317 #ifdef KTRACE
318 			if (KTRPOINT(td, KTR_CAPFAIL))
319 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
320 #endif
321 			return (ECAPMODE);
322 		}
323 	}
324 #endif
325 	error = 0;
326 
327 	/*
328 	 * Get starting point for the translation.
329 	 */
330 	pwd = pwd_hold(td);
331 	/*
332 	 * The reference on ni_rootdir is acquired in the block below to avoid
333 	 * back-to-back atomics for absolute lookups.
334 	 */
335 	ndp->ni_rootdir = pwd->pwd_rdir;
336 	ndp->ni_topdir = pwd->pwd_jdir;
337 
338 	if (cnp->cn_pnbuf[0] == '/') {
339 		ndp->ni_resflags |= NIRES_ABS;
340 		error = namei_handle_root(ndp, dpp);
341 	} else {
342 		if (ndp->ni_startdir != NULL) {
343 			*dpp = ndp->ni_startdir;
344 			startdir_used = true;
345 		} else if (ndp->ni_dirfd == AT_FDCWD) {
346 			*dpp = pwd->pwd_cdir;
347 			vrefact(*dpp);
348 		} else {
349 			if (cnp->cn_flags & AUDITVNODE1)
350 				AUDIT_ARG_ATFD1(ndp->ni_dirfd);
351 			if (cnp->cn_flags & AUDITVNODE2)
352 				AUDIT_ARG_ATFD2(ndp->ni_dirfd);
353 
354 			error = fgetvp_lookup(ndp->ni_dirfd, ndp, dpp);
355 		}
356 		if (error == 0 && (*dpp)->v_type != VDIR &&
357 		    (cnp->cn_pnbuf[0] != '\0' ||
358 		    (cnp->cn_flags & EMPTYPATH) == 0))
359 			error = ENOTDIR;
360 	}
361 	if (error == 0 && (cnp->cn_flags & RBENEATH) != 0) {
362 		if (cnp->cn_pnbuf[0] == '/') {
363 			error = ENOTCAPABLE;
364 		} else if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) == 0) {
365 			ndp->ni_lcf |= NI_LCF_STRICTRELATIVE |
366 			    NI_LCF_CAP_DOTDOT;
367 		}
368 	}
369 
370 	/*
371 	 * If we are auditing the kernel pathname, save the user pathname.
372 	 */
373 	if (cnp->cn_flags & AUDITVNODE1)
374 		AUDIT_ARG_UPATH1_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
375 	if (cnp->cn_flags & AUDITVNODE2)
376 		AUDIT_ARG_UPATH2_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
377 	if (ndp->ni_startdir != NULL && !startdir_used)
378 		vrele(ndp->ni_startdir);
379 	if (error != 0) {
380 		if (*dpp != NULL)
381 			vrele(*dpp);
382 		pwd_drop(pwd);
383 		return (error);
384 	}
385 	if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0 &&
386 	    lookup_cap_dotdot != 0)
387 		ndp->ni_lcf |= NI_LCF_CAP_DOTDOT;
388 	SDT_PROBE4(vfs, namei, lookup, entry, *dpp, cnp->cn_pnbuf,
389 	    cnp->cn_flags, false);
390 	*pwdp = pwd;
391 	return (0);
392 }
393 
394 static int
395 namei_getpath(struct nameidata *ndp)
396 {
397 	struct componentname *cnp;
398 	int error;
399 
400 	cnp = &ndp->ni_cnd;
401 
402 	/*
403 	 * Get a buffer for the name to be translated, and copy the
404 	 * name into the buffer.
405 	 */
406 	cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
407 	if (ndp->ni_segflg == UIO_SYSSPACE) {
408 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
409 		    &ndp->ni_pathlen);
410 	} else {
411 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
412 		    &ndp->ni_pathlen);
413 	}
414 
415 	return (error);
416 }
417 
418 static int
419 namei_emptypath(struct nameidata *ndp)
420 {
421 	struct componentname *cnp;
422 	struct pwd *pwd;
423 	struct vnode *dp;
424 	int error;
425 
426 	cnp = &ndp->ni_cnd;
427 	MPASS(*cnp->cn_pnbuf == '\0');
428 	MPASS((cnp->cn_flags & EMPTYPATH) != 0);
429 	MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
430 
431 	ndp->ni_resflags |= NIRES_EMPTYPATH;
432 	error = namei_setup(ndp, &dp, &pwd);
433 	if (error != 0) {
434 		goto errout;
435 	}
436 
437 	/*
438 	 * Usecount on dp already provided by namei_setup.
439 	 */
440 	ndp->ni_vp = dp;
441 	pwd_drop(pwd);
442 	NDVALIDATE(ndp);
443 	if ((cnp->cn_flags & LOCKLEAF) != 0) {
444 		VOP_LOCK(dp, (cnp->cn_flags & LOCKSHARED) != 0 ?
445 		    LK_SHARED : LK_EXCLUSIVE);
446 		if (VN_IS_DOOMED(dp)) {
447 			vput(dp);
448 			error = ENOENT;
449 			goto errout;
450 		}
451 	}
452 	SDT_PROBE4(vfs, namei, lookup, return, 0, ndp->ni_vp, false, ndp);
453 	return (0);
454 
455 errout:
456 	SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
457 	namei_cleanup_cnp(cnp);
458 	return (error);
459 }
460 
461 static int __noinline
462 namei_follow_link(struct nameidata *ndp)
463 {
464 	char *cp;
465 	struct iovec aiov;
466 	struct uio auio;
467 	struct componentname *cnp;
468 	struct thread *td;
469 	int error, linklen;
470 
471 	error = 0;
472 	cnp = &ndp->ni_cnd;
473 	td = curthread;
474 
475 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
476 		error = ELOOP;
477 		goto out;
478 	}
479 #ifdef MAC
480 	if ((cnp->cn_flags & NOMACCHECK) == 0) {
481 		error = mac_vnode_check_readlink(td->td_ucred, ndp->ni_vp);
482 		if (error != 0)
483 			goto out;
484 	}
485 #endif
486 	if (ndp->ni_pathlen > 1)
487 		cp = uma_zalloc(namei_zone, M_WAITOK);
488 	else
489 		cp = cnp->cn_pnbuf;
490 	aiov.iov_base = cp;
491 	aiov.iov_len = MAXPATHLEN;
492 	auio.uio_iov = &aiov;
493 	auio.uio_iovcnt = 1;
494 	auio.uio_offset = 0;
495 	auio.uio_rw = UIO_READ;
496 	auio.uio_segflg = UIO_SYSSPACE;
497 	auio.uio_td = td;
498 	auio.uio_resid = MAXPATHLEN;
499 	error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
500 	if (error != 0) {
501 		if (ndp->ni_pathlen > 1)
502 			uma_zfree(namei_zone, cp);
503 		goto out;
504 	}
505 	linklen = MAXPATHLEN - auio.uio_resid;
506 	if (linklen == 0) {
507 		if (ndp->ni_pathlen > 1)
508 			uma_zfree(namei_zone, cp);
509 		error = ENOENT;
510 		goto out;
511 	}
512 	if (linklen + ndp->ni_pathlen > MAXPATHLEN) {
513 		if (ndp->ni_pathlen > 1)
514 			uma_zfree(namei_zone, cp);
515 		error = ENAMETOOLONG;
516 		goto out;
517 	}
518 	if (ndp->ni_pathlen > 1) {
519 		bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
520 		uma_zfree(namei_zone, cnp->cn_pnbuf);
521 		cnp->cn_pnbuf = cp;
522 	} else
523 		cnp->cn_pnbuf[linklen] = '\0';
524 	ndp->ni_pathlen += linklen;
525 out:
526 	return (error);
527 }
528 
529 /*
530  * Convert a pathname into a pointer to a locked vnode.
531  *
532  * The FOLLOW flag is set when symbolic links are to be followed
533  * when they occur at the end of the name translation process.
534  * Symbolic links are always followed for all other pathname
535  * components other than the last.
536  *
537  * The segflg defines whether the name is to be copied from user
538  * space or kernel space.
539  *
540  * Overall outline of namei:
541  *
542  *	copy in name
543  *	get starting directory
544  *	while (!done && !error) {
545  *		call lookup to search path.
546  *		if symbolic link, massage name in buffer and continue
547  *	}
548  */
549 int
550 namei(struct nameidata *ndp)
551 {
552 	struct vnode *dp;	/* the directory we are searching */
553 	struct componentname *cnp;
554 	struct thread *td;
555 	struct pwd *pwd;
556 	int error;
557 	enum cache_fpl_status status;
558 
559 	cnp = &ndp->ni_cnd;
560 	td = curthread;
561 #ifdef INVARIANTS
562 	KASSERT((ndp->ni_debugflags & NAMEI_DBG_CALLED) == 0,
563 	    ("%s: repeated call to namei without NDREINIT", __func__));
564 	KASSERT(ndp->ni_debugflags == NAMEI_DBG_INITED,
565 	    ("%s: bad debugflags %d", __func__, ndp->ni_debugflags));
566 	ndp->ni_debugflags |= NAMEI_DBG_CALLED;
567 	if (ndp->ni_startdir != NULL)
568 		ndp->ni_debugflags |= NAMEI_DBG_HADSTARTDIR;
569 	if (cnp->cn_flags & FAILIFEXISTS) {
570 		KASSERT(cnp->cn_nameiop == CREATE,
571 		    ("%s: FAILIFEXISTS passed for op %d", __func__, cnp->cn_nameiop));
572 		/*
573 		 * The limitation below is to restrict hairy corner cases.
574 		 */
575 		KASSERT((cnp->cn_flags & (LOCKPARENT | LOCKLEAF)) == LOCKPARENT,
576 		    ("%s: FAILIFEXISTS must be passed with LOCKPARENT and without LOCKLEAF",
577 		    __func__));
578 	}
579 #endif
580 	ndp->ni_cnd.cn_cred = td->td_ucred;
581 	KASSERT(ndp->ni_resflags == 0, ("%s: garbage in ni_resflags: %x\n",
582 	    __func__, ndp->ni_resflags));
583 	KASSERT(cnp->cn_cred && td->td_proc, ("namei: bad cred/proc"));
584 	KASSERT((cnp->cn_flags & NAMEI_INTERNAL_FLAGS) == 0,
585 	    ("namei: unexpected flags: %" PRIx64 "\n",
586 	    cnp->cn_flags & NAMEI_INTERNAL_FLAGS));
587 	if (cnp->cn_flags & NOCACHE)
588 		KASSERT(cnp->cn_nameiop != LOOKUP,
589 		    ("%s: NOCACHE passed with LOOKUP", __func__));
590 	MPASS(ndp->ni_startdir == NULL || ndp->ni_startdir->v_type == VDIR ||
591 	    ndp->ni_startdir->v_type == VBAD);
592 
593 	ndp->ni_lcf = 0;
594 	ndp->ni_loopcnt = 0;
595 	ndp->ni_vp = NULL;
596 
597 	error = namei_getpath(ndp);
598 	if (__predict_false(error != 0)) {
599 		namei_cleanup_cnp(cnp);
600 		SDT_PROBE4(vfs, namei, lookup, return, error, NULL,
601 		    false, ndp);
602 		return (error);
603 	}
604 
605 	cnp->cn_nameptr = cnp->cn_pnbuf;
606 
607 #ifdef KTRACE
608 	if (KTRPOINT(td, KTR_NAMEI)) {
609 		ktrnamei(cnp->cn_pnbuf);
610 	}
611 #endif
612 	TSNAMEI(curthread->td_proc->p_pid, cnp->cn_pnbuf);
613 
614 	/*
615 	 * First try looking up the target without locking any vnodes.
616 	 *
617 	 * We may need to start from scratch or pick up where it left off.
618 	 */
619 	error = cache_fplookup(ndp, &status, &pwd);
620 	switch (status) {
621 	case CACHE_FPL_STATUS_UNSET:
622 		__assert_unreachable();
623 		break;
624 	case CACHE_FPL_STATUS_HANDLED:
625 		if (error == 0)
626 			NDVALIDATE(ndp);
627 		return (error);
628 	case CACHE_FPL_STATUS_PARTIAL:
629 		TAILQ_INIT(&ndp->ni_cap_tracker);
630 		dp = ndp->ni_startdir;
631 		break;
632 	case CACHE_FPL_STATUS_DESTROYED:
633 		ndp->ni_loopcnt = 0;
634 		error = namei_getpath(ndp);
635 		if (__predict_false(error != 0)) {
636 			namei_cleanup_cnp(cnp);
637 			return (error);
638 		}
639 		cnp->cn_nameptr = cnp->cn_pnbuf;
640 		/* FALLTHROUGH */
641 	case CACHE_FPL_STATUS_ABORTED:
642 		TAILQ_INIT(&ndp->ni_cap_tracker);
643 		MPASS(ndp->ni_lcf == 0);
644 		if (*cnp->cn_pnbuf == '\0') {
645 			if ((cnp->cn_flags & EMPTYPATH) != 0) {
646 				return (namei_emptypath(ndp));
647 			}
648 			namei_cleanup_cnp(cnp);
649 			SDT_PROBE4(vfs, namei, lookup, return, ENOENT, NULL,
650 			    false, ndp);
651 			return (ENOENT);
652 		}
653 		error = namei_setup(ndp, &dp, &pwd);
654 		if (error != 0) {
655 			namei_cleanup_cnp(cnp);
656 			return (error);
657 		}
658 		break;
659 	}
660 
661 	/*
662 	 * Locked lookup.
663 	 */
664 	for (;;) {
665 		ndp->ni_startdir = dp;
666 		error = vfs_lookup(ndp);
667 		if (error != 0)
668 			goto out;
669 
670 		/*
671 		 * If not a symbolic link, we're done.
672 		 */
673 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
674 			SDT_PROBE4(vfs, namei, lookup, return, error,
675 			    ndp->ni_vp, false, ndp);
676 			nameicap_cleanup(ndp);
677 			pwd_drop(pwd);
678 			NDVALIDATE(ndp);
679 			return (0);
680 		}
681 		error = namei_follow_link(ndp);
682 		if (error != 0)
683 			break;
684 		vput(ndp->ni_vp);
685 		dp = ndp->ni_dvp;
686 		/*
687 		 * Check if root directory should replace current directory.
688 		 */
689 		cnp->cn_nameptr = cnp->cn_pnbuf;
690 		if (*(cnp->cn_nameptr) == '/') {
691 			vrele(dp);
692 			error = namei_handle_root(ndp, &dp);
693 			if (error != 0)
694 				goto out;
695 		}
696 	}
697 	vput(ndp->ni_vp);
698 	ndp->ni_vp = NULL;
699 	vrele(ndp->ni_dvp);
700 out:
701 	MPASS(error != 0);
702 	SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
703 	namei_cleanup_cnp(cnp);
704 	nameicap_cleanup(ndp);
705 	pwd_drop(pwd);
706 	return (error);
707 }
708 
709 static int
710 compute_cn_lkflags(struct mount *mp, int lkflags, int cnflags)
711 {
712 
713 	if (mp == NULL || ((lkflags & LK_SHARED) &&
714 	    !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
715 		lkflags &= ~LK_SHARED;
716 		lkflags |= LK_EXCLUSIVE;
717 	}
718 	lkflags |= LK_NODDLKTREAT;
719 	return (lkflags);
720 }
721 
722 static __inline int
723 needs_exclusive_leaf(struct mount *mp, int flags)
724 {
725 
726 	/*
727 	 * Intermediate nodes can use shared locks, we only need to
728 	 * force an exclusive lock for leaf nodes.
729 	 */
730 	if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
731 		return (0);
732 
733 	/* Always use exclusive locks if LOCKSHARED isn't set. */
734 	if (!(flags & LOCKSHARED))
735 		return (1);
736 
737 	/*
738 	 * For lookups during open(), if the mount point supports
739 	 * extended shared operations, then use a shared lock for the
740 	 * leaf node, otherwise use an exclusive lock.
741 	 */
742 	if ((flags & ISOPEN) != 0)
743 		return (!MNT_EXTENDED_SHARED(mp));
744 
745 	/*
746 	 * Lookup requests outside of open() that specify LOCKSHARED
747 	 * only need a shared lock on the leaf vnode.
748 	 */
749 	return (0);
750 }
751 
752 /*
753  * Various filesystems expect to be able to copy a name component with length
754  * bounded by NAME_MAX into a directory entry buffer of size MAXNAMLEN.  Make
755  * sure that these are the same size.
756  */
757 _Static_assert(MAXNAMLEN == NAME_MAX,
758     "MAXNAMLEN and NAME_MAX have different values");
759 
760 static int __noinline
761 vfs_lookup_degenerate(struct nameidata *ndp, struct vnode *dp, int wantparent)
762 {
763 	struct componentname *cnp;
764 	struct mount *mp;
765 	int error;
766 
767 	cnp = &ndp->ni_cnd;
768 
769 	cnp->cn_flags |= ISLASTCN;
770 
771 	mp = atomic_load_ptr(&dp->v_mount);
772 	if (needs_exclusive_leaf(mp, cnp->cn_flags)) {
773 		cnp->cn_lkflags &= ~LK_SHARED;
774 		cnp->cn_lkflags |= LK_EXCLUSIVE;
775 	}
776 
777 	vn_lock(dp,
778 	    compute_cn_lkflags(mp, cnp->cn_lkflags | LK_RETRY,
779 	    cnp->cn_flags));
780 
781 	if (dp->v_type != VDIR) {
782 		error = ENOTDIR;
783 		goto bad;
784 	}
785 	if (cnp->cn_nameiop != LOOKUP) {
786 		error = EISDIR;
787 		goto bad;
788 	}
789 	if (wantparent) {
790 		ndp->ni_dvp = dp;
791 		VREF(dp);
792 	}
793 	ndp->ni_vp = dp;
794 	cnp->cn_namelen = 0;
795 
796 	if (cnp->cn_flags & AUDITVNODE1)
797 		AUDIT_ARG_VNODE1(dp);
798 	else if (cnp->cn_flags & AUDITVNODE2)
799 		AUDIT_ARG_VNODE2(dp);
800 
801 	if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
802 		VOP_UNLOCK(dp);
803 	return (0);
804 bad:
805 	VOP_UNLOCK(dp);
806 	return (error);
807 }
808 
809 /*
810  * FAILIFEXISTS handling.
811  *
812  * XXX namei called with LOCKPARENT but not LOCKLEAF has the strange
813  * behaviour of leaving the vnode unlocked if the target is the same
814  * vnode as the parent.
815  */
816 static int __noinline
817 vfs_lookup_failifexists(struct nameidata *ndp)
818 {
819 	struct componentname *cnp __diagused;
820 
821 	cnp = &ndp->ni_cnd;
822 
823 	MPASS((cnp->cn_flags & ISSYMLINK) == 0);
824 	if (ndp->ni_vp == ndp->ni_dvp)
825 		vrele(ndp->ni_dvp);
826 	else
827 		vput(ndp->ni_dvp);
828 	vrele(ndp->ni_vp);
829 	ndp->ni_dvp = NULL;
830 	ndp->ni_vp = NULL;
831 	NDFREE_PNBUF(ndp);
832 	return (EEXIST);
833 }
834 
835 /*
836  * Search a pathname.
837  * This is a very central and rather complicated routine.
838  *
839  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
840  * The starting directory is taken from ni_startdir. The pathname is
841  * descended until done, or a symbolic link is encountered. The variable
842  * ni_more is clear if the path is completed; it is set to one if a
843  * symbolic link needing interpretation is encountered.
844  *
845  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
846  * whether the name is to be looked up, created, renamed, or deleted.
847  * When CREATE, RENAME, or DELETE is specified, information usable in
848  * creating, renaming, or deleting a directory entry may be calculated.
849  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
850  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
851  * returned unlocked. Otherwise the parent directory is not returned. If
852  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
853  * the target is returned locked, otherwise it is returned unlocked.
854  * When creating or renaming and LOCKPARENT is specified, the target may not
855  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
856  *
857  * Overall outline of lookup:
858  *
859  * dirloop:
860  *	identify next component of name at ndp->ni_ptr
861  *	handle degenerate case where name is null string
862  *	if .. and crossing mount points and on mounted filesys, find parent
863  *	call VOP_LOOKUP routine for next component name
864  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
865  *	    component vnode returned in ni_vp (if it exists), locked.
866  *	if result vnode is mounted on and crossing mount points,
867  *	    find mounted on vnode
868  *	if more components of name, do next level at dirloop
869  *	return the answer in ni_vp, locked if LOCKLEAF set
870  *	    if LOCKPARENT set, return locked parent in ni_dvp
871  *	    if WANTPARENT set, return unlocked parent in ni_dvp
872  */
873 int
874 vfs_lookup(struct nameidata *ndp)
875 {
876 	char *cp;			/* pointer into pathname argument */
877 	char *prev_ni_next;		/* saved ndp->ni_next */
878 	char *nulchar;			/* location of '\0' in cn_pnbuf */
879 	char *lastchar;			/* location of the last character */
880 	struct vnode *dp = NULL;	/* the directory we are searching */
881 	struct vnode *tdp;		/* saved dp */
882 	struct mount *mp;		/* mount table entry */
883 	struct prison *pr;
884 	size_t prev_ni_pathlen;		/* saved ndp->ni_pathlen */
885 	int docache;			/* == 0 do not cache last component */
886 	int wantparent;			/* 1 => wantparent or lockparent flag */
887 	int rdonly;			/* lookup read-only flag bit */
888 	int error = 0;
889 	int dpunlocked = 0;		/* dp has already been unlocked */
890 	int relookup = 0;		/* do not consume the path component */
891 	struct componentname *cnp = &ndp->ni_cnd;
892 	int lkflags_save;
893 	int ni_dvp_unlocked;
894 	int crosslkflags;
895 	bool crosslock;
896 
897 	/*
898 	 * Setup: break out flag bits into variables.
899 	 */
900 	ni_dvp_unlocked = 0;
901 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
902 	KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
903 	    ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
904 	/*
905 	 * When set to zero, docache causes the last component of the
906 	 * pathname to be deleted from the cache and the full lookup
907 	 * of the name to be done (via VOP_CACHEDLOOKUP()). Often
908 	 * filesystems need some pre-computed values that are made
909 	 * during the full lookup, for instance UFS sets dp->i_offset.
910 	 *
911 	 * The docache variable is set to zero when requested by the
912 	 * NOCACHE flag and for all modifying operations except CREATE.
913 	 */
914 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
915 	if (cnp->cn_nameiop == DELETE ||
916 	    (wantparent && cnp->cn_nameiop != CREATE &&
917 	     cnp->cn_nameiop != LOOKUP))
918 		docache = 0;
919 	rdonly = cnp->cn_flags & RDONLY;
920 	cnp->cn_flags &= ~ISSYMLINK;
921 	ndp->ni_dvp = NULL;
922 
923 	cnp->cn_lkflags = LK_SHARED;
924 	dp = ndp->ni_startdir;
925 	ndp->ni_startdir = NULLVP;
926 
927 	/*
928 	 * Leading slashes, if any, are supposed to be skipped by the caller.
929 	 */
930 	MPASS(cnp->cn_nameptr[0] != '/');
931 
932 	/*
933 	 * Check for degenerate name (e.g. / or "") which is a way of talking
934 	 * about a directory, e.g. like "/." or ".".
935 	 */
936 	if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
937 		error = vfs_lookup_degenerate(ndp, dp, wantparent);
938 		if (error == 0)
939 			goto success_right_lock;
940 		goto bad_unlocked;
941 	}
942 
943 	/*
944 	 * Nul-out trailing slashes (e.g., "foo///" -> "foo").
945 	 *
946 	 * This must be done before VOP_LOOKUP() because some fs's don't know
947 	 * about trailing slashes.  Remember if there were trailing slashes to
948 	 * handle symlinks, existing non-directories and non-existing files
949 	 * that won't be directories specially later.
950 	 */
951 	MPASS(ndp->ni_pathlen >= 2);
952 	lastchar = &cnp->cn_nameptr[ndp->ni_pathlen - 2];
953 	if (*lastchar == '/') {
954 		while (lastchar >= cnp->cn_pnbuf) {
955 			*lastchar = '\0';
956 			lastchar--;
957 			ndp->ni_pathlen--;
958 			if (*lastchar != '/') {
959 				break;
960 			}
961 		}
962 		cnp->cn_flags |= TRAILINGSLASH;
963 	}
964 
965 	/*
966 	 * We use shared locks until we hit the parent of the last cn then
967 	 * we adjust based on the requesting flags.
968 	 */
969 	vn_lock(dp,
970 	    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY,
971 	    cnp->cn_flags));
972 
973 dirloop:
974 	/*
975 	 * Search a new directory.
976 	 *
977 	 * The last component of the filename is left accessible via
978 	 * cnp->cn_nameptr. It has to be freed with a call to NDFREE*.
979 	 *
980 	 * Store / as a temporary sentinel so that we only have one character
981 	 * to test for. Pathnames tend to be short so this should not be
982 	 * resulting in cache misses.
983 	 */
984 	nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
985 	KASSERT(*nulchar == '\0',
986 	    ("%s: expected nul at %p; string [%s]\n", __func__, nulchar,
987 	    cnp->cn_pnbuf));
988 	*nulchar = '/';
989 	for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
990 		KASSERT(*cp != '\0',
991 		    ("%s: encountered unexpected nul; string [%s]\n", __func__,
992 		    cnp->cn_nameptr));
993 		continue;
994 	}
995 	*nulchar = '\0';
996 	cnp->cn_namelen = cp - cnp->cn_nameptr;
997 	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
998 		error = ENAMETOOLONG;
999 		goto bad;
1000 	}
1001 #ifdef NAMEI_DIAGNOSTIC
1002 	{ char c = *cp;
1003 	*cp = '\0';
1004 	printf("{%s}: ", cnp->cn_nameptr);
1005 	*cp = c; }
1006 #endif
1007 	prev_ni_pathlen = ndp->ni_pathlen;
1008 	ndp->ni_pathlen -= cnp->cn_namelen;
1009 	KASSERT(ndp->ni_pathlen <= PATH_MAX,
1010 	    ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
1011 	prev_ni_next = ndp->ni_next;
1012 	ndp->ni_next = cp;
1013 
1014 	/*
1015 	 * Something else should be clearing this.
1016 	 */
1017 	cnp->cn_flags &= ~(ISDOTDOT|ISLASTCN);
1018 
1019 	cnp->cn_flags |= MAKEENTRY;
1020 	if (*cp == '\0' && docache == 0)
1021 		cnp->cn_flags &= ~MAKEENTRY;
1022 	if (cnp->cn_namelen == 2 &&
1023 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
1024 		cnp->cn_flags |= ISDOTDOT;
1025 	if (*ndp->ni_next == 0) {
1026 		cnp->cn_flags |= ISLASTCN;
1027 
1028 		if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
1029 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))) {
1030 			error = EINVAL;
1031 			goto bad;
1032 		}
1033 	}
1034 
1035 	nameicap_tracker_add(ndp, dp);
1036 
1037 	/*
1038 	 * Make sure degenerate names don't get here, their handling was
1039 	 * previously found in this spot.
1040 	 */
1041 	MPASS(cnp->cn_nameptr[0] != '\0');
1042 
1043 	/*
1044 	 * Handle "..": five special cases.
1045 	 * 0. If doing a capability lookup and lookup_cap_dotdot is
1046 	 *    disabled, return ENOTCAPABLE.
1047 	 * 1. Return an error if this is the last component of
1048 	 *    the name and the operation is DELETE or RENAME.
1049 	 * 2. If at root directory (e.g. after chroot)
1050 	 *    or at absolute root directory
1051 	 *    then ignore it so can't get out.
1052 	 * 3. If this vnode is the root of a mounted
1053 	 *    filesystem, then replace it with the
1054 	 *    vnode which was mounted on so we take the
1055 	 *    .. in the other filesystem.
1056 	 * 4. If the vnode is the top directory of
1057 	 *    the jail or chroot, don't let them out.
1058 	 * 5. If doing a capability lookup and lookup_cap_dotdot is
1059 	 *    enabled, return ENOTCAPABLE if the lookup would escape
1060 	 *    from the initial file descriptor directory.  Checks are
1061 	 *    done by ensuring that namei() already traversed the
1062 	 *    result of dotdot lookup.
1063 	 */
1064 	if (cnp->cn_flags & ISDOTDOT) {
1065 		if ((ndp->ni_lcf & (NI_LCF_STRICTRELATIVE | NI_LCF_CAP_DOTDOT))
1066 		    == NI_LCF_STRICTRELATIVE) {
1067 #ifdef KTRACE
1068 			if (KTRPOINT(curthread, KTR_CAPFAIL))
1069 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1070 #endif
1071 			error = ENOTCAPABLE;
1072 			goto bad;
1073 		}
1074 		if ((cnp->cn_flags & ISLASTCN) != 0 &&
1075 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1076 			error = EINVAL;
1077 			goto bad;
1078 		}
1079 		for (;;) {
1080 			for (pr = cnp->cn_cred->cr_prison; pr != NULL;
1081 			     pr = pr->pr_parent)
1082 				if (dp == pr->pr_root)
1083 					break;
1084 			if (dp == ndp->ni_rootdir ||
1085 			    dp == ndp->ni_topdir ||
1086 			    dp == rootvnode ||
1087 			    pr != NULL ||
1088 			    ((dp->v_vflag & VV_ROOT) != 0 &&
1089 			     (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
1090 				ndp->ni_dvp = dp;
1091 				ndp->ni_vp = dp;
1092 				VREF(dp);
1093 				goto nextname;
1094 			}
1095 			if ((dp->v_vflag & VV_ROOT) == 0)
1096 				break;
1097 			if (VN_IS_DOOMED(dp)) {	/* forced unmount */
1098 				error = ENOENT;
1099 				goto bad;
1100 			}
1101 			tdp = dp;
1102 			dp = dp->v_mount->mnt_vnodecovered;
1103 			VREF(dp);
1104 			vput(tdp);
1105 			vn_lock(dp,
1106 			    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
1107 			    LK_RETRY, ISDOTDOT));
1108 			error = nameicap_check_dotdot(ndp, dp);
1109 			if (error != 0) {
1110 #ifdef KTRACE
1111 				if (KTRPOINT(curthread, KTR_CAPFAIL))
1112 					ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1113 #endif
1114 				goto bad;
1115 			}
1116 		}
1117 	}
1118 
1119 	/*
1120 	 * We now have a segment name to search for, and a directory to search.
1121 	 */
1122 unionlookup:
1123 #ifdef MAC
1124 	error = mac_vnode_check_lookup(cnp->cn_cred, dp, cnp);
1125 	if (__predict_false(error))
1126 		goto bad;
1127 #endif
1128 	ndp->ni_dvp = dp;
1129 	ndp->ni_vp = NULL;
1130 	ASSERT_VOP_LOCKED(dp, "lookup");
1131 	/*
1132 	 * If we have a shared lock we may need to upgrade the lock for the
1133 	 * last operation.
1134 	 */
1135 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
1136 	    dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
1137 		vn_lock(dp, LK_UPGRADE|LK_RETRY);
1138 	if (VN_IS_DOOMED(dp)) {
1139 		error = ENOENT;
1140 		goto bad;
1141 	}
1142 	/*
1143 	 * If we're looking up the last component and we need an exclusive
1144 	 * lock, adjust our lkflags.
1145 	 */
1146 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
1147 		cnp->cn_lkflags = LK_EXCLUSIVE;
1148 #ifdef NAMEI_DIAGNOSTIC
1149 	vn_printf(dp, "lookup in ");
1150 #endif
1151 	lkflags_save = cnp->cn_lkflags;
1152 	cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags,
1153 	    cnp->cn_flags);
1154 	error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
1155 	cnp->cn_lkflags = lkflags_save;
1156 	if (error != 0) {
1157 		KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
1158 #ifdef NAMEI_DIAGNOSTIC
1159 		printf("not found\n");
1160 #endif
1161 		if ((error == ENOENT) &&
1162 		    (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
1163 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
1164 			tdp = dp;
1165 			dp = dp->v_mount->mnt_vnodecovered;
1166 			VREF(dp);
1167 			vput(tdp);
1168 			vn_lock(dp,
1169 			    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
1170 			    LK_RETRY, cnp->cn_flags));
1171 			nameicap_tracker_add(ndp, dp);
1172 			goto unionlookup;
1173 		}
1174 
1175 		if (error == ERELOOKUP) {
1176 			vref(dp);
1177 			ndp->ni_vp = dp;
1178 			error = 0;
1179 			relookup = 1;
1180 			goto good;
1181 		}
1182 
1183 		if (error != EJUSTRETURN)
1184 			goto bad;
1185 		/*
1186 		 * At this point, we know we're at the end of the
1187 		 * pathname.  If creating / renaming, we can consider
1188 		 * allowing the file or directory to be created / renamed,
1189 		 * provided we're not on a read-only filesystem.
1190 		 */
1191 		if (rdonly) {
1192 			error = EROFS;
1193 			goto bad;
1194 		}
1195 		/* trailing slash only allowed for directories */
1196 		if ((cnp->cn_flags & TRAILINGSLASH) &&
1197 		    !(cnp->cn_flags & WILLBEDIR)) {
1198 			error = ENOENT;
1199 			goto bad;
1200 		}
1201 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1202 			VOP_UNLOCK(dp);
1203 		/*
1204 		 * We return with ni_vp NULL to indicate that the entry
1205 		 * doesn't currently exist, leaving a pointer to the
1206 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1207 		 */
1208 		goto success;
1209 	}
1210 
1211 good:
1212 #ifdef NAMEI_DIAGNOSTIC
1213 	printf("found\n");
1214 #endif
1215 	dp = ndp->ni_vp;
1216 
1217 	/*
1218 	 * Check for symbolic link
1219 	 */
1220 	if ((dp->v_type == VLNK) &&
1221 	    ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
1222 	     *ndp->ni_next == '/')) {
1223 		cnp->cn_flags |= ISSYMLINK;
1224 		if (VN_IS_DOOMED(dp)) {
1225 			/*
1226 			 * We can't know whether the directory was mounted with
1227 			 * NOSYMFOLLOW, so we can't follow safely.
1228 			 */
1229 			error = ENOENT;
1230 			goto bad2;
1231 		}
1232 		if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
1233 			error = EACCES;
1234 			goto bad2;
1235 		}
1236 		/*
1237 		 * Symlink code always expects an unlocked dvp.
1238 		 */
1239 		if (ndp->ni_dvp != ndp->ni_vp) {
1240 			VOP_UNLOCK(ndp->ni_dvp);
1241 			ni_dvp_unlocked = 1;
1242 		}
1243 		goto success;
1244 	} else if ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0) {
1245 		if ((cnp->cn_flags & NOCROSSMOUNT) != 0)
1246 			goto nextname;
1247 	} else
1248 		goto nextname;
1249 
1250 	/*
1251 	 * Check to see if the vnode has been mounted on;
1252 	 * if so find the root of the mounted filesystem.
1253 	 */
1254 	do {
1255 		mp = dp->v_mountedhere;
1256 		KASSERT(mp != NULL,
1257 		    ("%s: NULL mountpoint for VIRF_MOUNTPOINT vnode", __func__));
1258 		crosslock = (dp->v_vflag & VV_CROSSLOCK) != 0;
1259 		crosslkflags = compute_cn_lkflags(mp, cnp->cn_lkflags,
1260 		    cnp->cn_flags);
1261 		if (__predict_false(crosslock)) {
1262 			/*
1263 			 * We are going to be holding the vnode lock, which
1264 			 * in this case is shared by the root vnode of the
1265 			 * filesystem mounted at mp, across the call to
1266 			 * VFS_ROOT().  Make the situation clear to the
1267 			 * filesystem by passing LK_CANRECURSE if the
1268 			 * lock is held exclusive, or by clearinng
1269 			 * LK_NODDLKTREAT to allow recursion on the shared
1270 			 * lock in the presence of an exclusive waiter.
1271 			 */
1272 			if (VOP_ISLOCKED(dp) == LK_EXCLUSIVE) {
1273 				crosslkflags &= ~LK_SHARED;
1274 				crosslkflags |= LK_EXCLUSIVE | LK_CANRECURSE;
1275 			} else if ((crosslkflags & LK_EXCLUSIVE) != 0) {
1276 				vn_lock(dp, LK_UPGRADE | LK_RETRY);
1277 				if (VN_IS_DOOMED(dp)) {
1278 					error = ENOENT;
1279 					goto bad2;
1280 				}
1281 			} else
1282 				crosslkflags &= ~LK_NODDLKTREAT;
1283 		}
1284 		if (vfs_busy(mp, 0) != 0)
1285 			continue;
1286 		if (__predict_true(!crosslock))
1287 			vput(dp);
1288 		if (dp != ndp->ni_dvp)
1289 			vput(ndp->ni_dvp);
1290 		else
1291 			vrele(ndp->ni_dvp);
1292 		vrefact(vp_crossmp);
1293 		ndp->ni_dvp = vp_crossmp;
1294 		error = VFS_ROOT(mp, crosslkflags, &tdp);
1295 		vfs_unbusy(mp);
1296 		if (__predict_false(crosslock))
1297 			vput(dp);
1298 		if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
1299 			panic("vp_crossmp exclusively locked or reclaimed");
1300 		if (error != 0) {
1301 			dpunlocked = 1;
1302 			goto bad2;
1303 		}
1304 		ndp->ni_vp = dp = tdp;
1305 	} while ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0);
1306 
1307 nextname:
1308 	/*
1309 	 * Not a symbolic link that we will follow.  Continue with the
1310 	 * next component if there is any; otherwise, we're done.
1311 	 */
1312 	KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1313 	    ("lookup: invalid path state."));
1314 	if (relookup) {
1315 		relookup = 0;
1316 		ndp->ni_pathlen = prev_ni_pathlen;
1317 		ndp->ni_next = prev_ni_next;
1318 		if (ndp->ni_dvp != dp)
1319 			vput(ndp->ni_dvp);
1320 		else
1321 			vrele(ndp->ni_dvp);
1322 		goto dirloop;
1323 	}
1324 	if (cnp->cn_flags & ISDOTDOT) {
1325 		error = nameicap_check_dotdot(ndp, ndp->ni_vp);
1326 		if (error != 0) {
1327 #ifdef KTRACE
1328 			if (KTRPOINT(curthread, KTR_CAPFAIL))
1329 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1330 #endif
1331 			goto bad2;
1332 		}
1333 	}
1334 	if (*ndp->ni_next == '/') {
1335 		cnp->cn_nameptr = ndp->ni_next;
1336 		while (*cnp->cn_nameptr == '/') {
1337 			cnp->cn_nameptr++;
1338 			ndp->ni_pathlen--;
1339 		}
1340 		if (ndp->ni_dvp != dp)
1341 			vput(ndp->ni_dvp);
1342 		else
1343 			vrele(ndp->ni_dvp);
1344 		goto dirloop;
1345 	}
1346 	/*
1347 	 * If we're processing a path with a trailing slash,
1348 	 * check that the end result is a directory.
1349 	 */
1350 	if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1351 		error = ENOTDIR;
1352 		goto bad2;
1353 	}
1354 	/*
1355 	 * Disallow directory write attempts on read-only filesystems.
1356 	 */
1357 	if (rdonly &&
1358 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1359 		error = EROFS;
1360 		goto bad2;
1361 	}
1362 	if (!wantparent) {
1363 		ni_dvp_unlocked = 2;
1364 		if (ndp->ni_dvp != dp)
1365 			vput(ndp->ni_dvp);
1366 		else
1367 			vrele(ndp->ni_dvp);
1368 	} else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1369 		VOP_UNLOCK(ndp->ni_dvp);
1370 		ni_dvp_unlocked = 1;
1371 	}
1372 
1373 	if (cnp->cn_flags & AUDITVNODE1)
1374 		AUDIT_ARG_VNODE1(dp);
1375 	else if (cnp->cn_flags & AUDITVNODE2)
1376 		AUDIT_ARG_VNODE2(dp);
1377 
1378 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1379 		VOP_UNLOCK(dp);
1380 success:
1381 	/*
1382 	 * FIXME: for lookups which only cross a mount point to fetch the
1383 	 * root vnode, ni_dvp will be set to vp_crossmp. This can be a problem
1384 	 * if either WANTPARENT or LOCKPARENT is set.
1385 	 */
1386 	/*
1387 	 * Because of shared lookup we may have the vnode shared locked, but
1388 	 * the caller may want it to be exclusively locked.
1389 	 */
1390 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1391 	    VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1392 		vn_lock(dp, LK_UPGRADE | LK_RETRY);
1393 		if (VN_IS_DOOMED(dp)) {
1394 			error = ENOENT;
1395 			goto bad2;
1396 		}
1397 	}
1398 success_right_lock:
1399 	if (ndp->ni_vp != NULL) {
1400 		if ((cnp->cn_flags & ISDOTDOT) == 0)
1401 			nameicap_tracker_add(ndp, ndp->ni_vp);
1402 		if ((cnp->cn_flags & (FAILIFEXISTS | ISSYMLINK)) == FAILIFEXISTS)
1403 			return (vfs_lookup_failifexists(ndp));
1404 	}
1405 	return (0);
1406 
1407 bad2:
1408 	if (ni_dvp_unlocked != 2) {
1409 		if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1410 			vput(ndp->ni_dvp);
1411 		else
1412 			vrele(ndp->ni_dvp);
1413 	}
1414 bad:
1415 	if (!dpunlocked)
1416 		vput(dp);
1417 bad_unlocked:
1418 	ndp->ni_vp = NULL;
1419 	return (error);
1420 }
1421 
1422 /*
1423  * relookup - lookup a path name component
1424  *    Used by lookup to re-acquire things.
1425  */
1426 int
1427 vfs_relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1428     bool refstart)
1429 {
1430 	struct vnode *dp = NULL;		/* the directory we are searching */
1431 	int rdonly;			/* lookup read-only flag bit */
1432 	int error = 0;
1433 
1434 	KASSERT(cnp->cn_flags & ISLASTCN,
1435 	    ("relookup: Not given last component."));
1436 	/*
1437 	 * Setup: break out flag bits into variables.
1438 	 */
1439 	KASSERT((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) != 0,
1440 	    ("relookup: parent not wanted"));
1441 	rdonly = cnp->cn_flags & RDONLY;
1442 	cnp->cn_flags &= ~ISSYMLINK;
1443 	dp = dvp;
1444 	cnp->cn_lkflags = LK_EXCLUSIVE;
1445 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1446 
1447 	/*
1448 	 * Search a new directory.
1449 	 *
1450 	 * See a comment in vfs_lookup for cnp->cn_nameptr.
1451 	 */
1452 #ifdef NAMEI_DIAGNOSTIC
1453 	printf("{%s}: ", cnp->cn_nameptr);
1454 #endif
1455 
1456 	/*
1457 	 * Check for "" which represents the root directory after slash
1458 	 * removal.
1459 	 */
1460 	if (cnp->cn_nameptr[0] == '\0') {
1461 		/*
1462 		 * Support only LOOKUP for "/" because lookup()
1463 		 * can't succeed for CREATE, DELETE and RENAME.
1464 		 */
1465 		KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1466 		KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1467 
1468 		if (!(cnp->cn_flags & LOCKLEAF))
1469 			VOP_UNLOCK(dp);
1470 		*vpp = dp;
1471 		/* XXX This should probably move to the top of function. */
1472 		if (refstart)
1473 			panic("lookup: SAVESTART");
1474 		return (0);
1475 	}
1476 
1477 	if (cnp->cn_flags & ISDOTDOT)
1478 		panic ("relookup: lookup on dot-dot");
1479 
1480 	/*
1481 	 * We now have a segment name to search for, and a directory to search.
1482 	 */
1483 #ifdef NAMEI_DIAGNOSTIC
1484 	vn_printf(dp, "search in ");
1485 #endif
1486 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1487 		KASSERT(*vpp == NULL, ("leaf should be empty"));
1488 		if (error != EJUSTRETURN)
1489 			goto bad;
1490 		/*
1491 		 * If creating and at end of pathname, then can consider
1492 		 * allowing file to be created.
1493 		 */
1494 		if (rdonly) {
1495 			error = EROFS;
1496 			goto bad;
1497 		}
1498 		/* ASSERT(dvp == ndp->ni_startdir) */
1499 		if (refstart)
1500 			VREF(dvp);
1501 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1502 			VOP_UNLOCK(dp);
1503 		/*
1504 		 * We return with ni_vp NULL to indicate that the entry
1505 		 * doesn't currently exist, leaving a pointer to the
1506 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1507 		 */
1508 		return (0);
1509 	}
1510 
1511 	dp = *vpp;
1512 
1513 	/*
1514 	 * Disallow directory write attempts on read-only filesystems.
1515 	 */
1516 	if (rdonly &&
1517 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1518 		if (dvp == dp)
1519 			vrele(dvp);
1520 		else
1521 			vput(dvp);
1522 		error = EROFS;
1523 		goto bad;
1524 	}
1525 	/*
1526 	 * Set the parent lock/ref state to the requested state.
1527 	 */
1528 	if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp)
1529 		VOP_UNLOCK(dvp);
1530 	/*
1531 	 * Check for symbolic link
1532 	 */
1533 	KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1534 	    ("relookup: symlink found.\n"));
1535 
1536 	/* ASSERT(dvp == ndp->ni_startdir) */
1537 	if (refstart)
1538 		VREF(dvp);
1539 
1540 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1541 		VOP_UNLOCK(dp);
1542 	return (0);
1543 bad:
1544 	vput(dp);
1545 	*vpp = NULL;
1546 	return (error);
1547 }
1548 
1549 #ifdef INVARIANTS
1550 /*
1551  * Validate the final state of ndp after the lookup.
1552  */
1553 static void
1554 NDVALIDATE_impl(struct nameidata *ndp, int line)
1555 {
1556 	struct componentname *cnp;
1557 
1558 	cnp = &ndp->ni_cnd;
1559 	if (cnp->cn_pnbuf == NULL)
1560 		panic("%s: got no buf! called from %d", __func__, line);
1561 }
1562 
1563 #endif
1564 
1565 /*
1566  * Determine if there is a suitable alternate filename under the specified
1567  * prefix for the specified path.  If the create flag is set, then the
1568  * alternate prefix will be used so long as the parent directory exists.
1569  * This is used by the various compatibility ABIs so that Linux binaries prefer
1570  * files under /compat/linux for example.  The chosen path (whether under
1571  * the prefix or under /) is returned in a kernel malloc'd buffer pointed
1572  * to by pathbuf.  The caller is responsible for free'ing the buffer from
1573  * the M_TEMP bucket if one is returned.
1574  */
1575 int
1576 kern_alternate_path(const char *prefix, const char *path, enum uio_seg pathseg,
1577     char **pathbuf, int create, int dirfd)
1578 {
1579 	struct nameidata nd, ndroot;
1580 	char *ptr, *buf, *cp;
1581 	size_t len, sz;
1582 	int error;
1583 
1584 	buf = (char *) malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1585 	*pathbuf = buf;
1586 
1587 	/* Copy the prefix into the new pathname as a starting point. */
1588 	len = strlcpy(buf, prefix, MAXPATHLEN);
1589 	if (len >= MAXPATHLEN) {
1590 		*pathbuf = NULL;
1591 		free(buf, M_TEMP);
1592 		return (EINVAL);
1593 	}
1594 	sz = MAXPATHLEN - len;
1595 	ptr = buf + len;
1596 
1597 	/* Append the filename to the prefix. */
1598 	if (pathseg == UIO_SYSSPACE)
1599 		error = copystr(path, ptr, sz, &len);
1600 	else
1601 		error = copyinstr(path, ptr, sz, &len);
1602 
1603 	if (error) {
1604 		*pathbuf = NULL;
1605 		free(buf, M_TEMP);
1606 		return (error);
1607 	}
1608 
1609 	/* Only use a prefix with absolute pathnames. */
1610 	if (*ptr != '/') {
1611 		error = EINVAL;
1612 		goto keeporig;
1613 	}
1614 
1615 	if (dirfd != AT_FDCWD) {
1616 		/*
1617 		 * We want the original because the "prefix" is
1618 		 * included in the already opened dirfd.
1619 		 */
1620 		bcopy(ptr, buf, len);
1621 		return (0);
1622 	}
1623 
1624 	/*
1625 	 * We know that there is a / somewhere in this pathname.
1626 	 * Search backwards for it, to find the file's parent dir
1627 	 * to see if it exists in the alternate tree. If it does,
1628 	 * and we want to create a file (cflag is set). We don't
1629 	 * need to worry about the root comparison in this case.
1630 	 */
1631 
1632 	if (create) {
1633 		for (cp = &ptr[len] - 1; *cp != '/'; cp--);
1634 		*cp = '\0';
1635 
1636 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, buf);
1637 		error = namei(&nd);
1638 		*cp = '/';
1639 		if (error != 0)
1640 			goto keeporig;
1641 	} else {
1642 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, buf);
1643 
1644 		error = namei(&nd);
1645 		if (error != 0)
1646 			goto keeporig;
1647 
1648 		/*
1649 		 * We now compare the vnode of the prefix to the one
1650 		 * vnode asked. If they resolve to be the same, then we
1651 		 * ignore the match so that the real root gets used.
1652 		 * This avoids the problem of traversing "../.." to find the
1653 		 * root directory and never finding it, because "/" resolves
1654 		 * to the emulation root directory. This is expensive :-(
1655 		 */
1656 		NDINIT(&ndroot, LOOKUP, FOLLOW, UIO_SYSSPACE, prefix);
1657 
1658 		/* We shouldn't ever get an error from this namei(). */
1659 		error = namei(&ndroot);
1660 		if (error == 0) {
1661 			if (nd.ni_vp == ndroot.ni_vp)
1662 				error = ENOENT;
1663 
1664 			NDFREE_PNBUF(&ndroot);
1665 			vrele(ndroot.ni_vp);
1666 		}
1667 	}
1668 
1669 	NDFREE_PNBUF(&nd);
1670 	vrele(nd.ni_vp);
1671 
1672 keeporig:
1673 	/* If there was an error, use the original path name. */
1674 	if (error)
1675 		bcopy(ptr, buf, len);
1676 	return (error);
1677 }
1678