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