Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.129
      1 /*	$NetBSD: vfs_lookup.c,v 1.129 2011/01/02 05:04:58 dholland 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.129 2011/01/02 05:04:58 dholland 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, struct vnode *startdir);
    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 	KASSERT((state->cnp->cn_flags & INRELOOKUP) == 0);
    403 
    404 	state->namei_startdir = NULL;
    405 
    406 	state->lookup_alldone = 0;
    407 
    408 	state->docache = 0;
    409 	state->rdonly = 0;
    410 	state->dp = NULL;
    411 	state->slashes = 0;
    412 }
    413 
    414 /*
    415  * Clean up the working namei state, leaving things ready for return
    416  * from namei.
    417  */
    418 static void
    419 namei_cleanup(struct namei_state *state)
    420 {
    421 	KASSERT(state->cnp == &state->ndp->ni_cnd);
    422 
    423 	//KASSERT(state->namei_startdir == NULL); 	// not yet
    424 
    425 	/* nothing for now */
    426 	(void)state;
    427 }
    428 
    429 //////////////////////////////
    430 
    431 /*
    432  * Start up namei. Early portion.
    433  *
    434  * This is divided from namei_start2 by the emul_retry: point.
    435  */
    436 static void
    437 namei_start1(struct namei_state *state)
    438 {
    439 
    440 #ifdef DIAGNOSTIC
    441 	if (!state->cnp->cn_cred)
    442 		panic("namei: bad cred/proc");
    443 	if (state->cnp->cn_nameiop & (~OPMASK))
    444 		panic("namei: nameiop contaminated with flags");
    445 	if (state->cnp->cn_flags & OPMASK)
    446 		panic("namei: flags contaminated with nameiops");
    447 #endif
    448 
    449 	/*
    450 	 * The buffer for name translation shall be the one inside the
    451 	 * pathbuf.
    452 	 */
    453 	state->ndp->ni_pnbuf = state->ndp->ni_pathbuf->pb_path;
    454 }
    455 
    456 /*
    457  * Start up namei. Copy the path, find the root dir and cwd, establish
    458  * the starting directory for lookup, and lock it.
    459  */
    460 static int
    461 namei_start2(struct namei_state *state)
    462 {
    463 	struct nameidata *ndp = state->ndp;
    464 	struct componentname *cnp = state->cnp;
    465 
    466 	struct cwdinfo *cwdi;		/* pointer to cwd state */
    467 	struct lwp *self = curlwp;	/* thread doing namei() */
    468 
    469 #if 0 /* not any more */
    470 	/* as both buffers are size PATH_MAX this cannot overflow */
    471 	strcpy(cnp->cn_pnbuf, ndp->ni_pathbuf->pb_path);
    472 #endif
    473 
    474 	/* length includes null terminator (was originally from copyinstr) */
    475 	ndp->ni_pathlen = strlen(ndp->ni_pnbuf) + 1;
    476 
    477 	/*
    478 	 * POSIX.1 requirement: "" is not a valid file name.
    479 	 */
    480 	if (ndp->ni_pathlen == 1) {
    481 		ndp->ni_vp = NULL;
    482 		return ENOENT;
    483 	}
    484 
    485 	ndp->ni_loopcnt = 0;
    486 
    487 	/*
    488 	 * Get root directory for the translation.
    489 	 */
    490 	cwdi = self->l_proc->p_cwdi;
    491 	rw_enter(&cwdi->cwdi_lock, RW_READER);
    492 	state->namei_startdir = cwdi->cwdi_rdir;
    493 	if (state->namei_startdir == NULL)
    494 		state->namei_startdir = rootvnode;
    495 	ndp->ni_rootdir = state->namei_startdir;
    496 
    497 	/*
    498 	 * Check if starting from root directory or current directory.
    499 	 */
    500 	if (ndp->ni_pnbuf[0] == '/') {
    501 		if (cnp->cn_flags & TRYEMULROOT) {
    502 			if (cnp->cn_flags & EMULROOTSET) {
    503 				/* Called from (eg) emul_find_interp() */
    504 				state->namei_startdir = ndp->ni_erootdir;
    505 			} else {
    506 				if (cwdi->cwdi_edir == NULL
    507 				    || (ndp->ni_pnbuf[1] == '.'
    508 					   && ndp->ni_pnbuf[2] == '.'
    509 					   && ndp->ni_pnbuf[3] == '/')) {
    510 					ndp->ni_erootdir = NULL;
    511 				} else {
    512 					state->namei_startdir = cwdi->cwdi_edir;
    513 					ndp->ni_erootdir = state->namei_startdir;
    514 				}
    515 			}
    516 		} else {
    517 			ndp->ni_erootdir = NULL;
    518 			if (cnp->cn_flags & NOCHROOT)
    519 				state->namei_startdir = ndp->ni_rootdir = rootvnode;
    520 		}
    521 	} else {
    522 		state->namei_startdir = cwdi->cwdi_cdir;
    523 		ndp->ni_erootdir = NULL;
    524 	}
    525 	vref(state->namei_startdir);
    526 	rw_exit(&cwdi->cwdi_lock);
    527 
    528 	/*
    529 	 * Ktrace it.
    530 	 */
    531 	if (ktrpoint(KTR_NAMEI)) {
    532 		if (ndp->ni_erootdir != NULL) {
    533 			/*
    534 			 * To make any sense, the trace entry need to have the
    535 			 * text of the emulation path prepended.
    536 			 * Usually we can get this from the current process,
    537 			 * but when called from emul_find_interp() it is only
    538 			 * in the exec_package - so we get it passed in ni_next
    539 			 * (this is a hack).
    540 			 */
    541 			const char *emul_path;
    542 			if (cnp->cn_flags & EMULROOTSET)
    543 				emul_path = ndp->ni_next;
    544 			else
    545 				emul_path = self->l_proc->p_emul->e_path;
    546 			ktrnamei2(emul_path, strlen(emul_path),
    547 			    ndp->ni_pnbuf, ndp->ni_pathlen);
    548 		} else
    549 			ktrnamei(ndp->ni_pnbuf, ndp->ni_pathlen);
    550 	}
    551 
    552 	vn_lock(state->namei_startdir, LK_EXCLUSIVE | LK_RETRY);
    553 
    554 	return 0;
    555 }
    556 
    557 /*
    558  * Undo namei_start: unlock and release the current lookup directory,
    559  * and discard the path buffer.
    560  */
    561 static void
    562 namei_end(struct namei_state *state)
    563 {
    564 	vput(state->namei_startdir);
    565 }
    566 
    567 /*
    568  * Check for being at a symlink.
    569  */
    570 static inline int
    571 namei_atsymlink(struct namei_state *state)
    572 {
    573 	return (state->cnp->cn_flags & ISSYMLINK) != 0;
    574 }
    575 
    576 /*
    577  * Follow a symlink.
    578  */
    579 static inline int
    580 namei_follow(struct namei_state *state)
    581 {
    582 	struct nameidata *ndp = state->ndp;
    583 	struct componentname *cnp = state->cnp;
    584 
    585 	struct lwp *self = curlwp;	/* thread doing namei() */
    586 	struct iovec aiov;		/* uio for reading symbolic links */
    587 	struct uio auio;
    588 	char *cp;			/* pointer into pathname argument */
    589 	size_t linklen;
    590 	int error;
    591 
    592 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
    593 		return ELOOP;
    594 	}
    595 	if (ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
    596 		error = VOP_ACCESS(ndp->ni_vp, VEXEC, cnp->cn_cred);
    597 		if (error != 0)
    598 			return error;
    599 	}
    600 
    601 	/* FUTURE: fix this to not use a second buffer */
    602 	cp = PNBUF_GET();
    603 	aiov.iov_base = cp;
    604 	aiov.iov_len = MAXPATHLEN;
    605 	auio.uio_iov = &aiov;
    606 	auio.uio_iovcnt = 1;
    607 	auio.uio_offset = 0;
    608 	auio.uio_rw = UIO_READ;
    609 	auio.uio_resid = MAXPATHLEN;
    610 	UIO_SETUP_SYSSPACE(&auio);
    611 	error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
    612 	if (error) {
    613 		PNBUF_PUT(cp);
    614 		return error;
    615 	}
    616 	linklen = MAXPATHLEN - auio.uio_resid;
    617 	if (linklen == 0) {
    618 		PNBUF_PUT(cp);
    619 		return ENOENT;
    620 	}
    621 
    622 	/*
    623 	 * Do symlink substitution, if appropriate, and
    624 	 * check length for potential overflow.
    625 	 */
    626 	if ((vfs_magiclinks &&
    627 	     symlink_magic(self->l_proc, cp, &linklen)) ||
    628 	    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
    629 		PNBUF_PUT(cp);
    630 		return ENAMETOOLONG;
    631 	}
    632 	if (ndp->ni_pathlen > 1) {
    633 		/* includes a null-terminator */
    634 		memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
    635 	} else {
    636 		cp[linklen] = '\0';
    637 	}
    638 	ndp->ni_pathlen += linklen;
    639 	memcpy(ndp->ni_pnbuf, cp, ndp->ni_pathlen);
    640 	PNBUF_PUT(cp);
    641 	vput(ndp->ni_vp);
    642 	state->namei_startdir = ndp->ni_dvp;
    643 
    644 	/*
    645 	 * Check if root directory should replace current directory.
    646 	 */
    647 	if (ndp->ni_pnbuf[0] == '/') {
    648 		vput(state->namei_startdir);
    649 		/* Keep absolute symbolic links inside emulation root */
    650 		state->namei_startdir = ndp->ni_erootdir;
    651 		if (state->namei_startdir == NULL ||
    652 		    (ndp->ni_pnbuf[1] == '.'
    653 		     && ndp->ni_pnbuf[2] == '.'
    654 		     && ndp->ni_pnbuf[3] == '/')) {
    655 			ndp->ni_erootdir = NULL;
    656 			state->namei_startdir = ndp->ni_rootdir;
    657 		}
    658 		vref(state->namei_startdir);
    659 		vn_lock(state->namei_startdir, LK_EXCLUSIVE | LK_RETRY);
    660 	}
    661 
    662 	return 0;
    663 }
    664 
    665 //////////////////////////////
    666 
    667 static int
    668 do_namei(struct namei_state *state)
    669 {
    670 	int error;
    671 
    672 	struct nameidata *ndp = state->ndp;
    673 	struct componentname *cnp = state->cnp;
    674 	const char *savepath = NULL;
    675 
    676 	KASSERT(cnp == &ndp->ni_cnd);
    677 
    678 	namei_start1(state);
    679 
    680 	if (cnp->cn_flags & TRYEMULROOT) {
    681 		savepath = pathbuf_stringcopy_get(ndp->ni_pathbuf);
    682 	}
    683 
    684     emul_retry:
    685 
    686 	if (savepath != NULL) {
    687 		/* kinda gross */
    688 		strcpy(ndp->ni_pathbuf->pb_path, savepath);
    689 		pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    690 		savepath = NULL;
    691 	}
    692 
    693 	error = namei_start2(state);
    694 	if (error) {
    695 		if (savepath != NULL) {
    696 			pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    697 		}
    698 		return error;
    699 	}
    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 		error = do_lookup(state, state->namei_startdir);
    713 		if (error != 0) {
    714 			/* XXX this should use namei_end() */
    715 			if (ndp->ni_dvp) {
    716 				vput(ndp->ni_dvp);
    717 			}
    718 			if (ndp->ni_erootdir != NULL) {
    719 				/* Retry the whole thing from the normal root */
    720 				cnp->cn_flags &= ~TRYEMULROOT;
    721 				goto emul_retry;
    722 			}
    723 			KASSERT(savepath == NULL);
    724 			return (error);
    725 		}
    726 
    727 		/*
    728 		 * Check for symbolic link
    729 		 */
    730 		if (namei_atsymlink(state)) {
    731 			error = namei_follow(state);
    732 			if (error) {
    733 				KASSERT(ndp->ni_dvp != ndp->ni_vp);
    734 				vput(ndp->ni_dvp);
    735 				vput(ndp->ni_vp);
    736 				ndp->ni_vp = NULL;
    737 				if (savepath != NULL) {
    738 					pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    739 				}
    740 				return error;
    741 			}
    742 		}
    743 		else {
    744 			break;
    745 		}
    746 	}
    747 
    748 	/*
    749 	 * Done
    750 	 */
    751 
    752 	if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp) {
    753 		if (ndp->ni_dvp == ndp->ni_vp) {
    754 			vrele(ndp->ni_dvp);
    755 		} else {
    756 			vput(ndp->ni_dvp);
    757 		}
    758 	}
    759 
    760 	if (savepath != NULL) {
    761 		pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
    762 	}
    763 
    764 	return 0;
    765 }
    766 
    767 int
    768 namei(struct nameidata *ndp)
    769 {
    770 	struct namei_state state;
    771 	int error;
    772 
    773 	namei_init(&state, ndp);
    774 	error = do_namei(&state);
    775 	namei_cleanup(&state);
    776 
    777 	return error;
    778 }
    779 
    780 /*
    781  * Determine the namei hash (for cn_hash) for name.
    782  * If *ep != NULL, hash from name to ep-1.
    783  * If *ep == NULL, hash from name until the first NUL or '/', and
    784  * return the location of this termination character in *ep.
    785  *
    786  * This function returns an equivalent hash to the MI hash32_strn().
    787  * The latter isn't used because in the *ep == NULL case, determining
    788  * the length of the string to the first NUL or `/' and then calling
    789  * hash32_strn() involves unnecessary double-handling of the data.
    790  */
    791 uint32_t
    792 namei_hash(const char *name, const char **ep)
    793 {
    794 	uint32_t	hash;
    795 
    796 	hash = HASH32_STR_INIT;
    797 	if (*ep != NULL) {
    798 		for (; name < *ep; name++)
    799 			hash = hash * 33 + *(const uint8_t *)name;
    800 	} else {
    801 		for (; *name != '\0' && *name != '/'; name++)
    802 			hash = hash * 33 + *(const uint8_t *)name;
    803 		*ep = name;
    804 	}
    805 	return (hash + (hash >> 5));
    806 }
    807 
    808 /*
    809  * Search a pathname.
    810  * This is a very central and rather complicated routine.
    811  *
    812  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
    813  * The starting directory is passed in. The pathname is descended
    814  * until done, or a symbolic link is encountered. The variable ni_more
    815  * is clear if the path is completed; it is set to one if a symbolic
    816  * link needing interpretation is encountered.
    817  *
    818  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
    819  * whether the name is to be looked up, created, renamed, or deleted.
    820  * When CREATE, RENAME, or DELETE is specified, information usable in
    821  * creating, renaming, or deleting a directory entry may be calculated.
    822  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
    823  * locked.  Otherwise the parent directory is not returned. If the target
    824  * of the pathname exists and LOCKLEAF is or'ed into the flag the target
    825  * is returned locked, otherwise it is returned unlocked.  When creating
    826  * or renaming and LOCKPARENT is specified, the target may not be ".".
    827  * When deleting and LOCKPARENT is specified, the target may be ".".
    828  *
    829  * Overall outline of lookup:
    830  *
    831  * dirloop:
    832  *	identify next component of name at ndp->ni_ptr
    833  *	handle degenerate case where name is null string
    834  *	if .. and crossing mount points and on mounted filesys, find parent
    835  *	call VOP_LOOKUP routine for next component name
    836  *	    directory vnode returned in ni_dvp, locked.
    837  *	    component vnode returned in ni_vp (if it exists), locked.
    838  *	if result vnode is mounted on and crossing mount points,
    839  *	    find mounted on vnode
    840  *	if more components of name, do next level at dirloop
    841  *	return the answer in ni_vp, locked if LOCKLEAF set
    842  *	    if LOCKPARENT set, return locked parent in ni_dvp
    843  */
    844 
    845 /*
    846  * Begin lookup().
    847  */
    848 static int
    849 lookup_start(struct namei_state *state, struct vnode *startdir)
    850 {
    851 	const char *cp;			/* pointer into pathname argument */
    852 
    853 	struct componentname *cnp = state->cnp;
    854 	struct nameidata *ndp = state->ndp;
    855 
    856 	KASSERT(cnp == &ndp->ni_cnd);
    857 
    858 	state->lookup_alldone = 0;
    859 	state->dp = NULL;
    860 
    861 	/*
    862 	 * Setup: break out flag bits into variables.
    863 	 */
    864 	state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
    865 	if (cnp->cn_nameiop == DELETE)
    866 		state->docache = 0;
    867 	state->rdonly = cnp->cn_flags & RDONLY;
    868 	ndp->ni_dvp = NULL;
    869 	cnp->cn_flags &= ~ISSYMLINK;
    870 	state->dp = startdir;
    871 
    872 	/*
    873 	 * If we have a leading string of slashes, remove them, and just make
    874 	 * sure the current node is a directory.
    875 	 */
    876 	cp = cnp->cn_nameptr;
    877 	if (*cp == '/') {
    878 		do {
    879 			cp++;
    880 		} while (*cp == '/');
    881 		ndp->ni_pathlen -= cp - cnp->cn_nameptr;
    882 		cnp->cn_nameptr = cp;
    883 
    884 		if (state->dp->v_type != VDIR) {
    885 			vput(state->dp);
    886 			return ENOTDIR;
    887 		}
    888 
    889 		/*
    890 		 * If we've exhausted the path name, then just return the
    891 		 * current node.
    892 		 */
    893 		if (cnp->cn_nameptr[0] == '\0') {
    894 			ndp->ni_vp = state->dp;
    895 			cnp->cn_flags |= ISLASTCN;
    896 
    897 			/* bleh */
    898 			state->lookup_alldone = 1;
    899 			return 0;
    900 		}
    901 	}
    902 
    903 	return 0;
    904 }
    905 
    906 static int
    907 lookup_parsepath(struct namei_state *state)
    908 {
    909 	const char *cp;			/* pointer into pathname argument */
    910 
    911 	struct componentname *cnp = state->cnp;
    912 	struct nameidata *ndp = state->ndp;
    913 
    914 	KASSERT(cnp == &ndp->ni_cnd);
    915 
    916 	/*
    917 	 * Search a new directory.
    918 	 *
    919 	 * The cn_hash value is for use by vfs_cache.
    920 	 * The last component of the filename is left accessible via
    921 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    922 	 * the name set the SAVENAME flag. When done, they assume
    923 	 * responsibility for freeing the pathname buffer.
    924 	 *
    925 	 * At this point, our only vnode state is that "dp" is held and locked.
    926 	 */
    927 	cnp->cn_consume = 0;
    928 	cp = NULL;
    929 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
    930 	cnp->cn_namelen = cp - cnp->cn_nameptr;
    931 	if (cnp->cn_namelen > NAME_MAX) {
    932 		vput(state->dp);
    933 		ndp->ni_dvp = NULL;
    934 		return ENAMETOOLONG;
    935 	}
    936 #ifdef NAMEI_DIAGNOSTIC
    937 	{ char c = *cp;
    938 	*(char *)cp = '\0';
    939 	printf("{%s}: ", cnp->cn_nameptr);
    940 	*(char *)cp = c; }
    941 #endif /* NAMEI_DIAGNOSTIC */
    942 	ndp->ni_pathlen -= cnp->cn_namelen;
    943 	ndp->ni_next = cp;
    944 	/*
    945 	 * If this component is followed by a slash, then move the pointer to
    946 	 * the next component forward, and remember that this component must be
    947 	 * a directory.
    948 	 */
    949 	if (*cp == '/') {
    950 		do {
    951 			cp++;
    952 		} while (*cp == '/');
    953 		state->slashes = cp - ndp->ni_next;
    954 		ndp->ni_pathlen -= state->slashes;
    955 		ndp->ni_next = cp;
    956 		cnp->cn_flags |= REQUIREDIR;
    957 	} else {
    958 		state->slashes = 0;
    959 		cnp->cn_flags &= ~REQUIREDIR;
    960 	}
    961 	/*
    962 	 * We do special processing on the last component, whether or not it's
    963 	 * a directory.  Cache all intervening lookups, but not the final one.
    964 	 */
    965 	if (*cp == '\0') {
    966 		if (state->docache)
    967 			cnp->cn_flags |= MAKEENTRY;
    968 		else
    969 			cnp->cn_flags &= ~MAKEENTRY;
    970 		cnp->cn_flags |= ISLASTCN;
    971 	} else {
    972 		cnp->cn_flags |= MAKEENTRY;
    973 		cnp->cn_flags &= ~ISLASTCN;
    974 	}
    975 	if (cnp->cn_namelen == 2 &&
    976 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
    977 		cnp->cn_flags |= ISDOTDOT;
    978 	else
    979 		cnp->cn_flags &= ~ISDOTDOT;
    980 
    981 	return 0;
    982 }
    983 
    984 static int
    985 lookup_once(struct namei_state *state)
    986 {
    987 	struct vnode *tdp;		/* saved dp */
    988 	struct mount *mp;		/* mount table entry */
    989 	struct lwp *l = curlwp;
    990 	int error;
    991 
    992 	struct componentname *cnp = state->cnp;
    993 	struct nameidata *ndp = state->ndp;
    994 
    995 	KASSERT(cnp == &ndp->ni_cnd);
    996 
    997 	/*
    998 	 * Handle "..": two special cases.
    999 	 * 1. If at root directory (e.g. after chroot)
   1000 	 *    or at absolute root directory
   1001 	 *    then ignore it so can't get out.
   1002 	 * 1a. If at the root of the emulation filesystem go to the real
   1003 	 *    root. So "/../<path>" is always absolute.
   1004 	 * 1b. If we have somehow gotten out of a jail, warn
   1005 	 *    and also ignore it so we can't get farther out.
   1006 	 * 2. If this vnode is the root of a mounted
   1007 	 *    filesystem, then replace it with the
   1008 	 *    vnode which was mounted on so we take the
   1009 	 *    .. in the other file system.
   1010 	 */
   1011 	if (cnp->cn_flags & ISDOTDOT) {
   1012 		struct proc *p = l->l_proc;
   1013 
   1014 		for (;;) {
   1015 			if (state->dp == ndp->ni_rootdir || state->dp == rootvnode) {
   1016 				ndp->ni_dvp = state->dp;
   1017 				ndp->ni_vp = state->dp;
   1018 				vref(state->dp);
   1019 				return 0;
   1020 			}
   1021 			if (ndp->ni_rootdir != rootvnode) {
   1022 				int retval;
   1023 
   1024 				VOP_UNLOCK(state->dp);
   1025 				retval = vn_isunder(state->dp, ndp->ni_rootdir, l);
   1026 				vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1027 				if (!retval) {
   1028 				    /* Oops! We got out of jail! */
   1029 				    log(LOG_WARNING,
   1030 					"chrooted pid %d uid %d (%s) "
   1031 					"detected outside of its chroot\n",
   1032 					p->p_pid, kauth_cred_geteuid(l->l_cred),
   1033 					p->p_comm);
   1034 				    /* Put us at the jail root. */
   1035 				    vput(state->dp);
   1036 				    state->dp = ndp->ni_rootdir;
   1037 				    ndp->ni_dvp = state->dp;
   1038 				    ndp->ni_vp = state->dp;
   1039 				    vref(state->dp);
   1040 				    vref(state->dp);
   1041 				    vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1042 				    return 0;
   1043 				}
   1044 			}
   1045 			if ((state->dp->v_vflag & VV_ROOT) == 0 ||
   1046 			    (cnp->cn_flags & NOCROSSMOUNT))
   1047 				break;
   1048 			tdp = state->dp;
   1049 			state->dp = state->dp->v_mount->mnt_vnodecovered;
   1050 			vput(tdp);
   1051 			vref(state->dp);
   1052 			vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1053 		}
   1054 	}
   1055 
   1056 	/*
   1057 	 * We now have a segment name to search for, and a directory to search.
   1058 	 * Again, our only vnode state is that "dp" is held and locked.
   1059 	 */
   1060 unionlookup:
   1061 	ndp->ni_dvp = state->dp;
   1062 	ndp->ni_vp = NULL;
   1063 	error = VOP_LOOKUP(state->dp, &ndp->ni_vp, cnp);
   1064 	if (error != 0) {
   1065 #ifdef DIAGNOSTIC
   1066 		if (ndp->ni_vp != NULL)
   1067 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
   1068 #endif /* DIAGNOSTIC */
   1069 #ifdef NAMEI_DIAGNOSTIC
   1070 		printf("not found\n");
   1071 #endif /* NAMEI_DIAGNOSTIC */
   1072 		if ((error == ENOENT) &&
   1073 		    (state->dp->v_vflag & VV_ROOT) &&
   1074 		    (state->dp->v_mount->mnt_flag & MNT_UNION)) {
   1075 			tdp = state->dp;
   1076 			state->dp = state->dp->v_mount->mnt_vnodecovered;
   1077 			vput(tdp);
   1078 			vref(state->dp);
   1079 			vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1080 			goto unionlookup;
   1081 		}
   1082 
   1083 		if (error != EJUSTRETURN)
   1084 			return error;
   1085 
   1086 		/*
   1087 		 * If this was not the last component, or there were trailing
   1088 		 * slashes, and we are not going to create a directory,
   1089 		 * then the name must exist.
   1090 		 */
   1091 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
   1092 			return ENOENT;
   1093 		}
   1094 
   1095 		/*
   1096 		 * If creating and at end of pathname, then can consider
   1097 		 * allowing file to be created.
   1098 		 */
   1099 		if (state->rdonly) {
   1100 			return EROFS;
   1101 		}
   1102 
   1103 		/*
   1104 		 * We return with ni_vp NULL to indicate that the entry
   1105 		 * doesn't currently exist, leaving a pointer to the
   1106 		 * (possibly locked) directory vnode in ndp->ni_dvp.
   1107 		 */
   1108 		state->lookup_alldone = 1;
   1109 		return (0);
   1110 	}
   1111 #ifdef NAMEI_DIAGNOSTIC
   1112 	printf("found\n");
   1113 #endif /* NAMEI_DIAGNOSTIC */
   1114 
   1115 	/*
   1116 	 * Take into account any additional components consumed by the
   1117 	 * underlying filesystem.  This will include any trailing slashes after
   1118 	 * the last component consumed.
   1119 	 */
   1120 	if (cnp->cn_consume > 0) {
   1121 		ndp->ni_pathlen -= cnp->cn_consume - state->slashes;
   1122 		ndp->ni_next += cnp->cn_consume - state->slashes;
   1123 		cnp->cn_consume = 0;
   1124 		if (ndp->ni_next[0] == '\0')
   1125 			cnp->cn_flags |= ISLASTCN;
   1126 	}
   1127 
   1128 	state->dp = ndp->ni_vp;
   1129 
   1130 	/*
   1131 	 * "state->dp" and "ndp->ni_dvp" are both locked and held,
   1132 	 * and may be the same vnode.
   1133 	 */
   1134 
   1135 	/*
   1136 	 * Check to see if the vnode has been mounted on;
   1137 	 * if so find the root of the mounted file system.
   1138 	 */
   1139 	while (state->dp->v_type == VDIR && (mp = state->dp->v_mountedhere) &&
   1140 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
   1141 		error = vfs_busy(mp, NULL);
   1142 		if (error != 0) {
   1143 			vput(state->dp);
   1144 			return error;
   1145 		}
   1146 		KASSERT(ndp->ni_dvp != state->dp);
   1147 		VOP_UNLOCK(ndp->ni_dvp);
   1148 		vput(state->dp);
   1149 		error = VFS_ROOT(mp, &tdp);
   1150 		vfs_unbusy(mp, false, NULL);
   1151 		if (error) {
   1152 			vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
   1153 			return error;
   1154 		}
   1155 		VOP_UNLOCK(tdp);
   1156 		ndp->ni_vp = state->dp = tdp;
   1157 		vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
   1158 		vn_lock(ndp->ni_vp, LK_EXCLUSIVE | LK_RETRY);
   1159 	}
   1160 
   1161 	return 0;
   1162 }
   1163 
   1164 static int
   1165 do_lookup(struct namei_state *state, struct vnode *startdir)
   1166 {
   1167 	int error = 0;
   1168 
   1169 	struct componentname *cnp = state->cnp;
   1170 	struct nameidata *ndp = state->ndp;
   1171 
   1172 	KASSERT(cnp == &ndp->ni_cnd);
   1173 
   1174 	error = lookup_start(state, startdir);
   1175 	if (error) {
   1176 		goto bad;
   1177 	}
   1178 	// XXX: this case should not be necessary given proper handling
   1179 	// of slashes elsewhere.
   1180 	if (state->lookup_alldone) {
   1181 		goto terminal;
   1182 	}
   1183 
   1184 dirloop:
   1185 	error = lookup_parsepath(state);
   1186 	if (error) {
   1187 		goto bad;
   1188 	}
   1189 
   1190 	error = lookup_once(state);
   1191 	if (error) {
   1192 		goto bad;
   1193 	}
   1194 	// XXX ought to be able to avoid this case too
   1195 	if (state->lookup_alldone) {
   1196 		/* this should NOT be "goto terminal;" */
   1197 		return 0;
   1198 	}
   1199 
   1200 	/*
   1201 	 * Check for symbolic link.  Back up over any slashes that we skipped,
   1202 	 * as we will need them again.
   1203 	 */
   1204 	if ((state->dp->v_type == VLNK) && (cnp->cn_flags & (FOLLOW|REQUIREDIR))) {
   1205 		ndp->ni_pathlen += state->slashes;
   1206 		ndp->ni_next -= state->slashes;
   1207 		cnp->cn_flags |= ISSYMLINK;
   1208 		return (0);
   1209 	}
   1210 
   1211 	/*
   1212 	 * Check for directory, if the component was followed by a series of
   1213 	 * slashes.
   1214 	 */
   1215 	if ((state->dp->v_type != VDIR) && (cnp->cn_flags & REQUIREDIR)) {
   1216 		error = ENOTDIR;
   1217 		KASSERT(state->dp != ndp->ni_dvp);
   1218 		vput(state->dp);
   1219 		goto bad;
   1220 	}
   1221 
   1222 	/*
   1223 	 * Not a symbolic link.  If this was not the last component, then
   1224 	 * continue at the next component, else return.
   1225 	 */
   1226 	if (!(cnp->cn_flags & ISLASTCN)) {
   1227 		cnp->cn_nameptr = ndp->ni_next;
   1228 		if (ndp->ni_dvp == state->dp) {
   1229 			vrele(ndp->ni_dvp);
   1230 		} else {
   1231 			vput(ndp->ni_dvp);
   1232 		}
   1233 		goto dirloop;
   1234 	}
   1235 
   1236 terminal:
   1237 	if (state->dp == ndp->ni_erootdir) {
   1238 		/*
   1239 		 * We are about to return the emulation root.
   1240 		 * This isn't a good idea because code might repeatedly
   1241 		 * lookup ".." until the file matches that returned
   1242 		 * for "/" and loop forever.
   1243 		 * So convert it to the real root.
   1244 		 */
   1245 		if (ndp->ni_dvp == state->dp)
   1246 			vrele(state->dp);
   1247 		else
   1248 			if (ndp->ni_dvp != NULL)
   1249 				vput(ndp->ni_dvp);
   1250 		ndp->ni_dvp = NULL;
   1251 		vput(state->dp);
   1252 		state->dp = ndp->ni_rootdir;
   1253 		vref(state->dp);
   1254 		vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1255 		ndp->ni_vp = state->dp;
   1256 	}
   1257 
   1258 	/*
   1259 	 * If the caller requested the parent node (i.e.
   1260 	 * it's a CREATE, DELETE, or RENAME), and we don't have one
   1261 	 * (because this is the root directory), then we must fail.
   1262 	 */
   1263 	if (ndp->ni_dvp == NULL && cnp->cn_nameiop != LOOKUP) {
   1264 		switch (cnp->cn_nameiop) {
   1265 		case CREATE:
   1266 			error = EEXIST;
   1267 			break;
   1268 		case DELETE:
   1269 		case RENAME:
   1270 			error = EBUSY;
   1271 			break;
   1272 		default:
   1273 			KASSERT(0);
   1274 		}
   1275 		vput(state->dp);
   1276 		goto bad;
   1277 	}
   1278 
   1279 	/*
   1280 	 * Disallow directory write attempts on read-only lookups.
   1281 	 * Prefers EEXIST over EROFS for the CREATE case.
   1282 	 */
   1283 	if (state->rdonly &&
   1284 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
   1285 		error = EROFS;
   1286 		if (state->dp != ndp->ni_dvp) {
   1287 			vput(state->dp);
   1288 		}
   1289 		goto bad;
   1290 	}
   1291 	if ((cnp->cn_flags & LOCKLEAF) == 0) {
   1292 		VOP_UNLOCK(state->dp);
   1293 	}
   1294 	return (0);
   1295 
   1296 bad:
   1297 	ndp->ni_vp = NULL;
   1298 	return (error);
   1299 }
   1300 
   1301 /*
   1302  * Externally visible interfaces used by nfsd (bletch, yuk, XXX)
   1303  *
   1304  * The "index" version differs from the "main" version in that it's
   1305  * called from a different place in a different context. For now I
   1306  * want to be able to shuffle code in from one call site without
   1307  * affecting the other.
   1308  */
   1309 
   1310 int
   1311 lookup_for_nfsd(struct nameidata *ndp, struct vnode *dp, int neverfollow)
   1312 {
   1313 	struct namei_state state;
   1314 	int error;
   1315 
   1316 	struct iovec aiov;
   1317 	struct uio auio;
   1318 	int linklen;
   1319 	char *cp;
   1320 
   1321 	ndp->ni_pnbuf = ndp->ni_pathbuf->pb_path;
   1322 	namei_init(&state, ndp);
   1323 
   1324 	/*
   1325 	 * BEGIN wodge of code from nfsd
   1326 	 */
   1327 
   1328 	vref(dp);
   1329 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
   1330 
   1331     for (;;) {
   1332 
   1333 	state.cnp->cn_nameptr = state.ndp->ni_pnbuf;
   1334 
   1335 	/*
   1336 	 * END wodge of code from nfsd
   1337 	 */
   1338 
   1339 	error = do_lookup(&state, dp);
   1340 	if (error) {
   1341 		/* BEGIN from nfsd */
   1342 		if (ndp->ni_dvp) {
   1343 			vput(ndp->ni_dvp);
   1344 		}
   1345 		/* END from nfsd */
   1346 		namei_cleanup(&state);
   1347 		return error;
   1348 	}
   1349 
   1350 	/*
   1351 	 * BEGIN wodge of code from nfsd
   1352 	 */
   1353 
   1354 	/*
   1355 	 * Check for encountering a symbolic link
   1356 	 */
   1357 	if ((state.cnp->cn_flags & ISSYMLINK) == 0) {
   1358 		if ((state.cnp->cn_flags & LOCKPARENT) == 0 && state.ndp->ni_dvp) {
   1359 			if (state.ndp->ni_dvp == state.ndp->ni_vp) {
   1360 				vrele(state.ndp->ni_dvp);
   1361 			} else {
   1362 				vput(state.ndp->ni_dvp);
   1363 			}
   1364 		}
   1365 		return (0);
   1366 	} else {
   1367 		if (neverfollow) {
   1368 			error = EINVAL;
   1369 			goto out;
   1370 		}
   1371 		if (state.ndp->ni_loopcnt++ >= MAXSYMLINKS) {
   1372 			error = ELOOP;
   1373 			goto out;
   1374 		}
   1375 		if (state.ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
   1376 			error = VOP_ACCESS(ndp->ni_vp, VEXEC, state.cnp->cn_cred);
   1377 			if (error != 0)
   1378 				goto out;
   1379 		}
   1380 		cp = PNBUF_GET();
   1381 		aiov.iov_base = cp;
   1382 		aiov.iov_len = MAXPATHLEN;
   1383 		auio.uio_iov = &aiov;
   1384 		auio.uio_iovcnt = 1;
   1385 		auio.uio_offset = 0;
   1386 		auio.uio_rw = UIO_READ;
   1387 		auio.uio_resid = MAXPATHLEN;
   1388 		UIO_SETUP_SYSSPACE(&auio);
   1389 		error = VOP_READLINK(ndp->ni_vp, &auio, state.cnp->cn_cred);
   1390 		if (error) {
   1391 			PNBUF_PUT(cp);
   1392 			goto out;
   1393 		}
   1394 		linklen = MAXPATHLEN - auio.uio_resid;
   1395 		if (linklen == 0) {
   1396 			PNBUF_PUT(cp);
   1397 			error = ENOENT;
   1398 			goto out;
   1399 		}
   1400 		if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
   1401 			PNBUF_PUT(cp);
   1402 			error = ENAMETOOLONG;
   1403 			goto out;
   1404 		}
   1405 		if (ndp->ni_pathlen > 1) {
   1406 			/* includes a null-terminator */
   1407 			memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
   1408 		} else {
   1409 			cp[linklen] = '\0';
   1410 		}
   1411 		state.ndp->ni_pathlen += linklen;
   1412 		memcpy(state.ndp->ni_pnbuf, cp, state.ndp->ni_pathlen);
   1413 		PNBUF_PUT(cp);
   1414 		vput(state.ndp->ni_vp);
   1415 		dp = state.ndp->ni_dvp;
   1416 
   1417 		/*
   1418 		 * Check if root directory should replace current directory.
   1419 		 */
   1420 		if (state.ndp->ni_pnbuf[0] == '/') {
   1421 			vput(dp);
   1422 			dp = ndp->ni_rootdir;
   1423 			vref(dp);
   1424 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
   1425 		}
   1426 	}
   1427 
   1428     }
   1429  out:
   1430 	vput(state.ndp->ni_vp);
   1431 	vput(state.ndp->ni_dvp);
   1432 	state.ndp->ni_vp = NULL;
   1433 
   1434 	/*
   1435 	 * END wodge of code from nfsd
   1436 	 */
   1437 	namei_cleanup(&state);
   1438 
   1439 	return error;
   1440 }
   1441 
   1442 int
   1443 lookup_for_nfsd_index(struct nameidata *ndp, struct vnode *startdir)
   1444 {
   1445 	struct namei_state state;
   1446 	int error;
   1447 
   1448 	vref(startdir);
   1449 
   1450 	ndp->ni_pnbuf = ndp->ni_pathbuf->pb_path;
   1451 	ndp->ni_cnd.cn_nameptr = ndp->ni_pnbuf;
   1452 
   1453 	namei_init(&state, ndp);
   1454 	error = do_lookup(&state, startdir);
   1455 	namei_cleanup(&state);
   1456 
   1457 	return error;
   1458 }
   1459 
   1460 /*
   1461  * Reacquire a path name component.
   1462  * dvp is locked on entry and exit.
   1463  * *vpp is locked on exit unless it's NULL.
   1464  */
   1465 int
   1466 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
   1467 {
   1468 	int rdonly;			/* lookup read-only flag bit */
   1469 	int error = 0;
   1470 #ifdef DEBUG
   1471 	uint32_t newhash;		/* DEBUG: check name hash */
   1472 	const char *cp;			/* DEBUG: check name ptr/len */
   1473 #endif /* DEBUG */
   1474 
   1475 	/*
   1476 	 * Setup: break out flag bits into variables.
   1477 	 */
   1478 	rdonly = cnp->cn_flags & RDONLY;
   1479 	cnp->cn_flags &= ~ISSYMLINK;
   1480 
   1481 	/*
   1482 	 * Search a new directory.
   1483 	 *
   1484 	 * The cn_hash value is for use by vfs_cache.
   1485 	 * The last component of the filename is left accessible via
   1486 	 * cnp->cn_nameptr for callers that need the name. Callers needing
   1487 	 * the name set the SAVENAME flag. When done, they assume
   1488 	 * responsibility for freeing the pathname buffer.
   1489 	 */
   1490 #ifdef DEBUG
   1491 	cp = NULL;
   1492 	newhash = namei_hash(cnp->cn_nameptr, &cp);
   1493 	if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
   1494 		panic("relookup: bad hash");
   1495 	if (cnp->cn_namelen != cp - cnp->cn_nameptr)
   1496 		panic("relookup: bad len");
   1497 	while (*cp == '/')
   1498 		cp++;
   1499 	if (*cp != 0)
   1500 		panic("relookup: not last component");
   1501 #endif /* DEBUG */
   1502 
   1503 	/*
   1504 	 * Check for degenerate name (e.g. / or "")
   1505 	 * which is a way of talking about a directory,
   1506 	 * e.g. like "/." or ".".
   1507 	 */
   1508 	if (cnp->cn_nameptr[0] == '\0')
   1509 		panic("relookup: null name");
   1510 
   1511 	if (cnp->cn_flags & ISDOTDOT)
   1512 		panic("relookup: lookup on dot-dot");
   1513 
   1514 	/*
   1515 	 * We now have a segment name to search for, and a directory to search.
   1516 	 */
   1517 	cnp->cn_flags |= INRELOOKUP;
   1518 	error = VOP_LOOKUP(dvp, vpp, cnp);
   1519 	cnp->cn_flags &= ~INRELOOKUP;
   1520 	if ((error) != 0) {
   1521 #ifdef DIAGNOSTIC
   1522 		if (*vpp != NULL)
   1523 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
   1524 #endif
   1525 		if (error != EJUSTRETURN)
   1526 			goto bad;
   1527 	}
   1528 
   1529 #ifdef DIAGNOSTIC
   1530 	/*
   1531 	 * Check for symbolic link
   1532 	 */
   1533 	if (*vpp && (*vpp)->v_type == VLNK && (cnp->cn_flags & FOLLOW))
   1534 		panic("relookup: symlink found");
   1535 #endif
   1536 
   1537 	/*
   1538 	 * Check for read-only lookups.
   1539 	 */
   1540 	if (rdonly && cnp->cn_nameiop != LOOKUP) {
   1541 		error = EROFS;
   1542 		if (*vpp) {
   1543 			vput(*vpp);
   1544 		}
   1545 		goto bad;
   1546 	}
   1547 	if (cnp->cn_flags & SAVESTART)
   1548 		vref(dvp);
   1549 	return (0);
   1550 
   1551 bad:
   1552 	*vpp = NULL;
   1553 	return (error);
   1554 }
   1555 
   1556 /*
   1557  * namei_simple - simple forms of namei.
   1558  *
   1559  * These are wrappers to allow the simple case callers of namei to be
   1560  * left alone while everything else changes under them.
   1561  */
   1562 
   1563 /* Flags */
   1564 struct namei_simple_flags_type {
   1565 	int dummy;
   1566 };
   1567 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
   1568 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
   1569 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
   1570 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
   1571 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
   1572 
   1573 static
   1574 int
   1575 namei_simple_convert_flags(namei_simple_flags_t sflags)
   1576 {
   1577 	if (sflags == NSM_NOFOLLOW_NOEMULROOT)
   1578 		return NOFOLLOW | 0;
   1579 	if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
   1580 		return NOFOLLOW | TRYEMULROOT;
   1581 	if (sflags == NSM_FOLLOW_NOEMULROOT)
   1582 		return FOLLOW | 0;
   1583 	if (sflags == NSM_FOLLOW_TRYEMULROOT)
   1584 		return FOLLOW | TRYEMULROOT;
   1585 	panic("namei_simple_convert_flags: bogus sflags\n");
   1586 	return 0;
   1587 }
   1588 
   1589 int
   1590 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
   1591 			struct vnode **vp_ret)
   1592 {
   1593 	struct nameidata nd;
   1594 	struct pathbuf *pb;
   1595 	int err;
   1596 
   1597 	pb = pathbuf_create(path);
   1598 	if (pb == NULL) {
   1599 		return ENOMEM;
   1600 	}
   1601 
   1602 	NDINIT(&nd,
   1603 		LOOKUP,
   1604 		namei_simple_convert_flags(sflags),
   1605 		pb);
   1606 	err = namei(&nd);
   1607 	if (err != 0) {
   1608 		pathbuf_destroy(pb);
   1609 		return err;
   1610 	}
   1611 	*vp_ret = nd.ni_vp;
   1612 	pathbuf_destroy(pb);
   1613 	return 0;
   1614 }
   1615 
   1616 int
   1617 namei_simple_user(const char *path, namei_simple_flags_t sflags,
   1618 			struct vnode **vp_ret)
   1619 {
   1620 	struct pathbuf *pb;
   1621 	struct nameidata nd;
   1622 	int err;
   1623 
   1624 	err = pathbuf_copyin(path, &pb);
   1625 	if (err) {
   1626 		return err;
   1627 	}
   1628 
   1629 	NDINIT(&nd,
   1630 		LOOKUP,
   1631 		namei_simple_convert_flags(sflags),
   1632 		pb);
   1633 	err = namei(&nd);
   1634 	if (err != 0) {
   1635 		pathbuf_destroy(pb);
   1636 		return err;
   1637 	}
   1638 	*vp_ret = nd.ni_vp;
   1639 	pathbuf_destroy(pb);
   1640 	return 0;
   1641 }
   1642