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