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