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