xref: /freebsd/sys/kern/vfs_lookup.c (revision 94942af266ac119ede0ca836f9aa5a5ac0582938)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)vfs_lookup.c	8.4 (Berkeley) 2/16/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_ktrace.h"
41 #include "opt_mac.h"
42 #include "opt_vfs.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/namei.h>
50 #include <sys/vnode.h>
51 #include <sys/mount.h>
52 #include <sys/filedesc.h>
53 #include <sys/proc.h>
54 #include <sys/syscallsubr.h>
55 #include <sys/sysctl.h>
56 #ifdef KTRACE
57 #include <sys/ktrace.h>
58 #endif
59 
60 #include <security/audit/audit.h>
61 #include <security/mac/mac_framework.h>
62 
63 #include <vm/uma.h>
64 
65 #define	NAMEI_DIAGNOSTIC 1
66 #undef NAMEI_DIAGNOSTIC
67 
68 /*
69  * Allocation zone for namei
70  */
71 uma_zone_t namei_zone;
72 /*
73  * Placeholder vnode for mp traversal
74  */
75 static struct vnode *vp_crossmp;
76 
77 static void
78 nameiinit(void *dummy __unused)
79 {
80 	int error;
81 
82 	namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
83 	    UMA_ALIGN_PTR, 0);
84 	error = getnewvnode("crossmp", NULL, &dead_vnodeops, &vp_crossmp);
85 	if (error != 0)
86 		panic("nameiinit: getnewvnode");
87 	vp_crossmp->v_vnlock->lk_flags &= ~LK_NOSHARE;
88 }
89 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL)
90 
91 #ifdef LOOKUP_SHARED
92 static int lookup_shared = 1;
93 #else
94 static int lookup_shared = 0;
95 #endif
96 SYSCTL_INT(_vfs, OID_AUTO, lookup_shared, CTLFLAG_RW, &lookup_shared, 0,
97     "Enables/Disables shared locks for path name translation");
98 
99 /*
100  * Convert a pathname into a pointer to a locked vnode.
101  *
102  * The FOLLOW flag is set when symbolic links are to be followed
103  * when they occur at the end of the name translation process.
104  * Symbolic links are always followed for all other pathname
105  * components other than the last.
106  *
107  * The segflg defines whether the name is to be copied from user
108  * space or kernel space.
109  *
110  * Overall outline of namei:
111  *
112  *	copy in name
113  *	get starting directory
114  *	while (!done && !error) {
115  *		call lookup to search path.
116  *		if symbolic link, massage name in buffer and continue
117  *	}
118  */
119 int
120 namei(struct nameidata *ndp)
121 {
122 	struct filedesc *fdp;	/* pointer to file descriptor state */
123 	char *cp;		/* pointer into pathname argument */
124 	struct vnode *dp;	/* the directory we are searching */
125 	struct iovec aiov;		/* uio for reading symbolic links */
126 	struct uio auio;
127 	int error, linklen;
128 	struct componentname *cnp = &ndp->ni_cnd;
129 	struct thread *td = cnp->cn_thread;
130 	struct proc *p = td->td_proc;
131 	int vfslocked;
132 
133 	KASSERT((cnp->cn_flags & MPSAFE) != 0 || mtx_owned(&Giant) != 0,
134 	    ("NOT MPSAFE and Giant not held"));
135 	ndp->ni_cnd.cn_cred = ndp->ni_cnd.cn_thread->td_ucred;
136 	KASSERT(cnp->cn_cred && p, ("namei: bad cred/proc"));
137 	KASSERT((cnp->cn_nameiop & (~OPMASK)) == 0,
138 	    ("namei: nameiop contaminated with flags"));
139 	KASSERT((cnp->cn_flags & OPMASK) == 0,
140 	    ("namei: flags contaminated with nameiops"));
141 	if (!lookup_shared)
142 		cnp->cn_flags &= ~LOCKSHARED;
143 	fdp = p->p_fd;
144 
145 	/*
146 	 * Get a buffer for the name to be translated, and copy the
147 	 * name into the buffer.
148 	 */
149 	if ((cnp->cn_flags & HASBUF) == 0)
150 		cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
151 	if (ndp->ni_segflg == UIO_SYSSPACE)
152 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf,
153 			    MAXPATHLEN, (size_t *)&ndp->ni_pathlen);
154 	else
155 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
156 			    MAXPATHLEN, (size_t *)&ndp->ni_pathlen);
157 
158 	/* If we are auditing the kernel pathname, save the user pathname. */
159 	if (cnp->cn_flags & AUDITVNODE1)
160 		AUDIT_ARG(upath, td, cnp->cn_pnbuf, ARG_UPATH1);
161 	if (cnp->cn_flags & AUDITVNODE2)
162 		AUDIT_ARG(upath, td, cnp->cn_pnbuf, ARG_UPATH2);
163 
164 	/*
165 	 * Don't allow empty pathnames.
166 	 */
167 	if (!error && *cnp->cn_pnbuf == '\0')
168 		error = ENOENT;
169 
170 	if (error) {
171 		uma_zfree(namei_zone, cnp->cn_pnbuf);
172 #ifdef DIAGNOSTIC
173 		cnp->cn_pnbuf = NULL;
174 		cnp->cn_nameptr = NULL;
175 #endif
176 		ndp->ni_vp = NULL;
177 		return (error);
178 	}
179 	ndp->ni_loopcnt = 0;
180 #ifdef KTRACE
181 	if (KTRPOINT(td, KTR_NAMEI)) {
182 		KASSERT(cnp->cn_thread == curthread,
183 		    ("namei not using curthread"));
184 		ktrnamei(cnp->cn_pnbuf);
185 	}
186 #endif
187 
188 	/*
189 	 * Get starting point for the translation.
190 	 */
191 	FILEDESC_SLOCK(fdp);
192 	ndp->ni_rootdir = fdp->fd_rdir;
193 	ndp->ni_topdir = fdp->fd_jdir;
194 
195 	dp = fdp->fd_cdir;
196 	vfslocked = VFS_LOCK_GIANT(dp->v_mount);
197 	VREF(dp);
198 	FILEDESC_SUNLOCK(fdp);
199 	for (;;) {
200 		/*
201 		 * Check if root directory should replace current directory.
202 		 * Done at start of translation and after symbolic link.
203 		 */
204 		cnp->cn_nameptr = cnp->cn_pnbuf;
205 		if (*(cnp->cn_nameptr) == '/') {
206 			vrele(dp);
207 			VFS_UNLOCK_GIANT(vfslocked);
208 			while (*(cnp->cn_nameptr) == '/') {
209 				cnp->cn_nameptr++;
210 				ndp->ni_pathlen--;
211 			}
212 			dp = ndp->ni_rootdir;
213 			vfslocked = VFS_LOCK_GIANT(dp->v_mount);
214 			VREF(dp);
215 		}
216 		if (vfslocked)
217 			ndp->ni_cnd.cn_flags |= GIANTHELD;
218 		ndp->ni_startdir = dp;
219 		error = lookup(ndp);
220 		if (error) {
221 			uma_zfree(namei_zone, cnp->cn_pnbuf);
222 #ifdef DIAGNOSTIC
223 			cnp->cn_pnbuf = NULL;
224 			cnp->cn_nameptr = NULL;
225 #endif
226 			return (error);
227 		}
228 		vfslocked = (ndp->ni_cnd.cn_flags & GIANTHELD) != 0;
229 		ndp->ni_cnd.cn_flags &= ~GIANTHELD;
230 		/*
231 		 * Check for symbolic link
232 		 */
233 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
234 			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0) {
235 				uma_zfree(namei_zone, cnp->cn_pnbuf);
236 #ifdef DIAGNOSTIC
237 				cnp->cn_pnbuf = NULL;
238 				cnp->cn_nameptr = NULL;
239 #endif
240 			} else
241 				cnp->cn_flags |= HASBUF;
242 
243 			if ((cnp->cn_flags & MPSAFE) == 0) {
244 				VFS_UNLOCK_GIANT(vfslocked);
245 			} else if (vfslocked)
246 				ndp->ni_cnd.cn_flags |= GIANTHELD;
247 			return (0);
248 		}
249 		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
250 			error = ELOOP;
251 			break;
252 		}
253 #ifdef MAC
254 		if ((cnp->cn_flags & NOMACCHECK) == 0) {
255 			error = mac_check_vnode_readlink(td->td_ucred,
256 			    ndp->ni_vp);
257 			if (error)
258 				break;
259 		}
260 #endif
261 		if (ndp->ni_pathlen > 1)
262 			cp = uma_zalloc(namei_zone, M_WAITOK);
263 		else
264 			cp = cnp->cn_pnbuf;
265 		aiov.iov_base = cp;
266 		aiov.iov_len = MAXPATHLEN;
267 		auio.uio_iov = &aiov;
268 		auio.uio_iovcnt = 1;
269 		auio.uio_offset = 0;
270 		auio.uio_rw = UIO_READ;
271 		auio.uio_segflg = UIO_SYSSPACE;
272 		auio.uio_td = (struct thread *)0;
273 		auio.uio_resid = MAXPATHLEN;
274 		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
275 		if (error) {
276 			if (ndp->ni_pathlen > 1)
277 				uma_zfree(namei_zone, cp);
278 			break;
279 		}
280 		linklen = MAXPATHLEN - auio.uio_resid;
281 		if (linklen == 0) {
282 			if (ndp->ni_pathlen > 1)
283 				uma_zfree(namei_zone, cp);
284 			error = ENOENT;
285 			break;
286 		}
287 		if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
288 			if (ndp->ni_pathlen > 1)
289 				uma_zfree(namei_zone, cp);
290 			error = ENAMETOOLONG;
291 			break;
292 		}
293 		if (ndp->ni_pathlen > 1) {
294 			bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
295 			uma_zfree(namei_zone, cnp->cn_pnbuf);
296 			cnp->cn_pnbuf = cp;
297 		} else
298 			cnp->cn_pnbuf[linklen] = '\0';
299 		ndp->ni_pathlen += linklen;
300 		vput(ndp->ni_vp);
301 		dp = ndp->ni_dvp;
302 	}
303 	uma_zfree(namei_zone, cnp->cn_pnbuf);
304 #ifdef DIAGNOSTIC
305 	cnp->cn_pnbuf = NULL;
306 	cnp->cn_nameptr = NULL;
307 #endif
308 	vput(ndp->ni_vp);
309 	ndp->ni_vp = NULL;
310 	vrele(ndp->ni_dvp);
311 	VFS_UNLOCK_GIANT(vfslocked);
312 	return (error);
313 }
314 
315 static int
316 compute_cn_lkflags(struct mount *mp, int lkflags)
317 {
318 	if (mp == NULL ||
319 	    ((lkflags & LK_SHARED) && !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
320 		lkflags &= ~LK_SHARED;
321 		lkflags |= LK_EXCLUSIVE;
322 	}
323 	return lkflags;
324 }
325 
326 /*
327  * Search a pathname.
328  * This is a very central and rather complicated routine.
329  *
330  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
331  * The starting directory is taken from ni_startdir. The pathname is
332  * descended until done, or a symbolic link is encountered. The variable
333  * ni_more is clear if the path is completed; it is set to one if a
334  * symbolic link needing interpretation is encountered.
335  *
336  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
337  * whether the name is to be looked up, created, renamed, or deleted.
338  * When CREATE, RENAME, or DELETE is specified, information usable in
339  * creating, renaming, or deleting a directory entry may be calculated.
340  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
341  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
342  * returned unlocked. Otherwise the parent directory is not returned. If
343  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
344  * the target is returned locked, otherwise it is returned unlocked.
345  * When creating or renaming and LOCKPARENT is specified, the target may not
346  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
347  *
348  * Overall outline of lookup:
349  *
350  * dirloop:
351  *	identify next component of name at ndp->ni_ptr
352  *	handle degenerate case where name is null string
353  *	if .. and crossing mount points and on mounted filesys, find parent
354  *	call VOP_LOOKUP routine for next component name
355  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
356  *	    component vnode returned in ni_vp (if it exists), locked.
357  *	if result vnode is mounted on and crossing mount points,
358  *	    find mounted on vnode
359  *	if more components of name, do next level at dirloop
360  *	return the answer in ni_vp, locked if LOCKLEAF set
361  *	    if LOCKPARENT set, return locked parent in ni_dvp
362  *	    if WANTPARENT set, return unlocked parent in ni_dvp
363  */
364 int
365 lookup(struct nameidata *ndp)
366 {
367 	char *cp;		/* pointer into pathname argument */
368 	struct vnode *dp = 0;	/* the directory we are searching */
369 	struct vnode *tdp;		/* saved dp */
370 	struct mount *mp;		/* mount table entry */
371 	int docache;			/* == 0 do not cache last component */
372 	int wantparent;			/* 1 => wantparent or lockparent flag */
373 	int rdonly;			/* lookup read-only flag bit */
374 	int trailing_slash;
375 	int error = 0;
376 	int dpunlocked = 0;		/* dp has already been unlocked */
377 	struct componentname *cnp = &ndp->ni_cnd;
378 	struct thread *td = cnp->cn_thread;
379 	int vfslocked;			/* VFS Giant state for child */
380 	int dvfslocked;			/* VFS Giant state for parent */
381 	int tvfslocked;
382 	int lkflags_save;
383 
384 	/*
385 	 * Setup: break out flag bits into variables.
386 	 */
387 	dvfslocked = (ndp->ni_cnd.cn_flags & GIANTHELD) != 0;
388 	vfslocked = 0;
389 	ndp->ni_cnd.cn_flags &= ~GIANTHELD;
390 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
391 	KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
392 	    ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
393 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
394 	if (cnp->cn_nameiop == DELETE ||
395 	    (wantparent && cnp->cn_nameiop != CREATE &&
396 	     cnp->cn_nameiop != LOOKUP))
397 		docache = 0;
398 	rdonly = cnp->cn_flags & RDONLY;
399 	cnp->cn_flags &= ~ISSYMLINK;
400 	ndp->ni_dvp = NULL;
401 	/*
402 	 * We use shared locks until we hit the parent of the last cn then
403 	 * we adjust based on the requesting flags.
404 	 */
405 	if (lookup_shared)
406 		cnp->cn_lkflags = LK_SHARED;
407 	else
408 		cnp->cn_lkflags = LK_EXCLUSIVE;
409 	dp = ndp->ni_startdir;
410 	ndp->ni_startdir = NULLVP;
411 	vn_lock(dp, compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY), td);
412 
413 dirloop:
414 	/*
415 	 * Search a new directory.
416 	 *
417 	 * The last component of the filename is left accessible via
418 	 * cnp->cn_nameptr for callers that need the name. Callers needing
419 	 * the name set the SAVENAME flag. When done, they assume
420 	 * responsibility for freeing the pathname buffer.
421 	 */
422 	cnp->cn_consume = 0;
423 	for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
424 		continue;
425 	cnp->cn_namelen = cp - cnp->cn_nameptr;
426 	if (cnp->cn_namelen > NAME_MAX) {
427 		error = ENAMETOOLONG;
428 		goto bad;
429 	}
430 #ifdef NAMEI_DIAGNOSTIC
431 	{ char c = *cp;
432 	*cp = '\0';
433 	printf("{%s}: ", cnp->cn_nameptr);
434 	*cp = c; }
435 #endif
436 	ndp->ni_pathlen -= cnp->cn_namelen;
437 	ndp->ni_next = cp;
438 
439 	/*
440 	 * Replace multiple slashes by a single slash and trailing slashes
441 	 * by a null.  This must be done before VOP_LOOKUP() because some
442 	 * fs's don't know about trailing slashes.  Remember if there were
443 	 * trailing slashes to handle symlinks, existing non-directories
444 	 * and non-existing files that won't be directories specially later.
445 	 */
446 	trailing_slash = 0;
447 	while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
448 		cp++;
449 		ndp->ni_pathlen--;
450 		if (*cp == '\0') {
451 			trailing_slash = 1;
452 			*ndp->ni_next = '\0';	/* XXX for direnter() ... */
453 		}
454 	}
455 	ndp->ni_next = cp;
456 
457 	cnp->cn_flags |= MAKEENTRY;
458 	if (*cp == '\0' && docache == 0)
459 		cnp->cn_flags &= ~MAKEENTRY;
460 	if (cnp->cn_namelen == 2 &&
461 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
462 		cnp->cn_flags |= ISDOTDOT;
463 	else
464 		cnp->cn_flags &= ~ISDOTDOT;
465 	if (*ndp->ni_next == 0)
466 		cnp->cn_flags |= ISLASTCN;
467 	else
468 		cnp->cn_flags &= ~ISLASTCN;
469 
470 
471 	/*
472 	 * Check for degenerate name (e.g. / or "")
473 	 * which is a way of talking about a directory,
474 	 * e.g. like "/." or ".".
475 	 */
476 	if (cnp->cn_nameptr[0] == '\0') {
477 		if (dp->v_type != VDIR) {
478 			error = ENOTDIR;
479 			goto bad;
480 		}
481 		if (cnp->cn_nameiop != LOOKUP) {
482 			error = EISDIR;
483 			goto bad;
484 		}
485 		if (wantparent) {
486 			ndp->ni_dvp = dp;
487 			VREF(dp);
488 		}
489 		ndp->ni_vp = dp;
490 
491 		if (cnp->cn_flags & AUDITVNODE1)
492 			AUDIT_ARG(vnode, dp, ARG_VNODE1);
493 		else if (cnp->cn_flags & AUDITVNODE2)
494 			AUDIT_ARG(vnode, dp, ARG_VNODE2);
495 
496 		if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
497 			VOP_UNLOCK(dp, 0, td);
498 		/* XXX This should probably move to the top of function. */
499 		if (cnp->cn_flags & SAVESTART)
500 			panic("lookup: SAVESTART");
501 		goto success;
502 	}
503 
504 	/*
505 	 * Handle "..": four special cases.
506 	 * 1. Return an error if this is the last component of
507 	 *    the name and the operation is DELETE or RENAME.
508 	 * 2. If at root directory (e.g. after chroot)
509 	 *    or at absolute root directory
510 	 *    then ignore it so can't get out.
511 	 * 3. If this vnode is the root of a mounted
512 	 *    filesystem, then replace it with the
513 	 *    vnode which was mounted on so we take the
514 	 *    .. in the other filesystem.
515 	 * 4. If the vnode is the top directory of
516 	 *    the jail or chroot, don't let them out.
517 	 */
518 	if (cnp->cn_flags & ISDOTDOT) {
519 		if ((cnp->cn_flags & ISLASTCN) != 0 &&
520 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
521 			error = EINVAL;
522 			goto bad;
523 		}
524 		for (;;) {
525 			if (dp == ndp->ni_rootdir ||
526 			    dp == ndp->ni_topdir ||
527 			    dp == rootvnode ||
528 			    ((dp->v_vflag & VV_ROOT) != 0 &&
529 			     (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
530 				ndp->ni_dvp = dp;
531 				ndp->ni_vp = dp;
532 				vfslocked = VFS_LOCK_GIANT(dp->v_mount);
533 				VREF(dp);
534 				goto nextname;
535 			}
536 			if ((dp->v_vflag & VV_ROOT) == 0)
537 				break;
538 			if (dp->v_iflag & VI_DOOMED) {	/* forced unmount */
539 				error = EBADF;
540 				goto bad;
541 			}
542 			tdp = dp;
543 			dp = dp->v_mount->mnt_vnodecovered;
544 			tvfslocked = dvfslocked;
545 			dvfslocked = VFS_LOCK_GIANT(dp->v_mount);
546 			VREF(dp);
547 			vput(tdp);
548 			VFS_UNLOCK_GIANT(tvfslocked);
549 			vn_lock(dp, compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY), td);
550 		}
551 	}
552 
553 	/*
554 	 * We now have a segment name to search for, and a directory to search.
555 	 */
556 unionlookup:
557 #ifdef MAC
558 	if ((cnp->cn_flags & NOMACCHECK) == 0) {
559 		error = mac_check_vnode_lookup(td->td_ucred, dp, cnp);
560 		if (error)
561 			goto bad;
562 	}
563 #endif
564 	ndp->ni_dvp = dp;
565 	ndp->ni_vp = NULL;
566 	ASSERT_VOP_LOCKED(dp, "lookup");
567 	VNASSERT(vfslocked == 0, dp, ("lookup: vfslocked %d", vfslocked));
568 	/*
569 	 * If we have a shared lock we may need to upgrade the lock for the
570 	 * last operation.
571 	 */
572 	if (dp != vp_crossmp &&
573 	    VOP_ISLOCKED(dp, td) == LK_SHARED &&
574 	    (cnp->cn_flags & ISLASTCN) && (cnp->cn_flags & LOCKPARENT))
575 		vn_lock(dp, LK_UPGRADE|LK_RETRY, td);
576 	/*
577 	 * If we're looking up the last component and we need an exclusive
578 	 * lock, adjust our lkflags.
579 	 */
580 	if ((cnp->cn_flags & (ISLASTCN|LOCKSHARED|LOCKLEAF)) ==
581 	    (ISLASTCN|LOCKLEAF))
582 		cnp->cn_lkflags = LK_EXCLUSIVE;
583 #ifdef NAMEI_DIAGNOSTIC
584 	vprint("lookup in", dp);
585 #endif
586 	lkflags_save = cnp->cn_lkflags;
587 	cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags);
588 	if ((error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp)) != 0) {
589 		cnp->cn_lkflags = lkflags_save;
590 		KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
591 #ifdef NAMEI_DIAGNOSTIC
592 		printf("not found\n");
593 #endif
594 		if ((error == ENOENT) &&
595 		    (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
596 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
597 			tdp = dp;
598 			dp = dp->v_mount->mnt_vnodecovered;
599 			tvfslocked = dvfslocked;
600 			dvfslocked = VFS_LOCK_GIANT(dp->v_mount);
601 			VREF(dp);
602 			vput(tdp);
603 			VFS_UNLOCK_GIANT(tvfslocked);
604 			vn_lock(dp, compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY), td);
605 			goto unionlookup;
606 		}
607 
608 		if (error != EJUSTRETURN)
609 			goto bad;
610 		/*
611 		 * If creating and at end of pathname, then can consider
612 		 * allowing file to be created.
613 		 */
614 		if (rdonly) {
615 			error = EROFS;
616 			goto bad;
617 		}
618 		if (*cp == '\0' && trailing_slash &&
619 		     !(cnp->cn_flags & WILLBEDIR)) {
620 			error = ENOENT;
621 			goto bad;
622 		}
623 		if ((cnp->cn_flags & LOCKPARENT) == 0)
624 			VOP_UNLOCK(dp, 0, td);
625 		/*
626 		 * This is a temporary assert to make sure I know what the
627 		 * behavior here was.
628 		 */
629 		KASSERT((cnp->cn_flags & (WANTPARENT|LOCKPARENT)) != 0,
630 		   ("lookup: Unhandled case."));
631 		/*
632 		 * We return with ni_vp NULL to indicate that the entry
633 		 * doesn't currently exist, leaving a pointer to the
634 		 * (possibly locked) directory vnode in ndp->ni_dvp.
635 		 */
636 		if (cnp->cn_flags & SAVESTART) {
637 			ndp->ni_startdir = ndp->ni_dvp;
638 			VREF(ndp->ni_startdir);
639 		}
640 		goto success;
641 	} else
642 		cnp->cn_lkflags = lkflags_save;
643 #ifdef NAMEI_DIAGNOSTIC
644 	printf("found\n");
645 #endif
646 	/*
647 	 * Take into account any additional components consumed by
648 	 * the underlying filesystem.
649 	 */
650 	if (cnp->cn_consume > 0) {
651 		cnp->cn_nameptr += cnp->cn_consume;
652 		ndp->ni_next += cnp->cn_consume;
653 		ndp->ni_pathlen -= cnp->cn_consume;
654 		cnp->cn_consume = 0;
655 	}
656 
657 	dp = ndp->ni_vp;
658 	vfslocked = VFS_LOCK_GIANT(dp->v_mount);
659 
660 	/*
661 	 * Check to see if the vnode has been mounted on;
662 	 * if so find the root of the mounted filesystem.
663 	 */
664 	while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
665 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
666 		if (vfs_busy(mp, 0, 0, td))
667 			continue;
668 		vput(dp);
669 		VFS_UNLOCK_GIANT(vfslocked);
670 		vfslocked = VFS_LOCK_GIANT(mp);
671 		if (dp != ndp->ni_dvp)
672 			vput(ndp->ni_dvp);
673 		else
674 			vrele(ndp->ni_dvp);
675 		VFS_UNLOCK_GIANT(dvfslocked);
676 		dvfslocked = 0;
677 		vref(vp_crossmp);
678 		ndp->ni_dvp = vp_crossmp;
679 		error = VFS_ROOT(mp, compute_cn_lkflags(mp, cnp->cn_lkflags), &tdp, td);
680 		vfs_unbusy(mp, td);
681 		if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT, td))
682 			panic("vp_crossmp exclusively locked or reclaimed");
683 		if (error) {
684 			dpunlocked = 1;
685 			goto bad2;
686 		}
687 		ndp->ni_vp = dp = tdp;
688 	}
689 
690 	/*
691 	 * Check for symbolic link
692 	 */
693 	if ((dp->v_type == VLNK) &&
694 	    ((cnp->cn_flags & FOLLOW) || trailing_slash ||
695 	     *ndp->ni_next == '/')) {
696 		cnp->cn_flags |= ISSYMLINK;
697 		if (dp->v_iflag & VI_DOOMED) {
698 			/* We can't know whether the directory was mounted with
699 			 * NOSYMFOLLOW, so we can't follow safely. */
700 			error = EBADF;
701 			goto bad2;
702 		}
703 		if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
704 			error = EACCES;
705 			goto bad2;
706 		}
707 		/*
708 		 * Symlink code always expects an unlocked dvp.
709 		 */
710 		if (ndp->ni_dvp != ndp->ni_vp)
711 			VOP_UNLOCK(ndp->ni_dvp, 0, td);
712 		goto success;
713 	}
714 
715 	/*
716 	 * Check for bogus trailing slashes.
717 	 */
718 	if (trailing_slash && dp->v_type != VDIR) {
719 		error = ENOTDIR;
720 		goto bad2;
721 	}
722 
723 nextname:
724 	/*
725 	 * Not a symbolic link.  If more pathname,
726 	 * continue at next component, else return.
727 	 */
728 	KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
729 	    ("lookup: invalid path state."));
730 	if (*ndp->ni_next == '/') {
731 		cnp->cn_nameptr = ndp->ni_next;
732 		while (*cnp->cn_nameptr == '/') {
733 			cnp->cn_nameptr++;
734 			ndp->ni_pathlen--;
735 		}
736 		if (ndp->ni_dvp != dp)
737 			vput(ndp->ni_dvp);
738 		else
739 			vrele(ndp->ni_dvp);
740 		VFS_UNLOCK_GIANT(dvfslocked);
741 		dvfslocked = vfslocked;	/* dp becomes dvp in dirloop */
742 		vfslocked = 0;
743 		goto dirloop;
744 	}
745 	/*
746 	 * Disallow directory write attempts on read-only filesystems.
747 	 */
748 	if (rdonly &&
749 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
750 		error = EROFS;
751 		goto bad2;
752 	}
753 	if (cnp->cn_flags & SAVESTART) {
754 		ndp->ni_startdir = ndp->ni_dvp;
755 		VREF(ndp->ni_startdir);
756 	}
757 	if (!wantparent) {
758 		if (ndp->ni_dvp != dp)
759 			vput(ndp->ni_dvp);
760 		else
761 			vrele(ndp->ni_dvp);
762 		VFS_UNLOCK_GIANT(dvfslocked);
763 		dvfslocked = 0;
764 	} else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp)
765 		VOP_UNLOCK(ndp->ni_dvp, 0, td);
766 
767 	if (cnp->cn_flags & AUDITVNODE1)
768 		AUDIT_ARG(vnode, dp, ARG_VNODE1);
769 	else if (cnp->cn_flags & AUDITVNODE2)
770 		AUDIT_ARG(vnode, dp, ARG_VNODE2);
771 
772 	if ((cnp->cn_flags & LOCKLEAF) == 0)
773 		VOP_UNLOCK(dp, 0, td);
774 success:
775 	if (vfslocked && dvfslocked)
776 		VFS_UNLOCK_GIANT(dvfslocked);	/* Only need one */
777 	if (vfslocked || dvfslocked)
778 		ndp->ni_cnd.cn_flags |= GIANTHELD;
779 	return (0);
780 
781 bad2:
782 	if (dp != ndp->ni_dvp)
783 		vput(ndp->ni_dvp);
784 	else
785 		vrele(ndp->ni_dvp);
786 bad:
787 	if (!dpunlocked)
788 		vput(dp);
789 	VFS_UNLOCK_GIANT(vfslocked);
790 	VFS_UNLOCK_GIANT(dvfslocked);
791 	ndp->ni_cnd.cn_flags &= ~GIANTHELD;
792 	ndp->ni_vp = NULL;
793 	return (error);
794 }
795 
796 /*
797  * relookup - lookup a path name component
798  *    Used by lookup to re-aquire things.
799  */
800 int
801 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
802 {
803 	struct thread *td = cnp->cn_thread;
804 	struct vnode *dp = 0;		/* the directory we are searching */
805 	int wantparent;			/* 1 => wantparent or lockparent flag */
806 	int rdonly;			/* lookup read-only flag bit */
807 	int error = 0;
808 
809 	KASSERT(cnp->cn_flags & ISLASTCN,
810 	    ("relookup: Not given last component."));
811 	/*
812 	 * Setup: break out flag bits into variables.
813 	 */
814 	wantparent = cnp->cn_flags & (LOCKPARENT|WANTPARENT);
815 	KASSERT(wantparent, ("relookup: parent not wanted."));
816 	rdonly = cnp->cn_flags & RDONLY;
817 	cnp->cn_flags &= ~ISSYMLINK;
818 	dp = dvp;
819 	cnp->cn_lkflags = LK_EXCLUSIVE;
820 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY, td);
821 
822 	/*
823 	 * Search a new directory.
824 	 *
825 	 * The last component of the filename is left accessible via
826 	 * cnp->cn_nameptr for callers that need the name. Callers needing
827 	 * the name set the SAVENAME flag. When done, they assume
828 	 * responsibility for freeing the pathname buffer.
829 	 */
830 #ifdef NAMEI_DIAGNOSTIC
831 	printf("{%s}: ", cnp->cn_nameptr);
832 #endif
833 
834 	/*
835 	 * Check for degenerate name (e.g. / or "")
836 	 * which is a way of talking about a directory,
837 	 * e.g. like "/." or ".".
838 	 */
839 	if (cnp->cn_nameptr[0] == '\0') {
840 		if (cnp->cn_nameiop != LOOKUP || wantparent) {
841 			error = EISDIR;
842 			goto bad;
843 		}
844 		if (dp->v_type != VDIR) {
845 			error = ENOTDIR;
846 			goto bad;
847 		}
848 		if (!(cnp->cn_flags & LOCKLEAF))
849 			VOP_UNLOCK(dp, 0, td);
850 		*vpp = dp;
851 		/* XXX This should probably move to the top of function. */
852 		if (cnp->cn_flags & SAVESTART)
853 			panic("lookup: SAVESTART");
854 		return (0);
855 	}
856 
857 	if (cnp->cn_flags & ISDOTDOT)
858 		panic ("relookup: lookup on dot-dot");
859 
860 	/*
861 	 * We now have a segment name to search for, and a directory to search.
862 	 */
863 #ifdef NAMEI_DIAGNOSTIC
864 	vprint("search in:", dp);
865 #endif
866 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
867 		KASSERT(*vpp == NULL, ("leaf should be empty"));
868 		if (error != EJUSTRETURN)
869 			goto bad;
870 		/*
871 		 * If creating and at end of pathname, then can consider
872 		 * allowing file to be created.
873 		 */
874 		if (rdonly) {
875 			error = EROFS;
876 			goto bad;
877 		}
878 		/* ASSERT(dvp == ndp->ni_startdir) */
879 		if (cnp->cn_flags & SAVESTART)
880 			VREF(dvp);
881 		if ((cnp->cn_flags & LOCKPARENT) == 0)
882 			VOP_UNLOCK(dp, 0, td);
883 		/*
884 		 * This is a temporary assert to make sure I know what the
885 		 * behavior here was.
886 		 */
887 		KASSERT((cnp->cn_flags & (WANTPARENT|LOCKPARENT)) != 0,
888 		   ("relookup: Unhandled case."));
889 		/*
890 		 * We return with ni_vp NULL to indicate that the entry
891 		 * doesn't currently exist, leaving a pointer to the
892 		 * (possibly locked) directory vnode in ndp->ni_dvp.
893 		 */
894 		return (0);
895 	}
896 
897 	dp = *vpp;
898 
899 	/*
900 	 * Disallow directory write attempts on read-only filesystems.
901 	 */
902 	if (rdonly &&
903 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
904 		if (dvp == dp)
905 			vrele(dvp);
906 		else
907 			vput(dvp);
908 		error = EROFS;
909 		goto bad;
910 	}
911 	/*
912 	 * Set the parent lock/ref state to the requested state.
913 	 */
914 	if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp) {
915 		if (wantparent)
916 			VOP_UNLOCK(dvp, 0, td);
917 		else
918 			vput(dvp);
919 	} else if (!wantparent)
920 		vrele(dvp);
921 	/*
922 	 * Check for symbolic link
923 	 */
924 	KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
925 	    ("relookup: symlink found.\n"));
926 
927 	/* ASSERT(dvp == ndp->ni_startdir) */
928 	if (cnp->cn_flags & SAVESTART)
929 		VREF(dvp);
930 
931 	if ((cnp->cn_flags & LOCKLEAF) == 0)
932 		VOP_UNLOCK(dp, 0, td);
933 	return (0);
934 bad:
935 	vput(dp);
936 	*vpp = NULL;
937 	return (error);
938 }
939 
940 /*
941  * Free data allocated by namei(); see namei(9) for details.
942  */
943 void
944 NDFREE(struct nameidata *ndp, const u_int flags)
945 {
946 	int unlock_dvp;
947 	int unlock_vp;
948 
949 	unlock_dvp = 0;
950 	unlock_vp = 0;
951 
952 	if (!(flags & NDF_NO_FREE_PNBUF) &&
953 	    (ndp->ni_cnd.cn_flags & HASBUF)) {
954 		uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
955 		ndp->ni_cnd.cn_flags &= ~HASBUF;
956 	}
957 	if (!(flags & NDF_NO_VP_UNLOCK) &&
958 	    (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
959 		unlock_vp = 1;
960 	if (!(flags & NDF_NO_VP_RELE) && ndp->ni_vp) {
961 		if (unlock_vp) {
962 			vput(ndp->ni_vp);
963 			unlock_vp = 0;
964 		} else
965 			vrele(ndp->ni_vp);
966 		ndp->ni_vp = NULL;
967 	}
968 	if (unlock_vp)
969 		VOP_UNLOCK(ndp->ni_vp, 0, ndp->ni_cnd.cn_thread);
970 	if (!(flags & NDF_NO_DVP_UNLOCK) &&
971 	    (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
972 	    ndp->ni_dvp != ndp->ni_vp)
973 		unlock_dvp = 1;
974 	if (!(flags & NDF_NO_DVP_RELE) &&
975 	    (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
976 		if (unlock_dvp) {
977 			vput(ndp->ni_dvp);
978 			unlock_dvp = 0;
979 		} else
980 			vrele(ndp->ni_dvp);
981 		ndp->ni_dvp = NULL;
982 	}
983 	if (unlock_dvp)
984 		VOP_UNLOCK(ndp->ni_dvp, 0, ndp->ni_cnd.cn_thread);
985 	if (!(flags & NDF_NO_STARTDIR_RELE) &&
986 	    (ndp->ni_cnd.cn_flags & SAVESTART)) {
987 		vrele(ndp->ni_startdir);
988 		ndp->ni_startdir = NULL;
989 	}
990 }
991 
992 /*
993  * Determine if there is a suitable alternate filename under the specified
994  * prefix for the specified path.  If the create flag is set, then the
995  * alternate prefix will be used so long as the parent directory exists.
996  * This is used by the various compatiblity ABIs so that Linux binaries prefer
997  * files under /compat/linux for example.  The chosen path (whether under
998  * the prefix or under /) is returned in a kernel malloc'd buffer pointed
999  * to by pathbuf.  The caller is responsible for free'ing the buffer from
1000  * the M_TEMP bucket if one is returned.
1001  */
1002 int
1003 kern_alternate_path(struct thread *td, const char *prefix, char *path,
1004     enum uio_seg pathseg, char **pathbuf, int create)
1005 {
1006 	struct nameidata nd, ndroot;
1007 	char *ptr, *buf, *cp;
1008 	size_t len, sz;
1009 	int error;
1010 
1011 	buf = (char *) malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1012 	*pathbuf = buf;
1013 
1014 	/* Copy the prefix into the new pathname as a starting point. */
1015 	len = strlcpy(buf, prefix, MAXPATHLEN);
1016 	if (len >= MAXPATHLEN) {
1017 		*pathbuf = NULL;
1018 		free(buf, M_TEMP);
1019 		return (EINVAL);
1020 	}
1021 	sz = MAXPATHLEN - len;
1022 	ptr = buf + len;
1023 
1024 	/* Append the filename to the prefix. */
1025 	if (pathseg == UIO_SYSSPACE)
1026 		error = copystr(path, ptr, sz, &len);
1027 	else
1028 		error = copyinstr(path, ptr, sz, &len);
1029 
1030 	if (error) {
1031 		*pathbuf = NULL;
1032 		free(buf, M_TEMP);
1033 		return (error);
1034 	}
1035 
1036 	/* Only use a prefix with absolute pathnames. */
1037 	if (*ptr != '/') {
1038 		error = EINVAL;
1039 		goto keeporig;
1040 	}
1041 
1042 	/*
1043 	 * We know that there is a / somewhere in this pathname.
1044 	 * Search backwards for it, to find the file's parent dir
1045 	 * to see if it exists in the alternate tree. If it does,
1046 	 * and we want to create a file (cflag is set). We don't
1047 	 * need to worry about the root comparison in this case.
1048 	 */
1049 
1050 	if (create) {
1051 		for (cp = &ptr[len] - 1; *cp != '/'; cp--);
1052 		*cp = '\0';
1053 
1054 		NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, buf, td);
1055 		error = namei(&nd);
1056 		*cp = '/';
1057 		if (error != 0)
1058 			goto keeporig;
1059 	} else {
1060 		NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, buf, td);
1061 
1062 		error = namei(&nd);
1063 		if (error != 0)
1064 			goto keeporig;
1065 
1066 		/*
1067 		 * We now compare the vnode of the prefix to the one
1068 		 * vnode asked. If they resolve to be the same, then we
1069 		 * ignore the match so that the real root gets used.
1070 		 * This avoids the problem of traversing "../.." to find the
1071 		 * root directory and never finding it, because "/" resolves
1072 		 * to the emulation root directory. This is expensive :-(
1073 		 */
1074 		NDINIT(&ndroot, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, prefix,
1075 		    td);
1076 
1077 		/* We shouldn't ever get an error from this namei(). */
1078 		error = namei(&ndroot);
1079 		if (error == 0) {
1080 			if (nd.ni_vp == ndroot.ni_vp)
1081 				error = ENOENT;
1082 
1083 			NDFREE(&ndroot, NDF_ONLY_PNBUF);
1084 			vrele(ndroot.ni_vp);
1085 			VFS_UNLOCK_GIANT(NDHASGIANT(&ndroot));
1086 		}
1087 	}
1088 
1089 	NDFREE(&nd, NDF_ONLY_PNBUF);
1090 	vrele(nd.ni_vp);
1091 	VFS_UNLOCK_GIANT(NDHASGIANT(&nd));
1092 
1093 keeporig:
1094 	/* If there was an error, use the original path name. */
1095 	if (error)
1096 		bcopy(ptr, buf, len);
1097 	return (error);
1098 }
1099