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