xref: /freebsd/sys/kern/vfs_lookup.c (revision be092bcde96bdcfde9013d60e442cca023bfbd1b)
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 enforce_lkflags(struct mount *mp, int lkflags)
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, enforce_lkflags(mp, cnp->cn_lkflags | LK_RETRY));
819 
820 	if (dp->v_type != VDIR) {
821 		error = ENOTDIR;
822 		goto bad;
823 	}
824 	if (cnp->cn_nameiop != LOOKUP) {
825 		error = EISDIR;
826 		goto bad;
827 	}
828 	if (wantparent) {
829 		ndp->ni_dvp = dp;
830 		VREF(dp);
831 	}
832 	ndp->ni_vp = dp;
833 	cnp->cn_namelen = 0;
834 
835 	if (cnp->cn_flags & AUDITVNODE1)
836 		AUDIT_ARG_VNODE1(dp);
837 	else if (cnp->cn_flags & AUDITVNODE2)
838 		AUDIT_ARG_VNODE2(dp);
839 
840 	if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
841 		VOP_UNLOCK(dp);
842 	return (0);
843 bad:
844 	VOP_UNLOCK(dp);
845 	return (error);
846 }
847 
848 /*
849  * FAILIFEXISTS handling.
850  *
851  * XXX namei called with LOCKPARENT but not LOCKLEAF has the strange
852  * behaviour of leaving the vnode unlocked if the target is the same
853  * vnode as the parent.
854  */
855 static int __noinline
856 vfs_lookup_failifexists(struct nameidata *ndp)
857 {
858 	struct componentname *cnp __diagused;
859 
860 	cnp = &ndp->ni_cnd;
861 
862 	MPASS((cnp->cn_flags & ISSYMLINK) == 0);
863 	if (ndp->ni_vp == ndp->ni_dvp)
864 		vrele(ndp->ni_dvp);
865 	else
866 		vput(ndp->ni_dvp);
867 	vrele(ndp->ni_vp);
868 	ndp->ni_dvp = NULL;
869 	ndp->ni_vp = NULL;
870 	NDFREE_PNBUF(ndp);
871 	return (EEXIST);
872 }
873 
874 /*
875  * Search a pathname.
876  * This is a very central and rather complicated routine.
877  *
878  * The pathname is pointed to by cn_nameptr and is of length ni_pathlen.
879  * The starting directory is taken from ni_startdir. The pathname is
880  * descended until done, or a symbolic link is encountered. The cn_flags
881  * has ISLASTCN or'ed if the path is completed or ISSYMLINK or'ed if a
882  * symbolic link needing interpretation is encountered.
883  *
884  * The cn_nameiop is LOOKUP, CREATE, RENAME, or DELETE depending on
885  * whether the name is to be looked up, created, renamed, or deleted.
886  * When CREATE, RENAME, or DELETE is specified, information usable in
887  * creating, renaming, or deleting a directory entry may be calculated.
888  * If cn_flags has LOCKPARENT or'ed into it, the parent directory is returned
889  * locked. If it has WANTPARENT or'ed into it, the parent directory is
890  * returned unlocked. Otherwise the parent directory is not returned. If
891  * the target of the pathname exists and LOCKLEAF is or'ed into the cn_flags
892  * the target is returned locked, otherwise it is returned unlocked.
893  *
894  * Overall outline of lookup:
895  *
896  *	handle degenerate case where name is null string
897  *
898  * dirloop:
899  *	identify next component of name at ndp->ni_cnd.cn_nameptr
900  *	handle .. special cases related to capabilities, chroot, jail
901  *	if .. and crossing mount points and on mounted filesys, find parent
902  *	call VOP_LOOKUP routine for next component name
903  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
904  *	    component vnode returned in ni_vp (if it exists), locked.
905  *	if result vnode is mounted on and crossing mount points,
906  *	    find mounted on vnode
907  *	if more components of name, do next level at dirloop
908  *	if VOP_LOOKUP returns ERELOOKUP, repeat the same level at dirloop
909  *	return the answer in ni_vp, locked if LOCKLEAF set
910  *	    if LOCKPARENT set, return locked parent in ni_dvp
911  *	    if WANTPARENT set, return unlocked parent in ni_dvp
912  */
913 int
914 vfs_lookup(struct nameidata *ndp)
915 {
916 	char *cp;			/* pointer into pathname argument */
917 	char *prev_ni_next;		/* saved ndp->ni_next */
918 	char *nulchar;			/* location of '\0' in cn_pnbuf */
919 	char *lastchar;			/* location of the last character */
920 	struct vnode *dp = NULL;	/* the directory we are searching */
921 	struct vnode *tdp;		/* saved dp */
922 	struct mount *mp;		/* mount table entry */
923 	struct prison *pr;
924 	size_t prev_ni_pathlen;		/* saved ndp->ni_pathlen */
925 	int docache;			/* == 0 do not cache last component */
926 	int wantparent;			/* 1 => wantparent or lockparent flag */
927 	int rdonly;			/* lookup read-only flag bit */
928 	int error = 0;
929 	int relookup = 0;		/* do not consume the path component */
930 	struct componentname *cnp = &ndp->ni_cnd;
931 	int lkflags_save;
932 	int ni_dvp_unlocked;
933 	int crosslkflags;
934 	bool crosslock;
935 
936 	/*
937 	 * Setup: break out flag bits into variables.
938 	 */
939 	ni_dvp_unlocked = 0;
940 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
941 	KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
942 	    ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
943 	/*
944 	 * When set to zero, docache causes the last component of the
945 	 * pathname to be deleted from the cache and the full lookup
946 	 * of the name to be done (via VOP_CACHEDLOOKUP()). Often
947 	 * filesystems need some pre-computed values that are made
948 	 * during the full lookup, for instance UFS sets dp->i_offset.
949 	 *
950 	 * The docache variable is set to zero when requested by the
951 	 * NOCACHE flag and for all modifying operations except CREATE.
952 	 */
953 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
954 	if (cnp->cn_nameiop == DELETE ||
955 	    (wantparent && cnp->cn_nameiop != CREATE &&
956 	     cnp->cn_nameiop != LOOKUP))
957 		docache = 0;
958 	rdonly = cnp->cn_flags & RDONLY;
959 	cnp->cn_flags &= ~ISSYMLINK;
960 	ndp->ni_dvp = NULL;
961 
962 	cnp->cn_lkflags = LK_SHARED;
963 	dp = ndp->ni_startdir;
964 	ndp->ni_startdir = NULLVP;
965 
966 	/*
967 	 * Leading slashes, if any, are supposed to be skipped by the caller.
968 	 */
969 	MPASS(cnp->cn_nameptr[0] != '/');
970 
971 	/*
972 	 * Check for degenerate name (e.g. / or "") which is a way of talking
973 	 * about a directory, e.g. like "/." or ".".
974 	 */
975 	if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
976 		error = vfs_lookup_degenerate(ndp, dp, wantparent);
977 		if (error == 0)
978 			goto success_right_lock;
979 		goto bad_unlocked;
980 	}
981 
982 	/*
983 	 * Nul-out trailing slashes (e.g., "foo///" -> "foo").
984 	 *
985 	 * This must be done before VOP_LOOKUP() because some fs's don't know
986 	 * about trailing slashes.  Remember if there were trailing slashes to
987 	 * handle symlinks, existing non-directories and non-existing files
988 	 * that won't be directories specially later.
989 	 */
990 	MPASS(ndp->ni_pathlen >= 2);
991 	lastchar = &cnp->cn_nameptr[ndp->ni_pathlen - 2];
992 	if (*lastchar == '/') {
993 		while (lastchar >= cnp->cn_pnbuf) {
994 			*lastchar = '\0';
995 			lastchar--;
996 			ndp->ni_pathlen--;
997 			if (*lastchar != '/') {
998 				break;
999 			}
1000 		}
1001 		cnp->cn_flags |= TRAILINGSLASH;
1002 	}
1003 
1004 	/*
1005 	 * We use shared locks until we hit the parent of the last cn then
1006 	 * we adjust based on the requesting flags.
1007 	 */
1008 	vn_lock(dp,
1009 	    enforce_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY));
1010 
1011 dirloop:
1012 	/*
1013 	 * Search a new directory.
1014 	 *
1015 	 * The last component of the filename is left accessible via
1016 	 * cnp->cn_nameptr. It has to be freed with a call to NDFREE*.
1017 	 *
1018 	 * Store / as a temporary sentinel so that we only have one character
1019 	 * to test for. Pathnames tend to be short so this should not be
1020 	 * resulting in cache misses.
1021 	 */
1022 	nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
1023 	KASSERT(*nulchar == '\0',
1024 	    ("%s: expected nul at %p; string [%s]\n", __func__, nulchar,
1025 	    cnp->cn_pnbuf));
1026 	*nulchar = '/';
1027 	for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
1028 		KASSERT(*cp != '\0',
1029 		    ("%s: encountered unexpected nul; string [%s]\n", __func__,
1030 		    cnp->cn_nameptr));
1031 		continue;
1032 	}
1033 	*nulchar = '\0';
1034 	cnp->cn_namelen = cp - cnp->cn_nameptr;
1035 	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
1036 		error = ENAMETOOLONG;
1037 		goto bad;
1038 	}
1039 #ifdef NAMEI_DIAGNOSTIC
1040 	{ char c = *cp;
1041 	*cp = '\0';
1042 	printf("{%s}: ", cnp->cn_nameptr);
1043 	*cp = c; }
1044 #endif
1045 	prev_ni_pathlen = ndp->ni_pathlen;
1046 	ndp->ni_pathlen -= cnp->cn_namelen;
1047 	KASSERT(ndp->ni_pathlen <= PATH_MAX,
1048 	    ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
1049 	prev_ni_next = ndp->ni_next;
1050 	ndp->ni_next = cp;
1051 
1052 	/*
1053 	 * Something else should be clearing this.
1054 	 */
1055 	cnp->cn_flags &= ~(ISDOTDOT|ISLASTCN);
1056 
1057 	cnp->cn_flags |= MAKEENTRY;
1058 	if (*cp == '\0' && docache == 0)
1059 		cnp->cn_flags &= ~MAKEENTRY;
1060 	if (cnp->cn_namelen == 2 &&
1061 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
1062 		cnp->cn_flags |= ISDOTDOT;
1063 	if (*ndp->ni_next == 0) {
1064 		cnp->cn_flags |= ISLASTCN;
1065 
1066 		if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
1067 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))) {
1068 			error = EINVAL;
1069 			goto bad;
1070 		}
1071 	}
1072 
1073 	nameicap_tracker_add(ndp, dp);
1074 
1075 	/*
1076 	 * Make sure degenerate names don't get here, their handling was
1077 	 * previously found in this spot.
1078 	 */
1079 	MPASS(cnp->cn_nameptr[0] != '\0');
1080 
1081 	/*
1082 	 * Handle "..": five special cases.
1083 	 * 0. If doing a capability lookup and lookup_cap_dotdot is
1084 	 *    disabled, return ENOTCAPABLE.
1085 	 * 1. Return an error if this is the last component of
1086 	 *    the name and the operation is DELETE or RENAME.
1087 	 * 2. If at root directory (e.g. after chroot)
1088 	 *    or at absolute root directory
1089 	 *    then ignore it so can't get out.
1090 	 * 3. If this vnode is the root of a mounted
1091 	 *    filesystem, then replace it with the
1092 	 *    vnode which was mounted on so we take the
1093 	 *    .. in the other filesystem.
1094 	 * 4. If the vnode is the top directory of
1095 	 *    the jail or chroot, don't let them out.
1096 	 * 5. If doing a capability lookup and lookup_cap_dotdot is
1097 	 *    enabled, return ENOTCAPABLE if the lookup would escape
1098 	 *    from the initial file descriptor directory.  Checks are
1099 	 *    done by ensuring that namei() already traversed the
1100 	 *    result of dotdot lookup.
1101 	 */
1102 	if (cnp->cn_flags & ISDOTDOT) {
1103 		if ((ndp->ni_lcf & (NI_LCF_STRICTRELATIVE | NI_LCF_CAP_DOTDOT))
1104 		    == NI_LCF_STRICTRELATIVE) {
1105 #ifdef KTRACE
1106 			if (KTRPOINT(curthread, KTR_CAPFAIL))
1107 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1108 #endif
1109 			error = ENOTCAPABLE;
1110 			goto bad;
1111 		}
1112 		if ((cnp->cn_flags & ISLASTCN) != 0 &&
1113 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1114 			error = EINVAL;
1115 			goto bad;
1116 		}
1117 		for (;;) {
1118 			for (pr = cnp->cn_cred->cr_prison; pr != NULL;
1119 			     pr = pr->pr_parent)
1120 				if (dp == pr->pr_root)
1121 					break;
1122 			bool isroot = dp == ndp->ni_rootdir ||
1123 			    dp == ndp->ni_topdir || dp == rootvnode ||
1124 			    pr != NULL;
1125 			if (isroot && (ndp->ni_lcf &
1126 			    NI_LCF_STRICTRELATIVE) != 0) {
1127 				error = ENOTCAPABLE;
1128 				goto capdotdot;
1129 			}
1130 			if (isroot || ((dp->v_vflag & VV_ROOT) != 0 &&
1131 			    (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
1132 				ndp->ni_dvp = dp;
1133 				ndp->ni_vp = dp;
1134 				VREF(dp);
1135 				goto nextname;
1136 			}
1137 			if ((dp->v_vflag & VV_ROOT) == 0)
1138 				break;
1139 			if (VN_IS_DOOMED(dp)) {	/* forced unmount */
1140 				error = ENOENT;
1141 				goto bad;
1142 			}
1143 			tdp = dp;
1144 			dp = dp->v_mount->mnt_vnodecovered;
1145 			VREF(dp);
1146 			vput(tdp);
1147 			vn_lock(dp,
1148 			    enforce_lkflags(dp->v_mount, cnp->cn_lkflags |
1149 			    LK_RETRY));
1150 			error = nameicap_check_dotdot(ndp, dp);
1151 			if (error != 0) {
1152 capdotdot:
1153 #ifdef KTRACE
1154 				if (KTRPOINT(curthread, KTR_CAPFAIL))
1155 					ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1156 #endif
1157 				goto bad;
1158 			}
1159 		}
1160 	}
1161 
1162 	/*
1163 	 * We now have a segment name to search for, and a directory to search.
1164 	 */
1165 unionlookup:
1166 #ifdef MAC
1167 	error = mac_vnode_check_lookup(cnp->cn_cred, dp, cnp);
1168 	if (__predict_false(error))
1169 		goto bad;
1170 #endif
1171 	ndp->ni_dvp = dp;
1172 	ndp->ni_vp = NULL;
1173 	ASSERT_VOP_LOCKED(dp, "lookup");
1174 	/*
1175 	 * If we have a shared lock we may need to upgrade the lock for the
1176 	 * last operation.
1177 	 */
1178 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
1179 	    dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
1180 		vn_lock(dp, LK_UPGRADE|LK_RETRY);
1181 	if (VN_IS_DOOMED(dp)) {
1182 		error = ENOENT;
1183 		goto bad;
1184 	}
1185 	/*
1186 	 * If we're looking up the last component and we need an exclusive
1187 	 * lock, adjust our lkflags.
1188 	 */
1189 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
1190 		cnp->cn_lkflags = LK_EXCLUSIVE;
1191 #ifdef NAMEI_DIAGNOSTIC
1192 	vn_printf(dp, "lookup in ");
1193 #endif
1194 	lkflags_save = cnp->cn_lkflags;
1195 	cnp->cn_lkflags = enforce_lkflags(dp->v_mount, cnp->cn_lkflags);
1196 	error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
1197 	cnp->cn_lkflags = lkflags_save;
1198 	if (error != 0) {
1199 		KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
1200 #ifdef NAMEI_DIAGNOSTIC
1201 		printf("not found\n");
1202 #endif
1203 		if ((error == ENOENT) &&
1204 		    (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
1205 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
1206 			tdp = dp;
1207 			dp = dp->v_mount->mnt_vnodecovered;
1208 			VREF(dp);
1209 			vput(tdp);
1210 			vn_lock(dp,
1211 			    enforce_lkflags(dp->v_mount, cnp->cn_lkflags |
1212 			    LK_RETRY));
1213 			nameicap_tracker_add(ndp, dp);
1214 			goto unionlookup;
1215 		}
1216 
1217 		if (error == ERELOOKUP) {
1218 			vref(dp);
1219 			ndp->ni_vp = dp;
1220 			error = 0;
1221 			relookup = 1;
1222 			goto good;
1223 		}
1224 
1225 		if (error != EJUSTRETURN)
1226 			goto bad;
1227 		/*
1228 		 * At this point, we know we're at the end of the
1229 		 * pathname.  If creating / renaming, we can consider
1230 		 * allowing the file or directory to be created / renamed,
1231 		 * provided we're not on a read-only filesystem.
1232 		 */
1233 		if (rdonly) {
1234 			error = EROFS;
1235 			goto bad;
1236 		}
1237 		/* trailing slash only allowed for directories */
1238 		if ((cnp->cn_flags & TRAILINGSLASH) &&
1239 		    !(cnp->cn_flags & WILLBEDIR)) {
1240 			error = ENOENT;
1241 			goto bad;
1242 		}
1243 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1244 			VOP_UNLOCK(dp);
1245 		/*
1246 		 * We return with ni_vp NULL to indicate that the entry
1247 		 * doesn't currently exist, leaving a pointer to the
1248 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1249 		 */
1250 		goto success;
1251 	}
1252 
1253 good:
1254 #ifdef NAMEI_DIAGNOSTIC
1255 	printf("found\n");
1256 #endif
1257 	dp = ndp->ni_vp;
1258 
1259 	/*
1260 	 * Check for symbolic link
1261 	 */
1262 	if ((dp->v_type == VLNK) &&
1263 	    ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
1264 	     *ndp->ni_next == '/')) {
1265 		cnp->cn_flags |= ISSYMLINK;
1266 		if (VN_IS_DOOMED(dp)) {
1267 			/*
1268 			 * We can't know whether the directory was mounted with
1269 			 * NOSYMFOLLOW, so we can't follow safely.
1270 			 */
1271 			error = ENOENT;
1272 			goto bad2;
1273 		}
1274 		if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
1275 			error = EACCES;
1276 			goto bad2;
1277 		}
1278 		/*
1279 		 * Symlink code always expects an unlocked dvp.
1280 		 */
1281 		if (ndp->ni_dvp != ndp->ni_vp) {
1282 			VOP_UNLOCK(ndp->ni_dvp);
1283 			ni_dvp_unlocked = 1;
1284 		}
1285 		goto success;
1286 	} else if ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0) {
1287 		if ((cnp->cn_flags & NOCROSSMOUNT) != 0)
1288 			goto nextname;
1289 	} else
1290 		goto nextname;
1291 
1292 	/*
1293 	 * Check to see if the vnode has been mounted on;
1294 	 * if so find the root of the mounted filesystem.
1295 	 */
1296 	do {
1297 		mp = dp->v_mountedhere;
1298 		KASSERT(mp != NULL,
1299 		    ("%s: NULL mountpoint for VIRF_MOUNTPOINT vnode", __func__));
1300 		crosslock = (dp->v_vflag & VV_CROSSLOCK) != 0;
1301 		crosslkflags = enforce_lkflags(mp, cnp->cn_lkflags);
1302 		if (__predict_false(crosslock)) {
1303 			/*
1304 			 * We are going to be holding the vnode lock, which
1305 			 * in this case is shared by the root vnode of the
1306 			 * filesystem mounted at mp, across the call to
1307 			 * VFS_ROOT().  Make the situation clear to the
1308 			 * filesystem by passing LK_CANRECURSE if the
1309 			 * lock is held exclusive, or by clearinng
1310 			 * LK_NODDLKTREAT to allow recursion on the shared
1311 			 * lock in the presence of an exclusive waiter.
1312 			 */
1313 			if (VOP_ISLOCKED(dp) == LK_EXCLUSIVE) {
1314 				crosslkflags &= ~LK_SHARED;
1315 				crosslkflags |= LK_EXCLUSIVE | LK_CANRECURSE;
1316 			} else if ((crosslkflags & LK_EXCLUSIVE) != 0) {
1317 				vn_lock(dp, LK_UPGRADE | LK_RETRY);
1318 				if (VN_IS_DOOMED(dp)) {
1319 					error = ENOENT;
1320 					goto bad2;
1321 				}
1322 				if (dp->v_mountedhere != mp) {
1323 					continue;
1324 				}
1325 			} else
1326 				crosslkflags &= ~LK_NODDLKTREAT;
1327 		}
1328 		if (vfs_busy(mp, 0) != 0)
1329 			continue;
1330 		if (__predict_true(!crosslock))
1331 			vput(dp);
1332 		if (dp != ndp->ni_dvp)
1333 			vput(ndp->ni_dvp);
1334 		else
1335 			vrele(ndp->ni_dvp);
1336 		vrefact(vp_crossmp);
1337 		ndp->ni_dvp = vp_crossmp;
1338 		error = VFS_ROOT(mp, crosslkflags, &tdp);
1339 		vfs_unbusy(mp);
1340 		if (__predict_false(crosslock))
1341 			vput(dp);
1342 		if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
1343 			panic("vp_crossmp exclusively locked or reclaimed");
1344 		if (error != 0)
1345 			goto bad_unlocked;
1346 		ndp->ni_vp = dp = tdp;
1347 	} while ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0);
1348 
1349 nextname:
1350 	/*
1351 	 * Not a symbolic link that we will follow.  Continue with the
1352 	 * next component if there is any; otherwise, we're done.
1353 	 */
1354 	KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1355 	    ("lookup: invalid path state."));
1356 	if (relookup) {
1357 		relookup = 0;
1358 		ndp->ni_pathlen = prev_ni_pathlen;
1359 		ndp->ni_next = prev_ni_next;
1360 		if (ndp->ni_dvp != dp)
1361 			vput(ndp->ni_dvp);
1362 		else
1363 			vrele(ndp->ni_dvp);
1364 		goto dirloop;
1365 	}
1366 	if (cnp->cn_flags & ISDOTDOT) {
1367 		error = nameicap_check_dotdot(ndp, ndp->ni_vp);
1368 		if (error != 0) {
1369 #ifdef KTRACE
1370 			if (KTRPOINT(curthread, KTR_CAPFAIL))
1371 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1372 #endif
1373 			goto bad2;
1374 		}
1375 	}
1376 	if (*ndp->ni_next == '/') {
1377 		cnp->cn_nameptr = ndp->ni_next;
1378 		while (*cnp->cn_nameptr == '/') {
1379 			cnp->cn_nameptr++;
1380 			ndp->ni_pathlen--;
1381 		}
1382 		if (ndp->ni_dvp != dp)
1383 			vput(ndp->ni_dvp);
1384 		else
1385 			vrele(ndp->ni_dvp);
1386 		goto dirloop;
1387 	}
1388 	/*
1389 	 * If we're processing a path with a trailing slash,
1390 	 * check that the end result is a directory.
1391 	 */
1392 	if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1393 		error = ENOTDIR;
1394 		goto bad2;
1395 	}
1396 	/*
1397 	 * Disallow directory write attempts on read-only filesystems.
1398 	 */
1399 	if (rdonly &&
1400 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1401 		error = EROFS;
1402 		goto bad2;
1403 	}
1404 	if (!wantparent) {
1405 		ni_dvp_unlocked = 2;
1406 		if (ndp->ni_dvp != dp)
1407 			vput(ndp->ni_dvp);
1408 		else
1409 			vrele(ndp->ni_dvp);
1410 	} else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1411 		VOP_UNLOCK(ndp->ni_dvp);
1412 		ni_dvp_unlocked = 1;
1413 	}
1414 
1415 	if (cnp->cn_flags & AUDITVNODE1)
1416 		AUDIT_ARG_VNODE1(dp);
1417 	else if (cnp->cn_flags & AUDITVNODE2)
1418 		AUDIT_ARG_VNODE2(dp);
1419 
1420 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1421 		VOP_UNLOCK(dp);
1422 success:
1423 	/*
1424 	 * FIXME: for lookups which only cross a mount point to fetch the
1425 	 * root vnode, ni_dvp will be set to vp_crossmp. This can be a problem
1426 	 * if either WANTPARENT or LOCKPARENT is set.
1427 	 */
1428 	/*
1429 	 * Because of shared lookup we may have the vnode shared locked, but
1430 	 * the caller may want it to be exclusively locked.
1431 	 */
1432 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1433 	    VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1434 		vn_lock(dp, LK_UPGRADE | LK_RETRY);
1435 		if (VN_IS_DOOMED(dp)) {
1436 			error = ENOENT;
1437 			goto bad2;
1438 		}
1439 	}
1440 success_right_lock:
1441 	if (ndp->ni_vp != NULL) {
1442 		if ((cnp->cn_flags & ISDOTDOT) == 0)
1443 			nameicap_tracker_add(ndp, ndp->ni_vp);
1444 		if ((cnp->cn_flags & (FAILIFEXISTS | ISSYMLINK)) == FAILIFEXISTS)
1445 			return (vfs_lookup_failifexists(ndp));
1446 	}
1447 	return (0);
1448 
1449 bad2:
1450 	if (ni_dvp_unlocked != 2) {
1451 		if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1452 			vput(ndp->ni_dvp);
1453 		else
1454 			vrele(ndp->ni_dvp);
1455 	}
1456 bad:
1457 	vput(dp);
1458 bad_unlocked:
1459 	ndp->ni_vp = NULL;
1460 	return (error);
1461 }
1462 
1463 /*
1464  * relookup - lookup a path name component
1465  *    Used by lookup to re-acquire things.
1466  */
1467 int
1468 vfs_relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1469     bool refstart)
1470 {
1471 	struct vnode *dp = NULL;		/* the directory we are searching */
1472 	int rdonly;			/* lookup read-only flag bit */
1473 	int error = 0;
1474 
1475 	KASSERT(cnp->cn_flags & ISLASTCN,
1476 	    ("relookup: Not given last component."));
1477 	/*
1478 	 * Setup: break out flag bits into variables.
1479 	 */
1480 	KASSERT((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) != 0,
1481 	    ("relookup: parent not wanted"));
1482 	rdonly = cnp->cn_flags & RDONLY;
1483 	cnp->cn_flags &= ~ISSYMLINK;
1484 	dp = dvp;
1485 	cnp->cn_lkflags = LK_EXCLUSIVE;
1486 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1487 
1488 	/*
1489 	 * Search a new directory.
1490 	 *
1491 	 * See a comment in vfs_lookup for cnp->cn_nameptr.
1492 	 */
1493 #ifdef NAMEI_DIAGNOSTIC
1494 	printf("{%s}: ", cnp->cn_nameptr);
1495 #endif
1496 
1497 	/*
1498 	 * Check for "" which represents the root directory after slash
1499 	 * removal.
1500 	 */
1501 	if (cnp->cn_nameptr[0] == '\0') {
1502 		/*
1503 		 * Support only LOOKUP for "/" because lookup()
1504 		 * can't succeed for CREATE, DELETE and RENAME.
1505 		 */
1506 		KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1507 		KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1508 
1509 		if (!(cnp->cn_flags & LOCKLEAF))
1510 			VOP_UNLOCK(dp);
1511 		*vpp = dp;
1512 		/* XXX This should probably move to the top of function. */
1513 		if (refstart)
1514 			panic("lookup: SAVESTART");
1515 		return (0);
1516 	}
1517 
1518 	if (cnp->cn_flags & ISDOTDOT)
1519 		panic ("relookup: lookup on dot-dot");
1520 
1521 	/*
1522 	 * We now have a segment name to search for, and a directory to search.
1523 	 */
1524 #ifdef NAMEI_DIAGNOSTIC
1525 	vn_printf(dp, "search in ");
1526 #endif
1527 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1528 		KASSERT(*vpp == NULL, ("leaf should be empty"));
1529 		if (error != EJUSTRETURN)
1530 			goto bad;
1531 		/*
1532 		 * If creating and at end of pathname, then can consider
1533 		 * allowing file to be created.
1534 		 */
1535 		if (rdonly) {
1536 			error = EROFS;
1537 			goto bad;
1538 		}
1539 		/* ASSERT(dvp == ndp->ni_startdir) */
1540 		if (refstart)
1541 			VREF(dvp);
1542 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1543 			VOP_UNLOCK(dp);
1544 		/*
1545 		 * We return with ni_vp NULL to indicate that the entry
1546 		 * doesn't currently exist, leaving a pointer to the
1547 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1548 		 */
1549 		return (0);
1550 	}
1551 
1552 	dp = *vpp;
1553 
1554 	/*
1555 	 * Disallow directory write attempts on read-only filesystems.
1556 	 */
1557 	if (rdonly &&
1558 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1559 		if (dvp == dp)
1560 			vrele(dvp);
1561 		else
1562 			vput(dvp);
1563 		error = EROFS;
1564 		goto bad;
1565 	}
1566 	/*
1567 	 * Set the parent lock/ref state to the requested state.
1568 	 */
1569 	if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp)
1570 		VOP_UNLOCK(dvp);
1571 	/*
1572 	 * Check for symbolic link
1573 	 */
1574 	KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1575 	    ("relookup: symlink found.\n"));
1576 
1577 	/* ASSERT(dvp == ndp->ni_startdir) */
1578 	if (refstart)
1579 		VREF(dvp);
1580 
1581 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1582 		VOP_UNLOCK(dp);
1583 	return (0);
1584 bad:
1585 	vput(dp);
1586 	*vpp = NULL;
1587 	return (error);
1588 }
1589 
1590 #ifdef INVARIANTS
1591 /*
1592  * Validate the final state of ndp after the lookup.
1593  */
1594 static void
1595 NDVALIDATE_impl(struct nameidata *ndp, int line)
1596 {
1597 	struct componentname *cnp;
1598 
1599 	cnp = &ndp->ni_cnd;
1600 	if (cnp->cn_pnbuf == NULL)
1601 		panic("%s: got no buf! called from %d", __func__, line);
1602 }
1603 
1604 #endif
1605