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