Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.77
      1 /*	$NetBSD: vfs_lookup.c,v 1.77 2006/12/27 23:21:02 chs Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1982, 1986, 1989, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)vfs_lookup.c	8.10 (Berkeley) 5/27/95
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: vfs_lookup.c,v 1.77 2006/12/27 23:21:02 chs Exp $");
     41 
     42 #include "opt_ktrace.h"
     43 #include "opt_systrace.h"
     44 #include "opt_magiclinks.h"
     45 
     46 #include <sys/param.h>
     47 #include <sys/systm.h>
     48 #include <sys/kernel.h>
     49 #include <sys/syslimits.h>
     50 #include <sys/time.h>
     51 #include <sys/namei.h>
     52 #include <sys/vnode.h>
     53 #include <sys/mount.h>
     54 #include <sys/errno.h>
     55 #include <sys/filedesc.h>
     56 #include <sys/hash.h>
     57 #include <sys/malloc.h>
     58 #include <sys/proc.h>
     59 #include <sys/syslog.h>
     60 #include <sys/kauth.h>
     61 
     62 #ifdef KTRACE
     63 #include <sys/ktrace.h>
     64 #endif
     65 #ifdef SYSTRACE
     66 #include <sys/systrace.h>
     67 #endif
     68 
     69 #ifndef MAGICLINKS
     70 #define MAGICLINKS 0
     71 #endif
     72 
     73 struct pathname_internal {
     74 	char *pathbuf;
     75 	boolean_t needfree;
     76 };
     77 
     78 int vfs_magiclinks = MAGICLINKS;
     79 
     80 struct pool pnbuf_pool;		/* pathname buffer pool */
     81 struct pool_cache pnbuf_cache;	/* pathname buffer cache */
     82 
     83 /*
     84  * Substitute replacement text for 'magic' strings in symlinks.
     85  * Returns 0 if successful, and returns non-zero if an error
     86  * occurs.  (Currently, the only possible error is running out
     87  * of temporary pathname space.)
     88  *
     89  * Looks for "@<string>" and "@<string>/", where <string> is a
     90  * recognized 'magic' string.  Replaces the "@<string>" with the
     91  * appropriate replacement text.  (Note that in some cases the
     92  * replacement text may have zero length.)
     93  *
     94  * This would have been table driven, but the variance in
     95  * replacement strings (and replacement string lengths) made
     96  * that impractical.
     97  */
     98 #define	VNL(x)							\
     99 	(sizeof(x) - 1)
    100 
    101 #define	VO	'{'
    102 #define	VC	'}'
    103 
    104 #define	MATCH(str)						\
    105 	((termchar == '/' && i + VNL(str) == *len) ||		\
    106 	 (i + VNL(str) < *len &&				\
    107 	  cp[i + VNL(str)] == termchar)) &&			\
    108 	!strncmp((str), &cp[i], VNL(str))
    109 
    110 #define	SUBSTITUTE(m, s, sl)					\
    111 	if ((newlen + (sl)) > MAXPATHLEN)			\
    112 		return (1);					\
    113 	i += VNL(m);						\
    114 	if (termchar != '/')					\
    115 		i++;						\
    116 	memcpy(&tmp[newlen], (s), (sl));			\
    117 	newlen += (sl);						\
    118 	change = 1;						\
    119 	termchar = '/';
    120 
    121 static int
    122 symlink_magic(struct proc *p, char *cp, int *len)
    123 {
    124 	char *tmp;
    125 	int change, i, newlen;
    126 	int termchar = '/';
    127 
    128 	tmp = PNBUF_GET();
    129 	for (change = i = newlen = 0; i < *len; ) {
    130 		if (cp[i] != '@') {
    131 			tmp[newlen++] = cp[i++];
    132 			continue;
    133 		}
    134 
    135 		i++;
    136 
    137 		/* Check for @{var} syntax. */
    138 		if (cp[i] == VO) {
    139 			termchar = VC;
    140 			i++;
    141 		}
    142 
    143 		/*
    144 		 * The following checks should be ordered according
    145 		 * to frequency of use.
    146 		 */
    147 		if (MATCH("machine_arch")) {
    148 			SUBSTITUTE("machine_arch", MACHINE_ARCH,
    149 			    sizeof(MACHINE_ARCH) - 1);
    150 		} else if (MATCH("machine")) {
    151 			SUBSTITUTE("machine", MACHINE,
    152 			    sizeof(MACHINE) - 1);
    153 		} else if (MATCH("hostname")) {
    154 			SUBSTITUTE("hostname", hostname,
    155 			    hostnamelen);
    156 		} else if (MATCH("osrelease")) {
    157 			SUBSTITUTE("osrelease", osrelease,
    158 			    strlen(osrelease));
    159 		} else if (MATCH("emul")) {
    160 			SUBSTITUTE("emul", p->p_emul->e_name,
    161 			    strlen(p->p_emul->e_name));
    162 		} else if (MATCH("kernel_ident")) {
    163 			SUBSTITUTE("kernel_ident", kernel_ident,
    164 			    strlen(kernel_ident));
    165 		} else if (MATCH("domainname")) {
    166 			SUBSTITUTE("domainname", domainname,
    167 			    domainnamelen);
    168 		} else if (MATCH("ostype")) {
    169 			SUBSTITUTE("ostype", ostype,
    170 			    strlen(ostype));
    171 		} else if (MATCH("uid")) {
    172 			char uidtmp[11]; /* XXX elad */
    173 
    174 			(void)snprintf(uidtmp, sizeof(uidtmp), "%u",
    175 			    kauth_cred_geteuid(kauth_cred_get()));
    176 			SUBSTITUTE("uid", uidtmp, strlen(uidtmp));
    177 		} else {
    178 			tmp[newlen++] = '@';
    179 			if (termchar == VC)
    180 				tmp[newlen++] = VO;
    181 		}
    182 	}
    183 
    184 	if (change) {
    185 		memcpy(cp, tmp, newlen);
    186 		*len = newlen;
    187 	}
    188 	PNBUF_PUT(tmp);
    189 
    190 	return (0);
    191 }
    192 
    193 #undef VNL
    194 #undef VO
    195 #undef VC
    196 #undef MATCH
    197 #undef SUBSTITUTE
    198 
    199 int
    200 pathname_get(const char *dirp, enum uio_seg segflg, pathname_t *path)
    201 {
    202 	int error;
    203 
    204 	if (dirp == NULL)
    205 		return (EFAULT);
    206 
    207 	*path = malloc(sizeof(struct pathname_internal), M_TEMP,
    208 	    M_ZERO|M_WAITOK);
    209 
    210 	if (segflg == UIO_USERSPACE) {
    211 		(*path)->pathbuf = PNBUF_GET();
    212 		error = copyinstr(dirp, (*path)->pathbuf, MAXPATHLEN,
    213 		    NULL);
    214 		if (error) {
    215 			PNBUF_PUT((*path)->pathbuf);
    216 			free(path, M_TEMP);
    217 			return (error);
    218 		}
    219 		(*path)->needfree = TRUE;
    220 	} else {
    221 		(*path)->pathbuf = __UNCONST(dirp);
    222 		(*path)->needfree = FALSE;
    223 	}
    224 
    225 	return (0);
    226 }
    227 
    228 const char *
    229 pathname_path(pathname_t path)
    230 {
    231 	KASSERT(path != NULL);
    232 	return (path->pathbuf);
    233 }
    234 
    235 void
    236 pathname_put(pathname_t path)
    237 {
    238 	if (path != NULL) {
    239 		if (path->pathbuf != NULL && path->needfree)
    240 			PNBUF_PUT(path->pathbuf);
    241 		free(path, M_TEMP);
    242 	}
    243 }
    244 
    245 /*
    246  * Convert a pathname into a pointer to a locked vnode.
    247  *
    248  * The FOLLOW flag is set when symbolic links are to be followed
    249  * when they occur at the end of the name translation process.
    250  * Symbolic links are always followed for all other pathname
    251  * components other than the last.
    252  *
    253  * The segflg defines whether the name is to be copied from user
    254  * space or kernel space.
    255  *
    256  * Overall outline of namei:
    257  *
    258  *	copy in name
    259  *	get starting directory
    260  *	while (!done && !error) {
    261  *		call lookup to search path.
    262  *		if symbolic link, massage name in buffer and continue
    263  *	}
    264  */
    265 int
    266 namei(struct nameidata *ndp)
    267 {
    268 	struct cwdinfo *cwdi;		/* pointer to cwd state */
    269 	char *cp;			/* pointer into pathname argument */
    270 	struct vnode *dp;		/* the directory we are searching */
    271 	struct iovec aiov;		/* uio for reading symbolic links */
    272 	struct uio auio;
    273 	int error, linklen;
    274 	struct componentname *cnp = &ndp->ni_cnd;
    275 
    276 #ifdef DIAGNOSTIC
    277 	if (!cnp->cn_cred || !cnp->cn_lwp)
    278 		panic("namei: bad cred/proc");
    279 	if (cnp->cn_nameiop & (~OPMASK))
    280 		panic("namei: nameiop contaminated with flags");
    281 	if (cnp->cn_flags & OPMASK)
    282 		panic("namei: flags contaminated with nameiops");
    283 #endif
    284 	cwdi = cnp->cn_lwp->l_proc->p_cwdi;
    285 
    286 	/*
    287 	 * Get a buffer for the name to be translated, and copy the
    288 	 * name into the buffer.
    289 	 */
    290 	if ((cnp->cn_flags & HASBUF) == 0)
    291 		cnp->cn_pnbuf = PNBUF_GET();
    292 	if (ndp->ni_segflg == UIO_SYSSPACE)
    293 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf,
    294 			    MAXPATHLEN, &ndp->ni_pathlen);
    295 	else
    296 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
    297 			    MAXPATHLEN, &ndp->ni_pathlen);
    298 
    299 	/*
    300 	 * POSIX.1 requirement: "" is not a valid file name.
    301 	 */
    302 	if (!error && ndp->ni_pathlen == 1)
    303 		error = ENOENT;
    304 
    305 	if (error) {
    306 		PNBUF_PUT(cnp->cn_pnbuf);
    307 		ndp->ni_vp = NULL;
    308 		return (error);
    309 	}
    310 	ndp->ni_loopcnt = 0;
    311 
    312 #ifdef KTRACE
    313 	if (KTRPOINT(cnp->cn_lwp->l_proc, KTR_NAMEI))
    314 		ktrnamei(cnp->cn_lwp, cnp->cn_pnbuf);
    315 #endif
    316 #ifdef SYSTRACE
    317 	if (ISSET(cnp->cn_lwp->l_proc->p_flag, P_SYSTRACE))
    318 		systrace_namei(ndp);
    319 #endif
    320 
    321 	/*
    322 	 * Get starting point for the translation.
    323 	 */
    324 	if ((ndp->ni_rootdir = cwdi->cwdi_rdir) == NULL)
    325 		ndp->ni_rootdir = rootvnode;
    326 	/*
    327 	 * Check if starting from root directory or current directory.
    328 	 */
    329 	if (cnp->cn_pnbuf[0] == '/') {
    330 		dp = ndp->ni_rootdir;
    331 		VREF(dp);
    332 	} else {
    333 		dp = cwdi->cwdi_cdir;
    334 		VREF(dp);
    335 	}
    336 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    337 	for (;;) {
    338 		if (!dp->v_mount) {
    339 			/* Give up if the directory is no longer mounted */
    340 			vput(dp);
    341 			PNBUF_PUT(cnp->cn_pnbuf);
    342 			return (ENOENT);
    343 		}
    344 		cnp->cn_nameptr = cnp->cn_pnbuf;
    345 		ndp->ni_startdir = dp;
    346 		error = lookup(ndp);
    347 		if (error != 0) {
    348 			if (ndp->ni_dvp) {
    349 				vput(ndp->ni_dvp);
    350 			}
    351 			PNBUF_PUT(cnp->cn_pnbuf);
    352 			return (error);
    353 		}
    354 
    355 		/*
    356 		 * Check for symbolic link
    357 		 */
    358 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
    359 			if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp) {
    360 				if (ndp->ni_dvp == ndp->ni_vp) {
    361 					vrele(ndp->ni_dvp);
    362 				} else {
    363 					vput(ndp->ni_dvp);
    364 				}
    365 			}
    366 			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
    367 				PNBUF_PUT(cnp->cn_pnbuf);
    368 			else
    369 				cnp->cn_flags |= HASBUF;
    370 			return (0);
    371 		}
    372 
    373 		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
    374 			error = ELOOP;
    375 			break;
    376 		}
    377 		if (ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
    378 			error = VOP_ACCESS(ndp->ni_vp, VEXEC, cnp->cn_cred,
    379 			    cnp->cn_lwp);
    380 			if (error != 0)
    381 				break;
    382 		}
    383 		if (ndp->ni_pathlen > 1)
    384 			cp = PNBUF_GET();
    385 		else
    386 			cp = cnp->cn_pnbuf;
    387 		aiov.iov_base = cp;
    388 		aiov.iov_len = MAXPATHLEN;
    389 		auio.uio_iov = &aiov;
    390 		auio.uio_iovcnt = 1;
    391 		auio.uio_offset = 0;
    392 		auio.uio_rw = UIO_READ;
    393 		auio.uio_resid = MAXPATHLEN;
    394 		UIO_SETUP_SYSSPACE(&auio);
    395 		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
    396 		if (error) {
    397 badlink:
    398 			if (ndp->ni_pathlen > 1)
    399 				PNBUF_PUT(cp);
    400 			break;
    401 		}
    402 		linklen = MAXPATHLEN - auio.uio_resid;
    403 		if (linklen == 0) {
    404 			error = ENOENT;
    405 			goto badlink;
    406 		}
    407 
    408 		/*
    409 		 * Do symlink substitution, if appropriate, and
    410 		 * check length for potential overflow.
    411 		 */
    412 		if ((vfs_magiclinks &&
    413 		     symlink_magic(cnp->cn_lwp->l_proc, cp, &linklen)) ||
    414 		    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
    415 			error = ENAMETOOLONG;
    416 			goto badlink;
    417 		}
    418 		if (ndp->ni_pathlen > 1) {
    419 			memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
    420 			PNBUF_PUT(cnp->cn_pnbuf);
    421 			cnp->cn_pnbuf = cp;
    422 		} else
    423 			cnp->cn_pnbuf[linklen] = '\0';
    424 		ndp->ni_pathlen += linklen;
    425 		vput(ndp->ni_vp);
    426 		dp = ndp->ni_dvp;
    427 
    428 		/*
    429 		 * Check if root directory should replace current directory.
    430 		 */
    431 		if (cnp->cn_pnbuf[0] == '/') {
    432 			vput(dp);
    433 			dp = ndp->ni_rootdir;
    434 			VREF(dp);
    435 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    436 		}
    437 	}
    438 	KASSERT(ndp->ni_dvp != ndp->ni_vp);
    439 	vput(ndp->ni_dvp);
    440 	vput(ndp->ni_vp);
    441 	ndp->ni_vp = NULL;
    442 	PNBUF_PUT(cnp->cn_pnbuf);
    443 	return (error);
    444 }
    445 
    446 /*
    447  * Determine the namei hash (for cn_hash) for name.
    448  * If *ep != NULL, hash from name to ep-1.
    449  * If *ep == NULL, hash from name until the first NUL or '/', and
    450  * return the location of this termination character in *ep.
    451  *
    452  * This function returns an equivalent hash to the MI hash32_strn().
    453  * The latter isn't used because in the *ep == NULL case, determining
    454  * the length of the string to the first NUL or `/' and then calling
    455  * hash32_strn() involves unnecessary double-handling of the data.
    456  */
    457 uint32_t
    458 namei_hash(const char *name, const char **ep)
    459 {
    460 	uint32_t	hash;
    461 
    462 	hash = HASH32_STR_INIT;
    463 	if (*ep != NULL) {
    464 		for (; name < *ep; name++)
    465 			hash = hash * 33 + *(const uint8_t *)name;
    466 	} else {
    467 		for (; *name != '\0' && *name != '/'; name++)
    468 			hash = hash * 33 + *(const uint8_t *)name;
    469 		*ep = name;
    470 	}
    471 	return (hash + (hash >> 5));
    472 }
    473 
    474 /*
    475  * Search a pathname.
    476  * This is a very central and rather complicated routine.
    477  *
    478  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
    479  * The starting directory is taken from ni_startdir. The pathname is
    480  * descended until done, or a symbolic link is encountered. The variable
    481  * ni_more is clear if the path is completed; it is set to one if a
    482  * symbolic link needing interpretation is encountered.
    483  *
    484  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
    485  * whether the name is to be looked up, created, renamed, or deleted.
    486  * When CREATE, RENAME, or DELETE is specified, information usable in
    487  * creating, renaming, or deleting a directory entry may be calculated.
    488  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
    489  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
    490  * returned unlocked. Otherwise the parent directory is not returned. If
    491  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
    492  * the target is returned locked, otherwise it is returned unlocked.
    493  * When creating or renaming and LOCKPARENT is specified, the target may not
    494  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
    495  *
    496  * Overall outline of lookup:
    497  *
    498  * dirloop:
    499  *	identify next component of name at ndp->ni_ptr
    500  *	handle degenerate case where name is null string
    501  *	if .. and crossing mount points and on mounted filesys, find parent
    502  *	call VOP_LOOKUP routine for next component name
    503  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
    504  *	    component vnode returned in ni_vp (if it exists), locked.
    505  *	if result vnode is mounted on and crossing mount points,
    506  *	    find mounted on vnode
    507  *	if more components of name, do next level at dirloop
    508  *	return the answer in ni_vp, locked if LOCKLEAF set
    509  *	    if LOCKPARENT set, return locked parent in ni_dvp
    510  *	    if WANTPARENT set, return unlocked parent in ni_dvp
    511  */
    512 int
    513 lookup(struct nameidata *ndp)
    514 {
    515 	const char *cp;			/* pointer into pathname argument */
    516 	struct vnode *dp = 0;		/* the directory we are searching */
    517 	struct vnode *tdp;		/* saved dp */
    518 	struct mount *mp;		/* mount table entry */
    519 	int docache;			/* == 0 do not cache last component */
    520 	int rdonly;			/* lookup read-only flag bit */
    521 	int error = 0;
    522 	int slashes;
    523 	struct componentname *cnp = &ndp->ni_cnd;
    524 	struct lwp *l = cnp->cn_lwp;
    525 
    526 	/*
    527 	 * Setup: break out flag bits into variables.
    528 	 */
    529 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
    530 	if (cnp->cn_nameiop != CREATE)
    531 		docache = 0;
    532 	rdonly = cnp->cn_flags & RDONLY;
    533 	ndp->ni_dvp = NULL;
    534 	cnp->cn_flags &= ~ISSYMLINK;
    535 	dp = ndp->ni_startdir;
    536 	ndp->ni_startdir = NULLVP;
    537 
    538 	/*
    539 	 * If we have a leading string of slashes, remove them, and just make
    540 	 * sure the current node is a directory.
    541 	 */
    542 	cp = cnp->cn_nameptr;
    543 	if (*cp == '/') {
    544 		do {
    545 			cp++;
    546 		} while (*cp == '/');
    547 		ndp->ni_pathlen -= cp - cnp->cn_nameptr;
    548 		cnp->cn_nameptr = cp;
    549 
    550 		if (dp->v_type != VDIR) {
    551 			error = ENOTDIR;
    552 			vput(dp);
    553 			goto bad;
    554 		}
    555 
    556 		/*
    557 		 * If we've exhausted the path name, then just return the
    558 		 * current node.  If the caller requested the parent node (i.e.
    559 		 * it's a CREATE, DELETE, or RENAME), and we don't have one
    560 		 * (because this is the root directory), then we must fail.
    561 		 */
    562 		if (cnp->cn_nameptr[0] == '\0') {
    563 			if (ndp->ni_dvp == NULL && cnp->cn_nameiop != LOOKUP) {
    564 				switch (cnp->cn_nameiop) {
    565 				case CREATE:
    566 					error = EEXIST;
    567 					break;
    568 				case DELETE:
    569 				case RENAME:
    570 					error = EBUSY;
    571 					break;
    572 				default:
    573 					KASSERT(0);
    574 				}
    575 				vput(dp);
    576 				goto bad;
    577 			}
    578 			ndp->ni_vp = dp;
    579 			cnp->cn_flags |= ISLASTCN;
    580 			goto terminal;
    581 		}
    582 	}
    583 
    584 dirloop:
    585 	/*
    586 	 * Search a new directory.
    587 	 *
    588 	 * The cn_hash value is for use by vfs_cache.
    589 	 * The last component of the filename is left accessible via
    590 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    591 	 * the name set the SAVENAME flag. When done, they assume
    592 	 * responsibility for freeing the pathname buffer.
    593 	 *
    594 	 * At this point, our only vnode state is that "dp" is held and locked.
    595 	 */
    596 	cnp->cn_consume = 0;
    597 	cp = NULL;
    598 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
    599 	cnp->cn_namelen = cp - cnp->cn_nameptr;
    600 	if (cnp->cn_namelen > NAME_MAX) {
    601 		vput(dp);
    602 		error = ENAMETOOLONG;
    603 		ndp->ni_dvp = NULL;
    604 		goto bad;
    605 	}
    606 #ifdef NAMEI_DIAGNOSTIC
    607 	{ char c = *cp;
    608 	*(char *)cp = '\0';
    609 	printf("{%s}: ", cnp->cn_nameptr);
    610 	*(char *)cp = c; }
    611 #endif /* NAMEI_DIAGNOSTIC */
    612 	ndp->ni_pathlen -= cnp->cn_namelen;
    613 	ndp->ni_next = cp;
    614 	/*
    615 	 * If this component is followed by a slash, then move the pointer to
    616 	 * the next component forward, and remember that this component must be
    617 	 * a directory.
    618 	 */
    619 	if (*cp == '/') {
    620 		do {
    621 			cp++;
    622 		} while (*cp == '/');
    623 		slashes = cp - ndp->ni_next;
    624 		ndp->ni_pathlen -= slashes;
    625 		ndp->ni_next = cp;
    626 		cnp->cn_flags |= REQUIREDIR;
    627 	} else {
    628 		slashes = 0;
    629 		cnp->cn_flags &= ~REQUIREDIR;
    630 	}
    631 	/*
    632 	 * We do special processing on the last component, whether or not it's
    633 	 * a directory.  Cache all intervening lookups, but not the final one.
    634 	 */
    635 	if (*cp == '\0') {
    636 		if (docache)
    637 			cnp->cn_flags |= MAKEENTRY;
    638 		else
    639 			cnp->cn_flags &= ~MAKEENTRY;
    640 		cnp->cn_flags |= ISLASTCN;
    641 	} else {
    642 		cnp->cn_flags |= MAKEENTRY;
    643 		cnp->cn_flags &= ~ISLASTCN;
    644 	}
    645 	if (cnp->cn_namelen == 2 &&
    646 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
    647 		cnp->cn_flags |= ISDOTDOT;
    648 	else
    649 		cnp->cn_flags &= ~ISDOTDOT;
    650 
    651 	/*
    652 	 * Handle "..": two special cases.
    653 	 * 1. If at root directory (e.g. after chroot)
    654 	 *    or at absolute root directory
    655 	 *    then ignore it so can't get out.
    656 	 * 1a. If we have somehow gotten out of a jail, warn
    657 	 *    and also ignore it so we can't get farther out.
    658 	 * 2. If this vnode is the root of a mounted
    659 	 *    filesystem, then replace it with the
    660 	 *    vnode which was mounted on so we take the
    661 	 *    .. in the other file system.
    662 	 */
    663 	if (cnp->cn_flags & ISDOTDOT) {
    664 		struct proc *p = l->l_proc;
    665 
    666 		for (;;) {
    667 			if (dp == ndp->ni_rootdir || dp == rootvnode) {
    668 				ndp->ni_dvp = dp;
    669 				ndp->ni_vp = dp;
    670 				VREF(dp);
    671 				goto nextname;
    672 			}
    673 			if (ndp->ni_rootdir != rootvnode) {
    674 				int retval;
    675 
    676 				VOP_UNLOCK(dp, 0);
    677 				retval = vn_isunder(dp, ndp->ni_rootdir, l);
    678 				vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    679 				if (!retval) {
    680 				    /* Oops! We got out of jail! */
    681 				    log(LOG_WARNING,
    682 					"chrooted pid %d uid %d (%s) "
    683 					"detected outside of its chroot\n",
    684 					p->p_pid, kauth_cred_geteuid(l->l_cred),
    685 					p->p_comm);
    686 				    /* Put us at the jail root. */
    687 				    vput(dp);
    688 				    dp = ndp->ni_rootdir;
    689 				    ndp->ni_dvp = dp;
    690 				    ndp->ni_vp = dp;
    691 				    VREF(dp);
    692 				    VREF(dp);
    693 				    vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    694 				    goto nextname;
    695 				}
    696 			}
    697 			if ((dp->v_flag & VROOT) == 0 ||
    698 			    (cnp->cn_flags & NOCROSSMOUNT))
    699 				break;
    700 			tdp = dp;
    701 			dp = dp->v_mount->mnt_vnodecovered;
    702 			vput(tdp);
    703 			VREF(dp);
    704 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    705 		}
    706 	}
    707 
    708 	/*
    709 	 * We now have a segment name to search for, and a directory to search.
    710 	 * Again, our only vnode state is that "dp" is held and locked.
    711 	 */
    712 unionlookup:
    713 	ndp->ni_dvp = dp;
    714 	ndp->ni_vp = NULL;
    715 	error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
    716 	if (error != 0) {
    717 #ifdef DIAGNOSTIC
    718 		if (ndp->ni_vp != NULL)
    719 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
    720 #endif /* DIAGNOSTIC */
    721 #ifdef NAMEI_DIAGNOSTIC
    722 		printf("not found\n");
    723 #endif /* NAMEI_DIAGNOSTIC */
    724 		if ((error == ENOENT) &&
    725 		    (dp->v_flag & VROOT) &&
    726 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
    727 			tdp = dp;
    728 			dp = dp->v_mount->mnt_vnodecovered;
    729 			vput(tdp);
    730 			VREF(dp);
    731 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    732 			goto unionlookup;
    733 		}
    734 
    735 		if (error != EJUSTRETURN)
    736 			goto bad;
    737 
    738 		/*
    739 		 * If this was not the last component, or there were trailing
    740 		 * slashes, and we are not going to create a directory,
    741 		 * then the name must exist.
    742 		 */
    743 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
    744 			error = ENOENT;
    745 			goto bad;
    746 		}
    747 
    748 		/*
    749 		 * If creating and at end of pathname, then can consider
    750 		 * allowing file to be created.
    751 		 */
    752 		if (rdonly) {
    753 			error = EROFS;
    754 			goto bad;
    755 		}
    756 
    757 		/*
    758 		 * We return with ni_vp NULL to indicate that the entry
    759 		 * doesn't currently exist, leaving a pointer to the
    760 		 * (possibly locked) directory vnode in ndp->ni_dvp.
    761 		 */
    762 		if (cnp->cn_flags & SAVESTART) {
    763 			ndp->ni_startdir = ndp->ni_dvp;
    764 			VREF(ndp->ni_startdir);
    765 		}
    766 		return (0);
    767 	}
    768 #ifdef NAMEI_DIAGNOSTIC
    769 	printf("found\n");
    770 #endif /* NAMEI_DIAGNOSTIC */
    771 
    772 	/*
    773 	 * Take into account any additional components consumed by the
    774 	 * underlying filesystem.  This will include any trailing slashes after
    775 	 * the last component consumed.
    776 	 */
    777 	if (cnp->cn_consume > 0) {
    778 		ndp->ni_pathlen -= cnp->cn_consume - slashes;
    779 		ndp->ni_next += cnp->cn_consume - slashes;
    780 		cnp->cn_consume = 0;
    781 		if (ndp->ni_next[0] == '\0')
    782 			cnp->cn_flags |= ISLASTCN;
    783 	}
    784 
    785 	dp = ndp->ni_vp;
    786 
    787 	/*
    788 	 * "dp" and "ndp->ni_dvp" are both locked and held,
    789 	 * and may be the same vnode.
    790 	 */
    791 
    792 	/*
    793 	 * Check to see if the vnode has been mounted on;
    794 	 * if so find the root of the mounted file system.
    795 	 */
    796 	while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
    797 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
    798 		if (vfs_busy(mp, 0, 0))
    799 			continue;
    800 
    801 		KASSERT(ndp->ni_dvp != dp);
    802 		VOP_UNLOCK(ndp->ni_dvp, 0);
    803 		vput(dp);
    804 		error = VFS_ROOT(mp, &tdp);
    805 		vfs_unbusy(mp);
    806 		if (error) {
    807 			vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
    808 			goto bad;
    809 		}
    810 		VOP_UNLOCK(tdp, 0);
    811 		ndp->ni_vp = dp = tdp;
    812 		vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
    813 		vn_lock(ndp->ni_vp, LK_EXCLUSIVE | LK_RETRY);
    814 	}
    815 
    816 	/*
    817 	 * Check for symbolic link.  Back up over any slashes that we skipped,
    818 	 * as we will need them again.
    819 	 */
    820 	if ((dp->v_type == VLNK) && (cnp->cn_flags & (FOLLOW|REQUIREDIR))) {
    821 		ndp->ni_pathlen += slashes;
    822 		ndp->ni_next -= slashes;
    823 		cnp->cn_flags |= ISSYMLINK;
    824 		return (0);
    825 	}
    826 
    827 	/*
    828 	 * Check for directory, if the component was followed by a series of
    829 	 * slashes.
    830 	 */
    831 	if ((dp->v_type != VDIR) && (cnp->cn_flags & REQUIREDIR)) {
    832 		error = ENOTDIR;
    833 		KASSERT(dp != ndp->ni_dvp);
    834 		vput(dp);
    835 		goto bad;
    836 	}
    837 
    838 nextname:
    839 
    840 	/*
    841 	 * Not a symbolic link.  If this was not the last component, then
    842 	 * continue at the next component, else return.
    843 	 */
    844 	if (!(cnp->cn_flags & ISLASTCN)) {
    845 		cnp->cn_nameptr = ndp->ni_next;
    846 		if (ndp->ni_dvp == dp) {
    847 			vrele(ndp->ni_dvp);
    848 		} else {
    849 			vput(ndp->ni_dvp);
    850 		}
    851 		goto dirloop;
    852 	}
    853 
    854 terminal:
    855 
    856 	/*
    857 	 * Disallow directory write attempts on read-only file systems.
    858 	 */
    859 	if (rdonly &&
    860 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
    861 
    862 		/*
    863 		 * Disallow directory write attempts on read-only
    864 		 * file systems.
    865 		 */
    866 		error = EROFS;
    867 		if (dp != ndp->ni_dvp) {
    868 			vput(dp);
    869 		}
    870 		goto bad;
    871 	}
    872 	if (ndp->ni_dvp != NULL) {
    873 		if (cnp->cn_flags & SAVESTART) {
    874 			ndp->ni_startdir = ndp->ni_dvp;
    875 			VREF(ndp->ni_startdir);
    876 		}
    877 	}
    878 	if ((cnp->cn_flags & LOCKLEAF) == 0) {
    879 		VOP_UNLOCK(dp, 0);
    880 	}
    881 	return (0);
    882 
    883 bad:
    884 	ndp->ni_vp = NULL;
    885 	return (error);
    886 }
    887 
    888 /*
    889  * Reacquire a path name component.
    890  * dvp is locked on entry and exit.
    891  * *vpp is locked on exit unless it's NULL.
    892  */
    893 int
    894 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
    895 {
    896 	struct vnode *dp = 0;		/* the directory we are searching */
    897 	int rdonly;			/* lookup read-only flag bit */
    898 	int error = 0;
    899 #ifdef DEBUG
    900 	u_long newhash;			/* DEBUG: check name hash */
    901 	const char *cp;			/* DEBUG: check name ptr/len */
    902 #endif /* DEBUG */
    903 
    904 	/*
    905 	 * Setup: break out flag bits into variables.
    906 	 */
    907 	rdonly = cnp->cn_flags & RDONLY;
    908 	cnp->cn_flags &= ~ISSYMLINK;
    909 	dp = dvp;
    910 
    911 /* dirloop: */
    912 	/*
    913 	 * Search a new directory.
    914 	 *
    915 	 * The cn_hash value is for use by vfs_cache.
    916 	 * The last component of the filename is left accessible via
    917 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    918 	 * the name set the SAVENAME flag. When done, they assume
    919 	 * responsibility for freeing the pathname buffer.
    920 	 */
    921 #ifdef DEBUG
    922 	cp = NULL;
    923 	newhash = namei_hash(cnp->cn_nameptr, &cp);
    924 	if (newhash != cnp->cn_hash)
    925 		panic("relookup: bad hash");
    926 	if (cnp->cn_namelen != cp - cnp->cn_nameptr)
    927 		panic("relookup: bad len");
    928 	while (*cp == '/')
    929 		cp++;
    930 	if (*cp != 0)
    931 		panic("relookup: not last component");
    932 #endif /* DEBUG */
    933 #ifdef NAMEI_DIAGNOSTIC
    934 	printf("{%s}: ", cnp->cn_nameptr);
    935 #endif /* NAMEI_DIAGNOSTIC */
    936 
    937 	/*
    938 	 * Check for degenerate name (e.g. / or "")
    939 	 * which is a way of talking about a directory,
    940 	 * e.g. like "/." or ".".
    941 	 */
    942 	if (cnp->cn_nameptr[0] == '\0')
    943 		panic("relookup: null name");
    944 
    945 	if (cnp->cn_flags & ISDOTDOT)
    946 		panic("relookup: lookup on dot-dot");
    947 
    948 	/*
    949 	 * We now have a segment name to search for, and a directory to search.
    950 	 */
    951 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
    952 #ifdef DIAGNOSTIC
    953 		if (*vpp != NULL)
    954 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
    955 #endif
    956 		if (error != EJUSTRETURN)
    957 			goto bad;
    958 
    959 		/*
    960 		 * If creating and at end of pathname, then can consider
    961 		 * allowing file to be created.
    962 		 */
    963 		if (rdonly) {
    964 			error = EROFS;
    965 			goto bad;
    966 		}
    967 
    968 		/* ASSERT(dvp == ndp->ni_startdir) */
    969 		if (cnp->cn_flags & SAVESTART)
    970 			VREF(dvp);
    971 
    972 		/*
    973 		 * We return with ni_vp NULL to indicate that the entry
    974 		 * doesn't currently exist, leaving a pointer to the
    975 		 * locked directory vnode in ndp->ni_dvp.
    976 		 */
    977 		return (0);
    978 	}
    979 	dp = *vpp;
    980 
    981 #ifdef DIAGNOSTIC
    982 	/*
    983 	 * Check for symbolic link
    984 	 */
    985 	if (dp->v_type == VLNK && (cnp->cn_flags & FOLLOW))
    986 		panic("relookup: symlink found");
    987 #endif
    988 
    989 	/*
    990 	 * Check for read-only file systems.
    991 	 */
    992 	if (rdonly &&
    993 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
    994 		error = EROFS;
    995 		goto bad;
    996 	}
    997 	/* ASSERT(dvp == ndp->ni_startdir) */
    998 	if (cnp->cn_flags & SAVESTART)
    999 		VREF(dvp);
   1000 	if ((cnp->cn_flags & LOCKLEAF) == 0)
   1001 		VOP_UNLOCK(dp, 0);
   1002 	return (0);
   1003 
   1004 bad:
   1005 	vput(dp);
   1006 	*vpp = NULL;
   1007 	return (error);
   1008 }
   1009