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