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