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