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