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