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