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