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