Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.126
      1 /*	$NetBSD: vfs_lookup.c,v 1.126 2010/12/17 22:34:04 yamt 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.126 2010/12/17 22:34:04 yamt Exp $");
     41 
     42 #include "opt_magiclinks.h"
     43 
     44 #include <sys/param.h>
     45 #include <sys/systm.h>
     46 #include <sys/kernel.h>
     47 #include <sys/syslimits.h>
     48 #include <sys/time.h>
     49 #include <sys/namei.h>
     50 #include <sys/vnode.h>
     51 #include <sys/mount.h>
     52 #include <sys/errno.h>
     53 #include <sys/filedesc.h>
     54 #include <sys/hash.h>
     55 #include <sys/proc.h>
     56 #include <sys/syslog.h>
     57 #include <sys/kauth.h>
     58 #include <sys/ktrace.h>
     59 
     60 #ifndef MAGICLINKS
     61 #define MAGICLINKS 0
     62 #endif
     63 
     64 int vfs_magiclinks = MAGICLINKS;
     65 
     66 pool_cache_t pnbuf_cache;	/* pathname buffer cache */
     67 
     68 /*
     69  * Substitute replacement text for 'magic' strings in symlinks.
     70  * Returns 0 if successful, and returns non-zero if an error
     71  * occurs.  (Currently, the only possible error is running out
     72  * of temporary pathname space.)
     73  *
     74  * Looks for "@<string>" and "@<string>/", where <string> is a
     75  * recognized 'magic' string.  Replaces the "@<string>" with the
     76  * appropriate replacement text.  (Note that in some cases the
     77  * replacement text may have zero length.)
     78  *
     79  * This would have been table driven, but the variance in
     80  * replacement strings (and replacement string lengths) made
     81  * that impractical.
     82  */
     83 #define	VNL(x)							\
     84 	(sizeof(x) - 1)
     85 
     86 #define	VO	'{'
     87 #define	VC	'}'
     88 
     89 #define	MATCH(str)						\
     90 	((termchar == '/' && i + VNL(str) == *len) ||		\
     91 	 (i + VNL(str) < *len &&				\
     92 	  cp[i + VNL(str)] == termchar)) &&			\
     93 	!strncmp((str), &cp[i], VNL(str))
     94 
     95 #define	SUBSTITUTE(m, s, sl)					\
     96 	if ((newlen + (sl)) >= MAXPATHLEN)			\
     97 		return 1;					\
     98 	i += VNL(m);						\
     99 	if (termchar != '/')					\
    100 		i++;						\
    101 	(void)memcpy(&tmp[newlen], (s), (sl));			\
    102 	newlen += (sl);						\
    103 	change = 1;						\
    104 	termchar = '/';
    105 
    106 static int
    107 symlink_magic(struct proc *p, char *cp, size_t *len)
    108 {
    109 	char *tmp;
    110 	size_t change, i, newlen, slen;
    111 	char termchar = '/';
    112 	char idtmp[11]; /* enough for 32 bit *unsigned* integer */
    113 
    114 
    115 	tmp = PNBUF_GET();
    116 	for (change = i = newlen = 0; i < *len; ) {
    117 		if (cp[i] != '@') {
    118 			tmp[newlen++] = cp[i++];
    119 			continue;
    120 		}
    121 
    122 		i++;
    123 
    124 		/* Check for @{var} syntax. */
    125 		if (cp[i] == VO) {
    126 			termchar = VC;
    127 			i++;
    128 		}
    129 
    130 		/*
    131 		 * The following checks should be ordered according
    132 		 * to frequency of use.
    133 		 */
    134 		if (MATCH("machine_arch")) {
    135 			slen = VNL(MACHINE_ARCH);
    136 			SUBSTITUTE("machine_arch", MACHINE_ARCH, slen);
    137 		} else if (MATCH("machine")) {
    138 			slen = VNL(MACHINE);
    139 			SUBSTITUTE("machine", MACHINE, slen);
    140 		} else if (MATCH("hostname")) {
    141 			SUBSTITUTE("hostname", hostname, hostnamelen);
    142 		} else if (MATCH("osrelease")) {
    143 			slen = strlen(osrelease);
    144 			SUBSTITUTE("osrelease", osrelease, slen);
    145 		} else if (MATCH("emul")) {
    146 			slen = strlen(p->p_emul->e_name);
    147 			SUBSTITUTE("emul", p->p_emul->e_name, slen);
    148 		} else if (MATCH("kernel_ident")) {
    149 			slen = strlen(kernel_ident);
    150 			SUBSTITUTE("kernel_ident", kernel_ident, slen);
    151 		} else if (MATCH("domainname")) {
    152 			SUBSTITUTE("domainname", domainname, domainnamelen);
    153 		} else if (MATCH("ostype")) {
    154 			slen = strlen(ostype);
    155 			SUBSTITUTE("ostype", ostype, slen);
    156 		} else if (MATCH("uid")) {
    157 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    158 			    kauth_cred_geteuid(kauth_cred_get()));
    159 			SUBSTITUTE("uid", idtmp, slen);
    160 		} else if (MATCH("ruid")) {
    161 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    162 			    kauth_cred_getuid(kauth_cred_get()));
    163 			SUBSTITUTE("ruid", idtmp, slen);
    164 		} else if (MATCH("gid")) {
    165 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    166 			    kauth_cred_getegid(kauth_cred_get()));
    167 			SUBSTITUTE("gid", idtmp, slen);
    168 		} else if (MATCH("rgid")) {
    169 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    170 			    kauth_cred_getgid(kauth_cred_get()));
    171 			SUBSTITUTE("rgid", idtmp, slen);
    172 		} else {
    173 			tmp[newlen++] = '@';
    174 			if (termchar == VC)
    175 				tmp[newlen++] = VO;
    176 		}
    177 	}
    178 
    179 	if (change) {
    180 		(void)memcpy(cp, tmp, newlen);
    181 		*len = newlen;
    182 	}
    183 	PNBUF_PUT(tmp);
    184 
    185 	return 0;
    186 }
    187 
    188 #undef VNL
    189 #undef VO
    190 #undef VC
    191 #undef MATCH
    192 #undef SUBSTITUTE
    193 
    194 ////////////////////////////////////////////////////////////
    195 
    196 /*
    197  * Sealed abstraction for pathnames.
    198  *
    199  * System-call-layer level code that is going to call namei should
    200  * first create a pathbuf and adjust all the bells and whistles on it
    201  * as needed by context
    202  */
    203 
    204 struct pathbuf {
    205 	char *pb_path;
    206 	char *pb_pathcopy;
    207 	unsigned pb_pathcopyuses;
    208 };
    209 
    210 static struct pathbuf *
    211 pathbuf_create_raw(void)
    212 {
    213 	struct pathbuf *pb;
    214 
    215 	pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
    216 	if (pb == NULL) {
    217 		return NULL;
    218 	}
    219 	pb->pb_path = PNBUF_GET();
    220 	if (pb->pb_path == NULL) {
    221 		kmem_free(pb, sizeof(*pb));
    222 		return NULL;
    223 	}
    224 	pb->pb_pathcopy = NULL;
    225 	pb->pb_pathcopyuses = 0;
    226 	return pb;
    227 }
    228 
    229 void
    230 pathbuf_destroy(struct pathbuf *pb)
    231 {
    232 	KASSERT(pb->pb_pathcopyuses == 0);
    233 	KASSERT(pb->pb_pathcopy == NULL);
    234 	PNBUF_PUT(pb->pb_path);
    235 	kmem_free(pb, sizeof(*pb));
    236 }
    237 
    238 struct pathbuf *
    239 pathbuf_assimilate(char *pnbuf)
    240 {
    241 	struct pathbuf *pb;
    242 
    243 	pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
    244 	if (pb == NULL) {
    245 		return NULL;
    246 	}
    247 	pb->pb_path = pnbuf;
    248 	pb->pb_pathcopy = NULL;
    249 	pb->pb_pathcopyuses = 0;
    250 	return pb;
    251 }
    252 
    253 struct pathbuf *
    254 pathbuf_create(const char *path)
    255 {
    256 	struct pathbuf *pb;
    257 	int error;
    258 
    259 	pb = pathbuf_create_raw();
    260 	if (pb == NULL) {
    261 		return NULL;
    262 	}
    263 	error = copystr(path, pb->pb_path, PATH_MAX, NULL);
    264 	if (error != 0) {
    265 		KASSERT(!"kernel path too long in pathbuf_create");
    266 		/* make sure it's null-terminated, just in case */
    267 		pb->pb_path[PATH_MAX-1] = '\0';
    268 	}
    269 	return pb;
    270 }
    271 
    272 int
    273 pathbuf_copyin(const char *userpath, struct pathbuf **ret)
    274 {
    275 	struct pathbuf *pb;
    276 	int error;
    277 
    278 	pb = pathbuf_create_raw();
    279 	if (pb == NULL) {
    280 		return ENOMEM;
    281 	}
    282 	error = copyinstr(userpath, pb->pb_path, PATH_MAX, NULL);
    283 	if (error) {
    284 		pathbuf_destroy(pb);
    285 		return error;
    286 	}
    287 	*ret = pb;
    288 	return 0;
    289 }
    290 
    291 /*
    292  * XXX should not exist
    293  */
    294 int
    295 pathbuf_maybe_copyin(const char *path, enum uio_seg seg, struct pathbuf **ret)
    296 {
    297 	if (seg == UIO_USERSPACE) {
    298 		return pathbuf_copyin(path, ret);
    299 	} else {
    300 		*ret = pathbuf_create(path);
    301 		if (*ret == NULL) {
    302 			return ENOMEM;
    303 		}
    304 		return 0;
    305 	}
    306 }
    307 
    308 /*
    309  * Get a copy of the path buffer as it currently exists. If this is
    310  * called after namei starts the results may be arbitrary.
    311  */
    312 void
    313 pathbuf_copystring(const struct pathbuf *pb, char *buf, size_t maxlen)
    314 {
    315 	strlcpy(buf, pb->pb_path, maxlen);
    316 }
    317 
    318 /*
    319  * These two functions allow access to a saved copy of the original
    320  * path string. The first copy should be gotten before namei is
    321  * called. Each copy that is gotten should be put back.
    322  */
    323 
    324 const char *
    325 pathbuf_stringcopy_get(struct pathbuf *pb)
    326 {
    327 	if (pb->pb_pathcopyuses == 0) {
    328 		pb->pb_pathcopy = PNBUF_GET();
    329 		strcpy(pb->pb_pathcopy, pb->pb_path);
    330 	}
    331 	pb->pb_pathcopyuses++;
    332 	return pb->pb_pathcopy;
    333 }
    334 
    335 void
    336 pathbuf_stringcopy_put(struct pathbuf *pb, const char *str)
    337 {
    338 	KASSERT(str == pb->pb_pathcopy);
    339 	KASSERT(pb->pb_pathcopyuses > 0);
    340 	pb->pb_pathcopyuses--;
    341 	if (pb->pb_pathcopyuses == 0) {
    342 		PNBUF_PUT(pb->pb_pathcopy);
    343 		pb->pb_pathcopy = NULL;
    344 	}
    345 }
    346 
    347 
    348 ////////////////////////////////////////////////////////////
    349 
    350 /*
    351  * Convert a pathname into a pointer to a locked vnode.
    352  *
    353  * The FOLLOW flag is set when symbolic links are to be followed
    354  * when they occur at the end of the name translation process.
    355  * Symbolic links are always followed for all other pathname
    356  * components other than the last.
    357  *
    358  * The segflg defines whether the name is to be copied from user
    359  * space or kernel space.
    360  *
    361  * Overall outline of namei:
    362  *
    363  *	copy in name
    364  *	get starting directory
    365  *	while (!done && !error) {
    366  *		call lookup to search path.
    367  *		if symbolic link, massage name in buffer and continue
    368  *	}
    369  */
    370 
    371 /*
    372  * Internal state for a namei operation.
    373  */
    374 struct namei_state {
    375 	struct nameidata *ndp;
    376 	struct componentname *cnp;
    377 
    378 	/* used by the pieces of namei */
    379 	struct vnode *namei_startdir; /* The directory namei() starts from. */
    380 
    381 	/* used by the pieces of lookup */
    382 	int lookup_alldone;
    383 
    384 	int docache;			/* == 0 do not cache last component */
    385 	int rdonly;			/* lookup read-only flag bit */
    386 	struct vnode *dp;		/* the directory we are searching */
    387 	int slashes;
    388 };
    389 
    390 /* XXX reorder things to make this decl unnecessary */
    391 static int do_lookup(struct namei_state *state);
    392 
    393 
    394 /*
    395  * Initialize the namei working state.
    396  */
    397 static void
    398 namei_init(struct namei_state *state, struct nameidata *ndp)
    399 {
    400 	state->ndp = ndp;
    401 	state->cnp = &ndp->ni_cnd;
    402 
    403 	state->namei_startdir = NULL;
    404 
    405 	state->lookup_alldone = 0;
    406 
    407 	state->docache = 0;
    408 	state->rdonly = 0;
    409 	state->dp = NULL;
    410 	state->slashes = 0;
    411 }
    412 
    413 /*
    414  * Clean up the working namei state, leaving things ready for return
    415  * from namei.
    416  */
    417 static void
    418 namei_cleanup(struct namei_state *state)
    419 {
    420 	KASSERT(state->cnp == &state->ndp->ni_cnd);
    421 
    422 	//KASSERT(state->namei_startdir == NULL); 	// not yet
    423 
    424 	/* nothing for now */
    425 	(void)state;
    426 }
    427 
    428 //////////////////////////////
    429 
    430 /*
    431  * Start up namei. Early portion.
    432  *
    433  * This is divided from namei_start2 by the emul_retry: point.
    434  */
    435 static void
    436 namei_start1(struct namei_state *state)
    437 {
    438 
    439 #ifdef DIAGNOSTIC
    440 	if (!state->cnp->cn_cred)
    441 		panic("namei: bad cred/proc");
    442 	if (state->cnp->cn_nameiop & (~OPMASK))
    443 		panic("namei: nameiop contaminated with flags");
    444 	if (state->cnp->cn_flags & OPMASK)
    445 		panic("namei: flags contaminated with nameiops");
    446 #endif
    447 
    448 	/*
    449 	 * The buffer for name translation shall be the one inside the
    450 	 * pathbuf.
    451 	 */
    452 	state->ndp->ni_pnbuf = state->ndp->ni_pathbuf->pb_path;
    453 }
    454 
    455 /*
    456  * Start up namei. Copy the path, find the root dir and cwd, establish
    457  * the starting directory for lookup, and lock it.
    458  */
    459 static int
    460 namei_start2(struct namei_state *state)
    461 {
    462 	struct nameidata *ndp = state->ndp;
    463 	struct componentname *cnp = state->cnp;
    464 
    465 	struct cwdinfo *cwdi;		/* pointer to cwd state */
    466 	struct lwp *self = curlwp;	/* thread doing namei() */
    467 
    468 #if 0 /* not any more */
    469 	/* as both buffers are size PATH_MAX this cannot overflow */
    470 	strcpy(cnp->cn_pnbuf, ndp->ni_pathbuf->pb_path);
    471 #endif
    472 
    473 	/* length includes null terminator (was originally from copyinstr) */
    474 	ndp->ni_pathlen = strlen(ndp->ni_pnbuf) + 1;
    475 
    476 	/*
    477 	 * POSIX.1 requirement: "" is not a valid file name.
    478 	 */
    479 	if (ndp->ni_pathlen == 1) {
    480 		ndp->ni_vp = NULL;
    481 		return ENOENT;
    482 	}
    483 
    484 	ndp->ni_loopcnt = 0;
    485 
    486 	/*
    487 	 * Get root directory for the translation.
    488 	 */
    489 	cwdi = self->l_proc->p_cwdi;
    490 	rw_enter(&cwdi->cwdi_lock, RW_READER);
    491 	state->namei_startdir = cwdi->cwdi_rdir;
    492 	if (state->namei_startdir == NULL)
    493 		state->namei_startdir = rootvnode;
    494 	ndp->ni_rootdir = state->namei_startdir;
    495 
    496 	/*
    497 	 * Check if starting from root directory or current directory.
    498 	 */
    499 	if (ndp->ni_pnbuf[0] == '/') {
    500 		if (cnp->cn_flags & TRYEMULROOT) {
    501 			if (cnp->cn_flags & EMULROOTSET) {
    502 				/* Called from (eg) emul_find_interp() */
    503 				state->namei_startdir = ndp->ni_erootdir;
    504 			} else {
    505 				if (cwdi->cwdi_edir == NULL
    506 				    || (ndp->ni_pnbuf[1] == '.'
    507 					   && ndp->ni_pnbuf[2] == '.'
    508 					   && ndp->ni_pnbuf[3] == '/')) {
    509 					ndp->ni_erootdir = NULL;
    510 				} else {
    511 					state->namei_startdir = cwdi->cwdi_edir;
    512 					ndp->ni_erootdir = state->namei_startdir;
    513 				}
    514 			}
    515 		} else {
    516 			ndp->ni_erootdir = NULL;
    517 			if (cnp->cn_flags & NOCHROOT)
    518 				state->namei_startdir = ndp->ni_rootdir = rootvnode;
    519 		}
    520 	} else {
    521 		state->namei_startdir = cwdi->cwdi_cdir;
    522 		ndp->ni_erootdir = NULL;
    523 	}
    524 	vref(state->namei_startdir);
    525 	rw_exit(&cwdi->cwdi_lock);
    526 
    527 	/*
    528 	 * Ktrace it.
    529 	 */
    530 	if (ktrpoint(KTR_NAMEI)) {
    531 		if (ndp->ni_erootdir != NULL) {
    532 			/*
    533 			 * To make any sense, the trace entry need to have the
    534 			 * text of the emulation path prepended.
    535 			 * Usually we can get this from the current process,
    536 			 * but when called from emul_find_interp() it is only
    537 			 * in the exec_package - so we get it passed in ni_next
    538 			 * (this is a hack).
    539 			 */
    540 			const char *emul_path;
    541 			if (cnp->cn_flags & EMULROOTSET)
    542 				emul_path = ndp->ni_next;
    543 			else
    544 				emul_path = self->l_proc->p_emul->e_path;
    545 			ktrnamei2(emul_path, strlen(emul_path),
    546 			    ndp->ni_pnbuf, ndp->ni_pathlen);
    547 		} else
    548 			ktrnamei(ndp->ni_pnbuf, ndp->ni_pathlen);
    549 	}
    550 
    551 	vn_lock(state->namei_startdir, LK_EXCLUSIVE | LK_RETRY);
    552 
    553 	return 0;
    554 }
    555 
    556 /*
    557  * Undo namei_start: unlock and release the current lookup directory,
    558  * and discard the path buffer.
    559  */
    560 static void
    561 namei_end(struct namei_state *state)
    562 {
    563 	vput(state->namei_startdir);
    564 }
    565 
    566 /*
    567  * Check for being at a symlink.
    568  */
    569 static inline int
    570 namei_atsymlink(struct namei_state *state)
    571 {
    572 	return (state->cnp->cn_flags & ISSYMLINK) != 0;
    573 }
    574 
    575 /*
    576  * Follow a symlink.
    577  */
    578 static inline int
    579 namei_follow(struct namei_state *state)
    580 {
    581 	struct nameidata *ndp = state->ndp;
    582 	struct componentname *cnp = state->cnp;
    583 
    584 	struct lwp *self = curlwp;	/* thread doing namei() */
    585 	struct iovec aiov;		/* uio for reading symbolic links */
    586 	struct uio auio;
    587 	char *cp;			/* pointer into pathname argument */
    588 	size_t linklen;
    589 	int error;
    590 
    591 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
    592 		return ELOOP;
    593 	}
    594 	if (ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
    595 		error = VOP_ACCESS(ndp->ni_vp, VEXEC, cnp->cn_cred);
    596 		if (error != 0)
    597 			return error;
    598 	}
    599 
    600 	/* FUTURE: fix this to not use a second buffer */
    601 	cp = PNBUF_GET();
    602 	aiov.iov_base = cp;
    603 	aiov.iov_len = MAXPATHLEN;
    604 	auio.uio_iov = &aiov;
    605 	auio.uio_iovcnt = 1;
    606 	auio.uio_offset = 0;
    607 	auio.uio_rw = UIO_READ;
    608 	auio.uio_resid = MAXPATHLEN;
    609 	UIO_SETUP_SYSSPACE(&auio);
    610 	error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
    611 	if (error) {
    612 		PNBUF_PUT(cp);
    613 		return error;
    614 	}
    615 	linklen = MAXPATHLEN - auio.uio_resid;
    616 	if (linklen == 0) {
    617 		PNBUF_PUT(cp);
    618 		return ENOENT;
    619 	}
    620 
    621 	/*
    622 	 * Do symlink substitution, if appropriate, and
    623 	 * check length for potential overflow.
    624 	 */
    625 	if ((vfs_magiclinks &&
    626 	     symlink_magic(self->l_proc, cp, &linklen)) ||
    627 	    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
    628 		PNBUF_PUT(cp);
    629 		return ENAMETOOLONG;
    630 	}
    631 	if (ndp->ni_pathlen > 1) {
    632 		/* includes a null-terminator */
    633 		memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
    634 	} else {
    635 		cp[linklen] = '\0';
    636 	}
    637 	ndp->ni_pathlen += linklen;
    638 	memcpy(ndp->ni_pnbuf, cp, ndp->ni_pathlen);
    639 	PNBUF_PUT(cp);
    640 	vput(ndp->ni_vp);
    641 	state->namei_startdir = ndp->ni_dvp;
    642 
    643 	/*
    644 	 * Check if root directory should replace current directory.
    645 	 */
    646 	if (ndp->ni_pnbuf[0] == '/') {
    647 		vput(state->namei_startdir);
    648 		/* Keep absolute symbolic links inside emulation root */
    649 		state->namei_startdir = ndp->ni_erootdir;
    650 		if (state->namei_startdir == NULL ||
    651 		    (ndp->ni_pnbuf[1] == '.'
    652 		     && ndp->ni_pnbuf[2] == '.'
    653 		     && ndp->ni_pnbuf[3] == '/')) {
    654 			ndp->ni_erootdir = NULL;
    655 			state->namei_startdir = ndp->ni_rootdir;
    656 		}
    657 		vref(state->namei_startdir);
    658 		vn_lock(state->namei_startdir, LK_EXCLUSIVE | LK_RETRY);
    659 	}
    660 
    661 	return 0;
    662 }
    663 
    664 //////////////////////////////
    665 
    666 static int
    667 do_namei(struct namei_state *state)
    668 {
    669 	int error;
    670 
    671 	struct nameidata *ndp = state->ndp;
    672 	struct componentname *cnp = state->cnp;
    673 	const char *savepath = NULL;
    674 
    675 	KASSERT(cnp == &ndp->ni_cnd);
    676 
    677 	namei_start1(state);
    678 
    679 	if (cnp->cn_flags & TRYEMULROOT) {
    680 		savepath = pathbuf_stringcopy_get(ndp->ni_pathbuf);
    681 	}
    682 
    683     emul_retry:
    684 
    685 	if (savepath != NULL) {
    686 		/* kinda gross */
    687 		strcpy(ndp->ni_pathbuf->pb_path, savepath);
    688 		pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    689 		savepath = NULL;
    690 	}
    691 
    692 	error = namei_start2(state);
    693 	if (error) {
    694 		if (savepath != NULL) {
    695 			pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    696 		}
    697 		return error;
    698 	}
    699 	KASSERT(VOP_ISLOCKED(state->namei_startdir) == LK_EXCLUSIVE);
    700 
    701 	/* Loop through symbolic links */
    702 	for (;;) {
    703 		if (state->namei_startdir->v_mount == NULL) {
    704 			/* Give up if the directory is no longer mounted */
    705 			if (savepath != NULL) {
    706 				pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    707 			}
    708 			namei_end(state);
    709 			return (ENOENT);
    710 		}
    711 		cnp->cn_nameptr = ndp->ni_pnbuf;
    712 		ndp->ni_startdir = state->namei_startdir;
    713 		error = do_lookup(state);
    714 		if (error != 0) {
    715 			/* XXX this should use namei_end() */
    716 			if (ndp->ni_dvp) {
    717 				vput(ndp->ni_dvp);
    718 			}
    719 			if (ndp->ni_erootdir != NULL) {
    720 				/* Retry the whole thing from the normal root */
    721 				cnp->cn_flags &= ~TRYEMULROOT;
    722 				goto emul_retry;
    723 			}
    724 			KASSERT(savepath == NULL);
    725 			return (error);
    726 		}
    727 
    728 		/*
    729 		 * Check for symbolic link
    730 		 */
    731 		if (namei_atsymlink(state)) {
    732 			error = namei_follow(state);
    733 			if (error) {
    734 				KASSERT(ndp->ni_dvp != ndp->ni_vp);
    735 				vput(ndp->ni_dvp);
    736 				vput(ndp->ni_vp);
    737 				ndp->ni_vp = NULL;
    738 				if (savepath != NULL) {
    739 					pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    740 				}
    741 				return error;
    742 			}
    743 		}
    744 		else {
    745 			break;
    746 		}
    747 	}
    748 
    749 	/*
    750 	 * Done
    751 	 */
    752 
    753 	if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp) {
    754 		if (ndp->ni_dvp == ndp->ni_vp) {
    755 			vrele(ndp->ni_dvp);
    756 		} else {
    757 			vput(ndp->ni_dvp);
    758 		}
    759 	}
    760 
    761 	if (savepath != NULL) {
    762 		pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    763 	}
    764 
    765 	return 0;
    766 }
    767 
    768 int
    769 namei(struct nameidata *ndp)
    770 {
    771 	struct namei_state state;
    772 	int error;
    773 
    774 	namei_init(&state, ndp);
    775 	error = do_namei(&state);
    776 	namei_cleanup(&state);
    777 
    778 	return error;
    779 }
    780 
    781 /*
    782  * Determine the namei hash (for cn_hash) for name.
    783  * If *ep != NULL, hash from name to ep-1.
    784  * If *ep == NULL, hash from name until the first NUL or '/', and
    785  * return the location of this termination character in *ep.
    786  *
    787  * This function returns an equivalent hash to the MI hash32_strn().
    788  * The latter isn't used because in the *ep == NULL case, determining
    789  * the length of the string to the first NUL or `/' and then calling
    790  * hash32_strn() involves unnecessary double-handling of the data.
    791  */
    792 uint32_t
    793 namei_hash(const char *name, const char **ep)
    794 {
    795 	uint32_t	hash;
    796 
    797 	hash = HASH32_STR_INIT;
    798 	if (*ep != NULL) {
    799 		for (; name < *ep; name++)
    800 			hash = hash * 33 + *(const uint8_t *)name;
    801 	} else {
    802 		for (; *name != '\0' && *name != '/'; name++)
    803 			hash = hash * 33 + *(const uint8_t *)name;
    804 		*ep = name;
    805 	}
    806 	return (hash + (hash >> 5));
    807 }
    808 
    809 /*
    810  * Search a pathname.
    811  * This is a very central and rather complicated routine.
    812  *
    813  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
    814  * The starting directory is taken from ni_startdir. The pathname is
    815  * descended until done, or a symbolic link is encountered. The variable
    816  * ni_more is clear if the path is completed; it is set to one if a
    817  * symbolic link needing interpretation is encountered.
    818  *
    819  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
    820  * whether the name is to be looked up, created, renamed, or deleted.
    821  * When CREATE, RENAME, or DELETE is specified, information usable in
    822  * creating, renaming, or deleting a directory entry may be calculated.
    823  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
    824  * locked.  Otherwise the parent directory is not returned. If the target
    825  * of the pathname exists and LOCKLEAF is or'ed into the flag the target
    826  * is returned locked, otherwise it is returned unlocked.  When creating
    827  * or renaming and LOCKPARENT is specified, the target may not be ".".
    828  * When deleting and LOCKPARENT is specified, the target may be ".".
    829  *
    830  * Overall outline of lookup:
    831  *
    832  * dirloop:
    833  *	identify next component of name at ndp->ni_ptr
    834  *	handle degenerate case where name is null string
    835  *	if .. and crossing mount points and on mounted filesys, find parent
    836  *	call VOP_LOOKUP routine for next component name
    837  *	    directory vnode returned in ni_dvp, locked.
    838  *	    component vnode returned in ni_vp (if it exists), locked.
    839  *	if result vnode is mounted on and crossing mount points,
    840  *	    find mounted on vnode
    841  *	if more components of name, do next level at dirloop
    842  *	return the answer in ni_vp, locked if LOCKLEAF set
    843  *	    if LOCKPARENT set, return locked parent in ni_dvp
    844  */
    845 
    846 /*
    847  * Begin lookup().
    848  */
    849 static int
    850 lookup_start(struct namei_state *state)
    851 {
    852 	const char *cp;			/* pointer into pathname argument */
    853 
    854 	struct componentname *cnp = state->cnp;
    855 	struct nameidata *ndp = state->ndp;
    856 
    857 	KASSERT(cnp == &ndp->ni_cnd);
    858 
    859 	state->lookup_alldone = 0;
    860 	state->dp = NULL;
    861 
    862 	/*
    863 	 * Setup: break out flag bits into variables.
    864 	 */
    865 	state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
    866 	if (cnp->cn_nameiop == DELETE)
    867 		state->docache = 0;
    868 	state->rdonly = cnp->cn_flags & RDONLY;
    869 	ndp->ni_dvp = NULL;
    870 	cnp->cn_flags &= ~ISSYMLINK;
    871 	state->dp = ndp->ni_startdir;
    872 	ndp->ni_startdir = NULLVP;
    873 
    874 	/*
    875 	 * If we have a leading string of slashes, remove them, and just make
    876 	 * sure the current node is a directory.
    877 	 */
    878 	cp = cnp->cn_nameptr;
    879 	if (*cp == '/') {
    880 		do {
    881 			cp++;
    882 		} while (*cp == '/');
    883 		ndp->ni_pathlen -= cp - cnp->cn_nameptr;
    884 		cnp->cn_nameptr = cp;
    885 
    886 		if (state->dp->v_type != VDIR) {
    887 			vput(state->dp);
    888 			return ENOTDIR;
    889 		}
    890 
    891 		/*
    892 		 * If we've exhausted the path name, then just return the
    893 		 * current node.
    894 		 */
    895 		if (cnp->cn_nameptr[0] == '\0') {
    896 			ndp->ni_vp = state->dp;
    897 			cnp->cn_flags |= ISLASTCN;
    898 
    899 			/* bleh */
    900 			state->lookup_alldone = 1;
    901 			return 0;
    902 		}
    903 	}
    904 
    905 	return 0;
    906 }
    907 
    908 /*
    909  * lookup_parsepath: consume a component name from state->ndp and prepare
    910  * state->cnp for it.
    911  */
    912 
    913 static int
    914 lookup_parsepath(struct namei_state *state)
    915 {
    916 	const char *cp;			/* pointer into pathname argument */
    917 
    918 	struct componentname *cnp = state->cnp;
    919 	struct nameidata *ndp = state->ndp;
    920 
    921 	KASSERT(cnp == &ndp->ni_cnd);
    922 
    923 	/*
    924 	 * Search a new directory.
    925 	 *
    926 	 * The cn_hash value is for use by vfs_cache.
    927 	 * The last component of the filename is left accessible via
    928 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    929 	 * the name set the SAVENAME flag. When done, they assume
    930 	 * responsibility for freeing the pathname buffer.
    931 	 */
    932 	cnp->cn_consume = 0;
    933 	cp = NULL;
    934 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
    935 	cnp->cn_namelen = cp - cnp->cn_nameptr;
    936 	if (cnp->cn_namelen > NAME_MAX) {
    937 		return ENAMETOOLONG;
    938 	}
    939 #ifdef NAMEI_DIAGNOSTIC
    940 	{ char c = *cp;
    941 	*(char *)cp = '\0';
    942 	printf("{%s}: ", cnp->cn_nameptr);
    943 	*(char *)cp = c; }
    944 #endif /* NAMEI_DIAGNOSTIC */
    945 	ndp->ni_pathlen -= cnp->cn_namelen;
    946 	ndp->ni_next = cp;
    947 	/*
    948 	 * If this component is followed by a slash, then move the pointer to
    949 	 * the next component forward, and remember that this component must be
    950 	 * a directory.
    951 	 */
    952 	if (*cp == '/') {
    953 		do {
    954 			cp++;
    955 		} while (*cp == '/');
    956 		state->slashes = cp - ndp->ni_next;
    957 		ndp->ni_pathlen -= state->slashes;
    958 		ndp->ni_next = cp;
    959 		cnp->cn_flags |= REQUIREDIR;
    960 	} else {
    961 		state->slashes = 0;
    962 		cnp->cn_flags &= ~REQUIREDIR;
    963 	}
    964 	/*
    965 	 * We do special processing on the last component, whether or not it's
    966 	 * a directory.  Cache all intervening lookups, but not the final one.
    967 	 */
    968 	if (*cp == '\0') {
    969 		if (state->docache)
    970 			cnp->cn_flags |= MAKEENTRY;
    971 		else
    972 			cnp->cn_flags &= ~MAKEENTRY;
    973 		cnp->cn_flags |= ISLASTCN;
    974 	} else {
    975 		cnp->cn_flags |= MAKEENTRY;
    976 		cnp->cn_flags &= ~ISLASTCN;
    977 	}
    978 	if (cnp->cn_namelen == 2 &&
    979 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
    980 		cnp->cn_flags |= ISDOTDOT;
    981 	else
    982 		cnp->cn_flags &= ~ISDOTDOT;
    983 
    984 	return 0;
    985 }
    986 
    987 /*
    988  * lookup_once: look up the vnode for the next component name (state->cnp).
    989  *
    990  * takes care of dot-dot, cross-mount, and MNT_UNION.
    991  *
    992  * inputs:
    993  *	state->dp	the parent vnode
    994  *	state->cnp	the componentname to lookup
    995  *
    996  * outputs:
    997  *	state->dp	the result vnode
    998  *	ndp->ni_vp	updated to state->dp
    999  *	ndp->ni_dvp	updated to the parent directory vnode
   1000  */
   1001 
   1002 static int
   1003 lookup_once(struct namei_state *state)
   1004 {
   1005 	struct vnode *tdp;		/* saved dp */
   1006 	struct mount *mp;		/* mount table entry */
   1007 	struct lwp *l = curlwp;
   1008 	int error;
   1009 
   1010 	struct componentname *cnp = state->cnp;
   1011 	struct nameidata *ndp = state->ndp;
   1012 
   1013 	KASSERT(cnp == &ndp->ni_cnd);
   1014 
   1015 	/*
   1016 	 * Handle "..": two special cases.
   1017 	 * 1. If at root directory (e.g. after chroot)
   1018 	 *    or at absolute root directory
   1019 	 *    then ignore it so can't get out.
   1020 	 * 1a. If at the root of the emulation filesystem go to the real
   1021 	 *    root. So "/../<path>" is always absolute.
   1022 	 * 1b. If we have somehow gotten out of a jail, warn
   1023 	 *    and also ignore it so we can't get farther out.
   1024 	 * 2. If this vnode is the root of a mounted
   1025 	 *    filesystem, then replace it with the
   1026 	 *    vnode which was mounted on so we take the
   1027 	 *    .. in the other file system.
   1028 	 */
   1029 	if (cnp->cn_flags & ISDOTDOT) {
   1030 		struct proc *p = l->l_proc;
   1031 
   1032 		for (;;) {
   1033 			if (state->dp == ndp->ni_rootdir || state->dp == rootvnode) {
   1034 				ndp->ni_dvp = state->dp;
   1035 				ndp->ni_vp = state->dp;
   1036 				vref(state->dp);
   1037 				return 0;
   1038 			}
   1039 			if (ndp->ni_rootdir != rootvnode) {
   1040 				int retval;
   1041 
   1042 				VOP_UNLOCK(state->dp);
   1043 				retval = vn_isunder(state->dp, ndp->ni_rootdir, l);
   1044 				vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1045 				if (!retval) {
   1046 				    /* Oops! We got out of jail! */
   1047 				    log(LOG_WARNING,
   1048 					"chrooted pid %d uid %d (%s) "
   1049 					"detected outside of its chroot\n",
   1050 					p->p_pid, kauth_cred_geteuid(l->l_cred),
   1051 					p->p_comm);
   1052 				    /* Put us at the jail root. */
   1053 				    vput(state->dp);
   1054 				    state->dp = ndp->ni_rootdir;
   1055 				    ndp->ni_dvp = state->dp;
   1056 				    ndp->ni_vp = state->dp;
   1057 				    vref(state->dp);
   1058 				    vref(state->dp);
   1059 				    vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1060 				    return 0;
   1061 				}
   1062 			}
   1063 			if ((state->dp->v_vflag & VV_ROOT) == 0 ||
   1064 			    (cnp->cn_flags & NOCROSSMOUNT))
   1065 				break;
   1066 			tdp = state->dp;
   1067 			state->dp = state->dp->v_mount->mnt_vnodecovered;
   1068 			vput(tdp);
   1069 			vref(state->dp);
   1070 			vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1071 		}
   1072 	}
   1073 
   1074 	/*
   1075 	 * We now have a segment name to search for, and a directory to search.
   1076 	 * Again, our only vnode state is that "dp" is held and locked.
   1077 	 */
   1078 unionlookup:
   1079 	ndp->ni_dvp = state->dp;
   1080 	ndp->ni_vp = NULL;
   1081 	error = VOP_LOOKUP(state->dp, &ndp->ni_vp, cnp);
   1082 	if (error != 0) {
   1083 #ifdef DIAGNOSTIC
   1084 		if (ndp->ni_vp != NULL)
   1085 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
   1086 #endif /* DIAGNOSTIC */
   1087 #ifdef NAMEI_DIAGNOSTIC
   1088 		printf("not found\n");
   1089 #endif /* NAMEI_DIAGNOSTIC */
   1090 		if ((error == ENOENT) &&
   1091 		    (state->dp->v_vflag & VV_ROOT) &&
   1092 		    (state->dp->v_mount->mnt_flag & MNT_UNION)) {
   1093 			tdp = state->dp;
   1094 			state->dp = state->dp->v_mount->mnt_vnodecovered;
   1095 			vput(tdp);
   1096 			vref(state->dp);
   1097 			vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1098 			goto unionlookup;
   1099 		}
   1100 
   1101 		if (error != EJUSTRETURN)
   1102 			return error;
   1103 
   1104 		/*
   1105 		 * If this was not the last component, or there were trailing
   1106 		 * slashes, and we are not going to create a directory,
   1107 		 * then the name must exist.
   1108 		 */
   1109 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
   1110 			return ENOENT;
   1111 		}
   1112 
   1113 		/*
   1114 		 * If creating and at end of pathname, then can consider
   1115 		 * allowing file to be created.
   1116 		 */
   1117 		if (state->rdonly) {
   1118 			return EROFS;
   1119 		}
   1120 
   1121 		/*
   1122 		 * We return with ni_vp NULL to indicate that the entry
   1123 		 * doesn't currently exist, leaving a pointer to the
   1124 		 * (possibly locked) directory vnode in ndp->ni_dvp.
   1125 		 */
   1126 		if (cnp->cn_flags & SAVESTART) {
   1127 			ndp->ni_startdir = ndp->ni_dvp;
   1128 			vref(ndp->ni_startdir);
   1129 		}
   1130 		state->lookup_alldone = 1;
   1131 		return (0);
   1132 	}
   1133 #ifdef NAMEI_DIAGNOSTIC
   1134 	printf("found\n");
   1135 #endif /* NAMEI_DIAGNOSTIC */
   1136 
   1137 	/*
   1138 	 * Take into account any additional components consumed by the
   1139 	 * underlying filesystem.  This will include any trailing slashes after
   1140 	 * the last component consumed.
   1141 	 */
   1142 	if (cnp->cn_consume > 0) {
   1143 		ndp->ni_pathlen -= cnp->cn_consume - state->slashes;
   1144 		ndp->ni_next += cnp->cn_consume - state->slashes;
   1145 		cnp->cn_consume = 0;
   1146 		if (ndp->ni_next[0] == '\0')
   1147 			cnp->cn_flags |= ISLASTCN;
   1148 	}
   1149 
   1150 	state->dp = ndp->ni_vp;
   1151 
   1152 	/*
   1153 	 * "state->dp" and "ndp->ni_dvp" are both locked and held,
   1154 	 * and may be the same vnode.
   1155 	 */
   1156 	KASSERT(VOP_ISLOCKED(state->dp) == LK_EXCLUSIVE);
   1157 	KASSERT(VOP_ISLOCKED(ndp->ni_dvp) == LK_EXCLUSIVE);
   1158 
   1159 	/*
   1160 	 * Check to see if the vnode has been mounted on;
   1161 	 * if so find the root of the mounted file system.
   1162 	 */
   1163 	while (state->dp->v_type == VDIR && (mp = state->dp->v_mountedhere) &&
   1164 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
   1165 		error = vfs_busy(mp, NULL);
   1166 		if (error != 0) {
   1167 			vput(state->dp);
   1168 			return error;
   1169 		}
   1170 		KASSERT(ndp->ni_dvp != state->dp);
   1171 		VOP_UNLOCK(ndp->ni_dvp);
   1172 		vput(state->dp);
   1173 		error = VFS_ROOT(mp, &tdp);
   1174 		vfs_unbusy(mp, false, NULL);
   1175 		if (error) {
   1176 			vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
   1177 			return error;
   1178 		}
   1179 		vrele(ndp->ni_dvp);
   1180 		vref(tdp);
   1181 		ndp->ni_dvp = ndp->ni_vp = state->dp = tdp;
   1182 	}
   1183 
   1184 	return 0;
   1185 }
   1186 
   1187 static int
   1188 do_lookup(struct namei_state *state)
   1189 {
   1190 	int error = 0;
   1191 
   1192 	struct componentname *cnp = state->cnp;
   1193 	struct nameidata *ndp = state->ndp;
   1194 
   1195 	KASSERT(cnp == &ndp->ni_cnd);
   1196 
   1197 	error = lookup_start(state);
   1198 	if (error) {
   1199 		goto bad;
   1200 	}
   1201 	// XXX: this case should not be necessary given proper handling
   1202 	// of slashes elsewhere.
   1203 	if (state->lookup_alldone) {
   1204 		goto terminal;
   1205 	}
   1206 
   1207 dirloop:
   1208 	/*
   1209 	 * At this point, our only vnode state is that "dp" is held and locked.
   1210 	 */
   1211 	KASSERT(VOP_ISLOCKED(state->dp) == LK_EXCLUSIVE);
   1212 	KASSERT(ndp->ni_dvp == NULL);
   1213 	error = lookup_parsepath(state);
   1214 	if (error) {
   1215 		vput(state->dp);
   1216 		goto bad;
   1217 	}
   1218 
   1219 	error = lookup_once(state);
   1220 	if (error) {
   1221 		goto bad;
   1222 	}
   1223 	// XXX ought to be able to avoid this case too
   1224 	if (state->lookup_alldone) {
   1225 		/* this should NOT be "goto terminal;" */
   1226 		return 0;
   1227 	}
   1228 
   1229 	/*
   1230 	 * Check for symbolic link.  Back up over any slashes that we skipped,
   1231 	 * as we will need them again.
   1232 	 */
   1233 	if ((state->dp->v_type == VLNK) && (cnp->cn_flags & (FOLLOW|REQUIREDIR))) {
   1234 		ndp->ni_pathlen += state->slashes;
   1235 		ndp->ni_next -= state->slashes;
   1236 		cnp->cn_flags |= ISSYMLINK;
   1237 		return (0);
   1238 	}
   1239 
   1240 	/*
   1241 	 * Check for directory, if the component was followed by a series of
   1242 	 * slashes.
   1243 	 */
   1244 	if ((state->dp->v_type != VDIR) && (cnp->cn_flags & REQUIREDIR)) {
   1245 		error = ENOTDIR;
   1246 		KASSERT(state->dp != ndp->ni_dvp);
   1247 		vput(state->dp);
   1248 		goto bad;
   1249 	}
   1250 
   1251 	/*
   1252 	 * Not a symbolic link.  If this was not the last component, then
   1253 	 * continue at the next component, else return.
   1254 	 */
   1255 	if (!(cnp->cn_flags & ISLASTCN)) {
   1256 		cnp->cn_nameptr = ndp->ni_next;
   1257 		if (ndp->ni_dvp == state->dp) {
   1258 			vrele(ndp->ni_dvp);
   1259 		} else {
   1260 			vput(ndp->ni_dvp);
   1261 		}
   1262 		ndp->ni_dvp = NULL;
   1263 		goto dirloop;
   1264 	}
   1265 
   1266 terminal:
   1267 	if (state->dp == ndp->ni_erootdir) {
   1268 		/*
   1269 		 * We are about to return the emulation root.
   1270 		 * This isn't a good idea because code might repeatedly
   1271 		 * lookup ".." until the file matches that returned
   1272 		 * for "/" and loop forever.
   1273 		 * So convert it to the real root.
   1274 		 */
   1275 		if (ndp->ni_dvp == state->dp)
   1276 			vrele(state->dp);
   1277 		else
   1278 			if (ndp->ni_dvp != NULL)
   1279 				vput(ndp->ni_dvp);
   1280 		ndp->ni_dvp = NULL;
   1281 		vput(state->dp);
   1282 		state->dp = ndp->ni_rootdir;
   1283 		vref(state->dp);
   1284 		vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1285 		ndp->ni_vp = state->dp;
   1286 	}
   1287 
   1288 	/*
   1289 	 * If the caller requested the parent node (i.e.
   1290 	 * it's a CREATE, DELETE, or RENAME), and we don't have one
   1291 	 * (because this is the root directory), then we must fail.
   1292 	 */
   1293 	if (ndp->ni_dvp == NULL && cnp->cn_nameiop != LOOKUP) {
   1294 		switch (cnp->cn_nameiop) {
   1295 		case CREATE:
   1296 			error = EEXIST;
   1297 			break;
   1298 		case DELETE:
   1299 		case RENAME:
   1300 			error = EBUSY;
   1301 			break;
   1302 		default:
   1303 			KASSERT(0);
   1304 		}
   1305 		vput(state->dp);
   1306 		goto bad;
   1307 	}
   1308 
   1309 	/*
   1310 	 * Disallow directory write attempts on read-only lookups.
   1311 	 * Prefers EEXIST over EROFS for the CREATE case.
   1312 	 */
   1313 	if (state->rdonly &&
   1314 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
   1315 		error = EROFS;
   1316 		if (state->dp != ndp->ni_dvp) {
   1317 			vput(state->dp);
   1318 		}
   1319 		goto bad;
   1320 	}
   1321 	if (ndp->ni_dvp != NULL) {
   1322 		if (cnp->cn_flags & SAVESTART) {
   1323 			ndp->ni_startdir = ndp->ni_dvp;
   1324 			vref(ndp->ni_startdir);
   1325 		}
   1326 	}
   1327 	if ((cnp->cn_flags & LOCKLEAF) == 0) {
   1328 		VOP_UNLOCK(state->dp);
   1329 	}
   1330 	return (0);
   1331 
   1332 bad:
   1333 	ndp->ni_vp = NULL;
   1334 	return (error);
   1335 }
   1336 
   1337 /*
   1338  * Externally visible interfaces used by nfsd (bletch, yuk, XXX)
   1339  *
   1340  * The "index" version differs from the "main" version in that it's
   1341  * called from a different place in a different context. For now I
   1342  * want to be able to shuffle code in from one call site without
   1343  * affecting the other.
   1344  */
   1345 
   1346 int
   1347 lookup_for_nfsd(struct nameidata *ndp, struct vnode *dp, int neverfollow)
   1348 {
   1349 	struct namei_state state;
   1350 	int error;
   1351 
   1352 	struct iovec aiov;
   1353 	struct uio auio;
   1354 	int linklen;
   1355 	char *cp;
   1356 
   1357 	ndp->ni_pnbuf = ndp->ni_pathbuf->pb_path;
   1358 	namei_init(&state, ndp);
   1359 
   1360 	/*
   1361 	 * BEGIN wodge of code from nfsd
   1362 	 */
   1363 
   1364 	vref(dp);
   1365 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
   1366 
   1367     for (;;) {
   1368 
   1369 	state.cnp->cn_nameptr = state.ndp->ni_pnbuf;
   1370 	state.ndp->ni_startdir = dp;
   1371 
   1372 	/*
   1373 	 * END wodge of code from nfsd
   1374 	 */
   1375 
   1376 	error = do_lookup(&state);
   1377 	if (error) {
   1378 		/* BEGIN from nfsd */
   1379 		if (ndp->ni_dvp) {
   1380 			vput(ndp->ni_dvp);
   1381 		}
   1382 		/* END from nfsd */
   1383 		namei_cleanup(&state);
   1384 		return error;
   1385 	}
   1386 
   1387 	/*
   1388 	 * BEGIN wodge of code from nfsd
   1389 	 */
   1390 
   1391 	/*
   1392 	 * Check for encountering a symbolic link
   1393 	 */
   1394 	if ((state.cnp->cn_flags & ISSYMLINK) == 0) {
   1395 		if ((state.cnp->cn_flags & LOCKPARENT) == 0 && state.ndp->ni_dvp) {
   1396 			if (state.ndp->ni_dvp == state.ndp->ni_vp) {
   1397 				vrele(state.ndp->ni_dvp);
   1398 			} else {
   1399 				vput(state.ndp->ni_dvp);
   1400 			}
   1401 		}
   1402 		return (0);
   1403 	} else {
   1404 		if (neverfollow) {
   1405 			error = EINVAL;
   1406 			goto out;
   1407 		}
   1408 		if (state.ndp->ni_loopcnt++ >= MAXSYMLINKS) {
   1409 			error = ELOOP;
   1410 			goto out;
   1411 		}
   1412 		if (state.ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
   1413 			error = VOP_ACCESS(ndp->ni_vp, VEXEC, state.cnp->cn_cred);
   1414 			if (error != 0)
   1415 				goto out;
   1416 		}
   1417 		cp = PNBUF_GET();
   1418 		aiov.iov_base = cp;
   1419 		aiov.iov_len = MAXPATHLEN;
   1420 		auio.uio_iov = &aiov;
   1421 		auio.uio_iovcnt = 1;
   1422 		auio.uio_offset = 0;
   1423 		auio.uio_rw = UIO_READ;
   1424 		auio.uio_resid = MAXPATHLEN;
   1425 		UIO_SETUP_SYSSPACE(&auio);
   1426 		error = VOP_READLINK(ndp->ni_vp, &auio, state.cnp->cn_cred);
   1427 		if (error) {
   1428 			PNBUF_PUT(cp);
   1429 			goto out;
   1430 		}
   1431 		linklen = MAXPATHLEN - auio.uio_resid;
   1432 		if (linklen == 0) {
   1433 			PNBUF_PUT(cp);
   1434 			error = ENOENT;
   1435 			goto out;
   1436 		}
   1437 		if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
   1438 			PNBUF_PUT(cp);
   1439 			error = ENAMETOOLONG;
   1440 			goto out;
   1441 		}
   1442 		if (ndp->ni_pathlen > 1) {
   1443 			/* includes a null-terminator */
   1444 			memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
   1445 		} else {
   1446 			cp[linklen] = '\0';
   1447 		}
   1448 		state.ndp->ni_pathlen += linklen;
   1449 		memcpy(state.ndp->ni_pnbuf, cp, state.ndp->ni_pathlen);
   1450 		PNBUF_PUT(cp);
   1451 		vput(state.ndp->ni_vp);
   1452 		dp = state.ndp->ni_dvp;
   1453 
   1454 		/*
   1455 		 * Check if root directory should replace current directory.
   1456 		 */
   1457 		if (state.ndp->ni_pnbuf[0] == '/') {
   1458 			vput(dp);
   1459 			dp = ndp->ni_rootdir;
   1460 			vref(dp);
   1461 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
   1462 		}
   1463 	}
   1464 
   1465     }
   1466  out:
   1467 	vput(state.ndp->ni_vp);
   1468 	vput(state.ndp->ni_dvp);
   1469 	state.ndp->ni_vp = NULL;
   1470 
   1471 	/*
   1472 	 * END wodge of code from nfsd
   1473 	 */
   1474 	namei_cleanup(&state);
   1475 
   1476 	return error;
   1477 }
   1478 
   1479 int
   1480 lookup_for_nfsd_index(struct nameidata *ndp)
   1481 {
   1482 	struct namei_state state;
   1483 	int error;
   1484 
   1485 	ndp->ni_pnbuf = ndp->ni_pathbuf->pb_path;
   1486 	ndp->ni_cnd.cn_nameptr = ndp->ni_pnbuf;
   1487 
   1488 	namei_init(&state, ndp);
   1489 	error = do_lookup(&state);
   1490 	namei_cleanup(&state);
   1491 
   1492 	return error;
   1493 }
   1494 
   1495 /*
   1496  * Reacquire a path name component.
   1497  * dvp is locked on entry and exit.
   1498  * *vpp is locked on exit unless it's NULL.
   1499  */
   1500 int
   1501 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
   1502 {
   1503 	int rdonly;			/* lookup read-only flag bit */
   1504 	int error = 0;
   1505 #ifdef DEBUG
   1506 	uint32_t newhash;		/* DEBUG: check name hash */
   1507 	const char *cp;			/* DEBUG: check name ptr/len */
   1508 #endif /* DEBUG */
   1509 
   1510 	/*
   1511 	 * Setup: break out flag bits into variables.
   1512 	 */
   1513 	rdonly = cnp->cn_flags & RDONLY;
   1514 	cnp->cn_flags &= ~ISSYMLINK;
   1515 
   1516 	/*
   1517 	 * Search a new directory.
   1518 	 *
   1519 	 * The cn_hash value is for use by vfs_cache.
   1520 	 * The last component of the filename is left accessible via
   1521 	 * cnp->cn_nameptr for callers that need the name. Callers needing
   1522 	 * the name set the SAVENAME flag. When done, they assume
   1523 	 * responsibility for freeing the pathname buffer.
   1524 	 */
   1525 #ifdef DEBUG
   1526 	cp = NULL;
   1527 	newhash = namei_hash(cnp->cn_nameptr, &cp);
   1528 	if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
   1529 		panic("relookup: bad hash");
   1530 	if (cnp->cn_namelen != cp - cnp->cn_nameptr)
   1531 		panic("relookup: bad len");
   1532 	while (*cp == '/')
   1533 		cp++;
   1534 	if (*cp != 0)
   1535 		panic("relookup: not last component");
   1536 #endif /* DEBUG */
   1537 
   1538 	/*
   1539 	 * Check for degenerate name (e.g. / or "")
   1540 	 * which is a way of talking about a directory,
   1541 	 * e.g. like "/." or ".".
   1542 	 */
   1543 	if (cnp->cn_nameptr[0] == '\0')
   1544 		panic("relookup: null name");
   1545 
   1546 	if (cnp->cn_flags & ISDOTDOT)
   1547 		panic("relookup: lookup on dot-dot");
   1548 
   1549 	/*
   1550 	 * We now have a segment name to search for, and a directory to search.
   1551 	 */
   1552 	if ((error = VOP_LOOKUP(dvp, vpp, cnp)) != 0) {
   1553 #ifdef DIAGNOSTIC
   1554 		if (*vpp != NULL)
   1555 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
   1556 #endif
   1557 		if (error != EJUSTRETURN)
   1558 			goto bad;
   1559 	}
   1560 
   1561 #ifdef DIAGNOSTIC
   1562 	/*
   1563 	 * Check for symbolic link
   1564 	 */
   1565 	if (*vpp && (*vpp)->v_type == VLNK && (cnp->cn_flags & FOLLOW))
   1566 		panic("relookup: symlink found");
   1567 #endif
   1568 
   1569 	/*
   1570 	 * Check for read-only lookups.
   1571 	 */
   1572 	if (rdonly && cnp->cn_nameiop != LOOKUP) {
   1573 		error = EROFS;
   1574 		if (*vpp) {
   1575 			vput(*vpp);
   1576 		}
   1577 		goto bad;
   1578 	}
   1579 	if (cnp->cn_flags & SAVESTART)
   1580 		vref(dvp);
   1581 	return (0);
   1582 
   1583 bad:
   1584 	*vpp = NULL;
   1585 	return (error);
   1586 }
   1587 
   1588 /*
   1589  * namei_simple - simple forms of namei.
   1590  *
   1591  * These are wrappers to allow the simple case callers of namei to be
   1592  * left alone while everything else changes under them.
   1593  */
   1594 
   1595 /* Flags */
   1596 struct namei_simple_flags_type {
   1597 	int dummy;
   1598 };
   1599 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
   1600 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
   1601 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
   1602 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
   1603 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
   1604 
   1605 static
   1606 int
   1607 namei_simple_convert_flags(namei_simple_flags_t sflags)
   1608 {
   1609 	if (sflags == NSM_NOFOLLOW_NOEMULROOT)
   1610 		return NOFOLLOW | 0;
   1611 	if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
   1612 		return NOFOLLOW | TRYEMULROOT;
   1613 	if (sflags == NSM_FOLLOW_NOEMULROOT)
   1614 		return FOLLOW | 0;
   1615 	if (sflags == NSM_FOLLOW_TRYEMULROOT)
   1616 		return FOLLOW | TRYEMULROOT;
   1617 	panic("namei_simple_convert_flags: bogus sflags\n");
   1618 	return 0;
   1619 }
   1620 
   1621 int
   1622 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
   1623 			struct vnode **vp_ret)
   1624 {
   1625 	struct nameidata nd;
   1626 	struct pathbuf *pb;
   1627 	int err;
   1628 
   1629 	pb = pathbuf_create(path);
   1630 	if (pb == NULL) {
   1631 		return ENOMEM;
   1632 	}
   1633 
   1634 	NDINIT(&nd,
   1635 		LOOKUP,
   1636 		namei_simple_convert_flags(sflags),
   1637 		pb);
   1638 	err = namei(&nd);
   1639 	if (err != 0) {
   1640 		pathbuf_destroy(pb);
   1641 		return err;
   1642 	}
   1643 	*vp_ret = nd.ni_vp;
   1644 	pathbuf_destroy(pb);
   1645 	return 0;
   1646 }
   1647 
   1648 int
   1649 namei_simple_user(const char *path, namei_simple_flags_t sflags,
   1650 			struct vnode **vp_ret)
   1651 {
   1652 	struct pathbuf *pb;
   1653 	struct nameidata nd;
   1654 	int err;
   1655 
   1656 	err = pathbuf_copyin(path, &pb);
   1657 	if (err) {
   1658 		return err;
   1659 	}
   1660 
   1661 	NDINIT(&nd,
   1662 		LOOKUP,
   1663 		namei_simple_convert_flags(sflags),
   1664 		pb);
   1665 	err = namei(&nd);
   1666 	if (err != 0) {
   1667 		pathbuf_destroy(pb);
   1668 		return err;
   1669 	}
   1670 	*vp_ret = nd.ni_vp;
   1671 	pathbuf_destroy(pb);
   1672 	return 0;
   1673 }
   1674