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