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