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