Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.236
      1 /*	$NetBSD: vfs_lookup.c,v 1.236 2024/12/07 02:11:42 riastradh 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.236 2024/12/07 02:11:42 riastradh Exp $");
     41 
     42 #ifdef _KERNEL_OPT
     43 #include "opt_magiclinks.h"
     44 #endif
     45 
     46 #include <sys/param.h>
     47 #include <sys/types.h>
     48 
     49 #include <sys/dirent.h>
     50 #include <sys/errno.h>
     51 #include <sys/filedesc.h>
     52 #include <sys/fstrans.h>
     53 #include <sys/hash.h>
     54 #include <sys/kauth.h>
     55 #include <sys/kernel.h>
     56 #include <sys/ktrace.h>
     57 #include <sys/mount.h>
     58 #include <sys/namei.h>
     59 #include <sys/proc.h>
     60 #include <sys/syslimits.h>
     61 #include <sys/syslog.h>
     62 #include <sys/systm.h>
     63 #include <sys/time.h>
     64 #include <sys/vnode.h>
     65 #include <sys/vnode_impl.h>
     66 
     67 #ifndef MAGICLINKS
     68 #define MAGICLINKS 0
     69 #endif
     70 
     71 int vfs_magiclinks = MAGICLINKS;
     72 
     73 __CTASSERT(MAXNAMLEN == NAME_MAX);
     74 
     75 /*
     76  * Substitute replacement text for 'magic' strings in symlinks.
     77  * Returns 0 if successful, and returns non-zero if an error
     78  * occurs.  (Currently, the only possible error is running out
     79  * of temporary pathname space.)
     80  *
     81  * Looks for "@<string>" and "@<string>/", where <string> is a
     82  * recognized 'magic' string.  Replaces the "@<string>" with the
     83  * appropriate replacement text.  (Note that in some cases the
     84  * replacement text may have zero length.)
     85  *
     86  * This would have been table driven, but the variance in
     87  * replacement strings (and replacement string lengths) made
     88  * that impractical.
     89  */
     90 #define	VNL(x)							\
     91 	(sizeof(x) - 1)
     92 
     93 #define	VO	'{'
     94 #define	VC	'}'
     95 
     96 #define	MATCH(str)						\
     97 	((termchar == '/' && i + VNL(str) == *len) ||		\
     98 	 (i + VNL(str) < *len &&				\
     99 	  cp[i + VNL(str)] == termchar)) &&			\
    100 	!strncmp((str), &cp[i], VNL(str))
    101 
    102 #define	SUBSTITUTE(m, s, sl)					\
    103 	if ((newlen + (sl)) >= MAXPATHLEN)			\
    104 		return 1;					\
    105 	i += VNL(m);						\
    106 	if (termchar != '/')					\
    107 		i++;						\
    108 	(void)memcpy(&tmp[newlen], (s), (sl));			\
    109 	newlen += (sl);						\
    110 	change = 1;						\
    111 	termchar = '/';
    112 
    113 static int
    114 symlink_magic(struct proc *p, char *cp, size_t *len)
    115 {
    116 	char *tmp;
    117 	size_t change, i, newlen, slen;
    118 	char termchar = '/';
    119 	char idtmp[11]; /* enough for 32 bit *unsigned* integer */
    120 
    121 
    122 	tmp = PNBUF_GET();
    123 	for (change = i = newlen = 0; i < *len; ) {
    124 		if (cp[i] != '@') {
    125 			tmp[newlen++] = cp[i++];
    126 			continue;
    127 		}
    128 
    129 		i++;
    130 
    131 		/* Check for @{var} syntax. */
    132 		if (cp[i] == VO) {
    133 			termchar = VC;
    134 			i++;
    135 		}
    136 
    137 		/*
    138 		 * The following checks should be ordered according
    139 		 * to frequency of use.
    140 		 */
    141 		if (MATCH("machine_arch")) {
    142 			slen = strlen(PROC_MACHINE_ARCH(p));
    143 			SUBSTITUTE("machine_arch", PROC_MACHINE_ARCH(p), slen);
    144 		} else if (MATCH("machine")) {
    145 			slen = VNL(MACHINE);
    146 			SUBSTITUTE("machine", MACHINE, slen);
    147 		} else if (MATCH("hostname")) {
    148 			SUBSTITUTE("hostname", hostname, hostnamelen);
    149 		} else if (MATCH("osrelease")) {
    150 			slen = strlen(osrelease);
    151 			SUBSTITUTE("osrelease", osrelease, slen);
    152 		} else if (MATCH("emul")) {
    153 			slen = strlen(p->p_emul->e_name);
    154 			SUBSTITUTE("emul", p->p_emul->e_name, slen);
    155 		} else if (MATCH("kernel_ident")) {
    156 			slen = strlen(kernel_ident);
    157 			SUBSTITUTE("kernel_ident", kernel_ident, slen);
    158 		} else if (MATCH("domainname")) {
    159 			SUBSTITUTE("domainname", domainname, domainnamelen);
    160 		} else if (MATCH("ostype")) {
    161 			slen = strlen(ostype);
    162 			SUBSTITUTE("ostype", ostype, slen);
    163 		} else if (MATCH("uid")) {
    164 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    165 			    kauth_cred_geteuid(kauth_cred_get()));
    166 			SUBSTITUTE("uid", idtmp, slen);
    167 		} else if (MATCH("ruid")) {
    168 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    169 			    kauth_cred_getuid(kauth_cred_get()));
    170 			SUBSTITUTE("ruid", idtmp, slen);
    171 		} else if (MATCH("gid")) {
    172 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    173 			    kauth_cred_getegid(kauth_cred_get()));
    174 			SUBSTITUTE("gid", idtmp, slen);
    175 		} else if (MATCH("rgid")) {
    176 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    177 			    kauth_cred_getgid(kauth_cred_get()));
    178 			SUBSTITUTE("rgid", idtmp, slen);
    179 		} else {
    180 			tmp[newlen++] = '@';
    181 			if (termchar == VC)
    182 				tmp[newlen++] = VO;
    183 		}
    184 	}
    185 
    186 	if (change) {
    187 		(void)memcpy(cp, tmp, newlen);
    188 		*len = newlen;
    189 	}
    190 	PNBUF_PUT(tmp);
    191 
    192 	return 0;
    193 }
    194 
    195 #undef VNL
    196 #undef VO
    197 #undef VC
    198 #undef MATCH
    199 #undef SUBSTITUTE
    200 
    201 ////////////////////////////////////////////////////////////
    202 
    203 /*
    204  * Determine the namei hash (for the namecache) for name.
    205  * If *ep != NULL, hash from name to ep-1.
    206  * If *ep == NULL, hash from name until the first NUL or '/', and
    207  * return the location of this termination character in *ep.
    208  *
    209  * This function returns an equivalent hash to the MI hash32_strn().
    210  * The latter isn't used because in the *ep == NULL case, determining
    211  * the length of the string to the first NUL or `/' and then calling
    212  * hash32_strn() involves unnecessary double-handling of the data.
    213  */
    214 uint32_t
    215 namei_hash(const char *name, const char **ep)
    216 {
    217 	uint32_t	hash;
    218 
    219 	hash = HASH32_STR_INIT;
    220 	if (*ep != NULL) {
    221 		for (; name < *ep; name++)
    222 			hash = hash * 33 + *(const uint8_t *)name;
    223 	} else {
    224 		for (; *name != '\0' && *name != '/'; name++)
    225 			hash = hash * 33 + *(const uint8_t *)name;
    226 		*ep = name;
    227 	}
    228 	return (hash + (hash >> 5));
    229 }
    230 
    231 ////////////////////////////////////////////////////////////
    232 
    233 /*
    234  * Sealed abstraction for pathnames.
    235  *
    236  * System-call-layer level code that is going to call namei should
    237  * first create a pathbuf and adjust all the bells and whistles on it
    238  * as needed by context.
    239  */
    240 
    241 struct pathbuf {
    242 	char *pb_path;
    243 	char *pb_pathcopy;
    244 	unsigned pb_pathcopyuses;
    245 };
    246 
    247 static struct pathbuf *
    248 pathbuf_create_raw(void)
    249 {
    250 	struct pathbuf *pb;
    251 
    252 	pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
    253 	pb->pb_path = PNBUF_GET();
    254 	if (pb->pb_path == NULL) {
    255 		kmem_free(pb, sizeof(*pb));
    256 		return NULL;
    257 	}
    258 	pb->pb_pathcopy = NULL;
    259 	pb->pb_pathcopyuses = 0;
    260 	return pb;
    261 }
    262 
    263 void
    264 pathbuf_destroy(struct pathbuf *pb)
    265 {
    266 
    267 	KASSERT(pb->pb_pathcopyuses == 0);
    268 	KASSERT(pb->pb_pathcopy == NULL);
    269 	PNBUF_PUT(pb->pb_path);
    270 	kmem_free(pb, sizeof(*pb));
    271 }
    272 
    273 struct pathbuf *
    274 pathbuf_assimilate(char *pnbuf)
    275 {
    276 	struct pathbuf *pb;
    277 
    278 	pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
    279 	pb->pb_path = pnbuf;
    280 	pb->pb_pathcopy = NULL;
    281 	pb->pb_pathcopyuses = 0;
    282 	return pb;
    283 }
    284 
    285 struct pathbuf *
    286 pathbuf_create(const char *path)
    287 {
    288 	struct pathbuf *pb;
    289 	int error;
    290 
    291 	pb = pathbuf_create_raw();
    292 	if (pb == NULL) {
    293 		return NULL;
    294 	}
    295 	error = copystr(path, pb->pb_path, PATH_MAX, NULL);
    296 	if (error != 0) {
    297 		KASSERT(!"kernel path too long in pathbuf_create");
    298 		/* make sure it's null-terminated, just in case */
    299 		pb->pb_path[PATH_MAX-1] = '\0';
    300 	}
    301 	return pb;
    302 }
    303 
    304 int
    305 pathbuf_copyin(const char *userpath, struct pathbuf **ret)
    306 {
    307 	struct pathbuf *pb;
    308 	int error;
    309 
    310 	pb = pathbuf_create_raw();
    311 	if (pb == NULL) {
    312 		return ENOMEM;
    313 	}
    314 	error = copyinstr(userpath, pb->pb_path, PATH_MAX, NULL);
    315 	if (error) {
    316 		pathbuf_destroy(pb);
    317 		return error;
    318 	}
    319 	*ret = pb;
    320 	return 0;
    321 }
    322 
    323 /*
    324  * XXX should not exist:
    325  *   1. whether a pointer is kernel or user should be statically checkable.
    326  *   2. copyin should be handled by the upper part of the syscall layer,
    327  *      not in here.
    328  */
    329 int
    330 pathbuf_maybe_copyin(const char *path, enum uio_seg seg, struct pathbuf **ret)
    331 {
    332 
    333 	if (seg == UIO_USERSPACE) {
    334 		return pathbuf_copyin(path, ret);
    335 	} else {
    336 		*ret = pathbuf_create(path);
    337 		if (*ret == NULL) {
    338 			return ENOMEM;
    339 		}
    340 		return 0;
    341 	}
    342 }
    343 
    344 /*
    345  * Get a copy of the path buffer as it currently exists. If this is
    346  * called after namei starts the results may be arbitrary.
    347  */
    348 void
    349 pathbuf_copystring(const struct pathbuf *pb, char *buf, size_t maxlen)
    350 {
    351 
    352 	strlcpy(buf, pb->pb_path, maxlen);
    353 }
    354 
    355 /*
    356  * These two functions allow access to a saved copy of the original
    357  * path string. The first copy should be gotten before namei is
    358  * called. Each copy that is gotten should be put back.
    359  */
    360 
    361 const char *
    362 pathbuf_stringcopy_get(struct pathbuf *pb)
    363 {
    364 
    365 	if (pb->pb_pathcopyuses == 0) {
    366 		pb->pb_pathcopy = PNBUF_GET();
    367 		strcpy(pb->pb_pathcopy, pb->pb_path);
    368 	}
    369 	pb->pb_pathcopyuses++;
    370 	return pb->pb_pathcopy;
    371 }
    372 
    373 void
    374 pathbuf_stringcopy_put(struct pathbuf *pb, const char *str)
    375 {
    376 
    377 	KASSERT(str == pb->pb_pathcopy);
    378 	KASSERT(pb->pb_pathcopyuses > 0);
    379 	pb->pb_pathcopyuses--;
    380 	if (pb->pb_pathcopyuses == 0) {
    381 		PNBUF_PUT(pb->pb_pathcopy);
    382 		pb->pb_pathcopy = NULL;
    383 	}
    384 }
    385 
    386 
    387 ////////////////////////////////////////////////////////////
    388 
    389 /*
    390  * namei: convert a pathname into a pointer to a (maybe-locked) vnode,
    391  * and maybe also its parent directory vnode, and assorted other guff.
    392  * See namei(9) for the interface documentation.
    393  *
    394  *
    395  * The FOLLOW flag is set when symbolic links are to be followed
    396  * when they occur at the end of the name translation process.
    397  * Symbolic links are always followed for all other pathname
    398  * components other than the last.
    399  *
    400  * The segflg defines whether the name is to be copied from user
    401  * space or kernel space.
    402  *
    403  * Overall outline of namei:
    404  *
    405  *	copy in name
    406  *	get starting directory
    407  *	while (!done && !error) {
    408  *		call lookup to search path.
    409  *		if symbolic link, massage name in buffer and continue
    410  *	}
    411  */
    412 
    413 /*
    414  * Search a pathname.
    415  * This is a very central and rather complicated routine.
    416  *
    417  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
    418  * The starting directory is passed in. The pathname is descended
    419  * until done, or a symbolic link is encountered. The variable ni_more
    420  * is clear if the path is completed; it is set to one if a symbolic
    421  * link needing interpretation is encountered.
    422  *
    423  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
    424  * whether the name is to be looked up, created, renamed, or deleted.
    425  * When CREATE, RENAME, or DELETE is specified, information usable in
    426  * creating, renaming, or deleting a directory entry may be calculated.
    427  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
    428  * locked.  Otherwise the parent directory is not returned. If the target
    429  * of the pathname exists and LOCKLEAF is or'ed into the flag the target
    430  * is returned locked, otherwise it is returned unlocked.  When creating
    431  * or renaming and LOCKPARENT is specified, the target may not be ".".
    432  * When deleting and LOCKPARENT is specified, the target may be ".".
    433  *
    434  * Overall outline of lookup:
    435  *
    436  * dirloop:
    437  *	identify next component of name at ndp->ni_ptr
    438  *	handle degenerate case where name is null string
    439  *	if .. and crossing mount points and on mounted filesys, find parent
    440  *	call VOP_LOOKUP routine for next component name
    441  *	    directory vnode returned in ni_dvp, locked.
    442  *	    component vnode returned in ni_vp (if it exists), locked.
    443  *	if result vnode is mounted on and crossing mount points,
    444  *	    find mounted on vnode
    445  *	if more components of name, do next level at dirloop
    446  *	return the answer in ni_vp, locked if LOCKLEAF set
    447  *	    if LOCKPARENT set, return locked parent in ni_dvp
    448  */
    449 
    450 
    451 /*
    452  * Internal state for a namei operation.
    453  *
    454  * cnp is always equal to &ndp->ni_cnp.
    455  */
    456 struct namei_state {
    457 	struct nameidata *ndp;
    458 	struct componentname *cnp;
    459 
    460 	int docache;			/* == 0 do not cache last component */
    461 	int rdonly;			/* lookup read-only flag bit */
    462 	int slashes;
    463 
    464 	unsigned attempt_retry:1;	/* true if error allows emul retry */
    465 	unsigned root_referenced:1;	/* true if ndp->ni_rootdir and
    466 					    ndp->ni_erootdir were referenced */
    467 };
    468 
    469 
    470 /*
    471  * Initialize the namei working state.
    472  */
    473 static void
    474 namei_init(struct namei_state *state, struct nameidata *ndp)
    475 {
    476 
    477 	state->ndp = ndp;
    478 	state->cnp = &ndp->ni_cnd;
    479 
    480 	state->docache = 0;
    481 	state->rdonly = 0;
    482 	state->slashes = 0;
    483 
    484 	state->root_referenced = 0;
    485 
    486 	KASSERTMSG((state->cnp->cn_cred != NULL), "namei: bad cred/proc");
    487 	KASSERTMSG(((state->cnp->cn_nameiop & (~OPMASK)) == 0),
    488 	    "namei: nameiop contaminated with flags: %08"PRIx32,
    489 	    state->cnp->cn_nameiop);
    490 	KASSERTMSG(((state->cnp->cn_flags & OPMASK) == 0),
    491 	    "name: flags contaminated with nameiops: %08"PRIx32,
    492 	    state->cnp->cn_flags);
    493 
    494 	/*
    495 	 * The buffer for name translation shall be the one inside the
    496 	 * pathbuf.
    497 	 */
    498 	state->ndp->ni_pnbuf = state->ndp->ni_pathbuf->pb_path;
    499 }
    500 
    501 /*
    502  * Clean up the working namei state, leaving things ready for return
    503  * from namei.
    504  */
    505 static void
    506 namei_cleanup(struct namei_state *state)
    507 {
    508 
    509 	KASSERT(state->cnp == &state->ndp->ni_cnd);
    510 
    511 	if (state->root_referenced) {
    512 		if (state->ndp->ni_rootdir != NULL)
    513 			vrele(state->ndp->ni_rootdir);
    514 		if (state->ndp->ni_erootdir != NULL)
    515 			vrele(state->ndp->ni_erootdir);
    516 	}
    517 }
    518 
    519 //////////////////////////////
    520 
    521 /*
    522  * Get the directory context.
    523  * Initializes the rootdir and erootdir state and returns a reference
    524  * to the starting dir.
    525  */
    526 static struct vnode *
    527 namei_getstartdir(struct namei_state *state)
    528 {
    529 	struct nameidata *ndp = state->ndp;
    530 	struct componentname *cnp = state->cnp;
    531 	struct cwdinfo *cwdi;		/* pointer to cwd state */
    532 	struct lwp *self = curlwp;	/* thread doing namei() */
    533 	struct vnode *rootdir, *erootdir, *curdir, *startdir;
    534 
    535 	if (state->root_referenced) {
    536 		if (state->ndp->ni_rootdir != NULL)
    537 			vrele(state->ndp->ni_rootdir);
    538 		if (state->ndp->ni_erootdir != NULL)
    539 			vrele(state->ndp->ni_erootdir);
    540 		state->root_referenced = 0;
    541 	}
    542 
    543 	cwdi = self->l_proc->p_cwdi;
    544 	rw_enter(&cwdi->cwdi_lock, RW_READER);
    545 
    546 	/* root dir */
    547 	if (cwdi->cwdi_rdir == NULL || (cnp->cn_flags & NOCHROOT)) {
    548 		rootdir = rootvnode;
    549 	} else {
    550 		rootdir = cwdi->cwdi_rdir;
    551 	}
    552 
    553 	/* emulation root dir, if any */
    554 	if ((cnp->cn_flags & TRYEMULROOT) == 0) {
    555 		/* if we don't want it, don't fetch it */
    556 		erootdir = NULL;
    557 	} else if (cnp->cn_flags & EMULROOTSET) {
    558 		/* explicitly set emulroot; "/../" doesn't override this */
    559 		erootdir = ndp->ni_erootdir;
    560 	} else if (!strncmp(ndp->ni_pnbuf, "/../", 4)) {
    561 		/* explicit reference to real rootdir */
    562 		erootdir = NULL;
    563 	} else {
    564 		/* may be null */
    565 		erootdir = cwdi->cwdi_edir;
    566 	}
    567 
    568 	/* current dir */
    569 	curdir = cwdi->cwdi_cdir;
    570 
    571 	if (ndp->ni_pnbuf[0] != '/') {
    572 		if (ndp->ni_atdir != NULL) {
    573 			startdir = ndp->ni_atdir;
    574 		} else {
    575 			startdir = curdir;
    576 		}
    577 		erootdir = NULL;
    578 	} else if (cnp->cn_flags & TRYEMULROOT && erootdir != NULL) {
    579 		startdir = erootdir;
    580 	} else {
    581 		startdir = rootdir;
    582 		erootdir = NULL;
    583 	}
    584 
    585 	state->ndp->ni_rootdir = rootdir;
    586 	state->ndp->ni_erootdir = erootdir;
    587 
    588 	/*
    589 	 * Get a reference to the start dir so we can safely unlock cwdi.
    590 	 *
    591 	 * Must hold references to rootdir and erootdir while we're running.
    592 	 * A multithreaded process may chroot during namei.
    593 	 */
    594 	if (startdir != NULL)
    595 		vref(startdir);
    596 	if (state->ndp->ni_rootdir != NULL)
    597 		vref(state->ndp->ni_rootdir);
    598 	if (state->ndp->ni_erootdir != NULL)
    599 		vref(state->ndp->ni_erootdir);
    600 	state->root_referenced = 1;
    601 
    602 	rw_exit(&cwdi->cwdi_lock);
    603 	return startdir;
    604 }
    605 
    606 /*
    607  * Get the directory context for the nfsd case, in parallel to
    608  * getstartdir. Initializes the rootdir and erootdir state and
    609  * returns a reference to the passed-in starting dir.
    610  */
    611 static struct vnode *
    612 namei_getstartdir_for_nfsd(struct namei_state *state)
    613 {
    614 
    615 	KASSERT(state->ndp->ni_atdir != NULL);
    616 
    617 	/* always use the real root, and never set an emulation root */
    618 	if (rootvnode == NULL) {
    619 		return NULL;
    620 	}
    621 	state->ndp->ni_rootdir = rootvnode;
    622 	state->ndp->ni_erootdir = NULL;
    623 
    624 	vref(state->ndp->ni_atdir);
    625 	KASSERT(! state->root_referenced);
    626 	vref(state->ndp->ni_rootdir);
    627 	state->root_referenced = 1;
    628 	return state->ndp->ni_atdir;
    629 }
    630 
    631 
    632 /*
    633  * Ktrace the namei operation.
    634  */
    635 static void
    636 namei_ktrace(struct namei_state *state)
    637 {
    638 	struct nameidata *ndp = state->ndp;
    639 	struct componentname *cnp = state->cnp;
    640 	struct lwp *self = curlwp;	/* thread doing namei() */
    641 	const char *emul_path;
    642 
    643 	if (ktrpoint(KTR_NAMEI)) {
    644 		if (ndp->ni_erootdir != NULL) {
    645 			/*
    646 			 * To make any sense, the trace entry need to have the
    647 			 * text of the emulation path prepended.
    648 			 * Usually we can get this from the current process,
    649 			 * but when called from emul_find_interp() it is only
    650 			 * in the exec_package - so we get it passed in ni_next
    651 			 * (this is a hack).
    652 			 */
    653 			if (cnp->cn_flags & EMULROOTSET)
    654 				emul_path = ndp->ni_next;
    655 			else
    656 				emul_path = self->l_proc->p_emul->e_path;
    657 			ktrnamei2(emul_path, strlen(emul_path),
    658 			    ndp->ni_pnbuf, ndp->ni_pathlen);
    659 		} else
    660 			ktrnamei(ndp->ni_pnbuf, ndp->ni_pathlen);
    661 	}
    662 }
    663 
    664 /*
    665  * Start up namei. Find the root dir and cwd, establish the starting
    666  * directory for lookup, and lock it. Also calls ktrace when
    667  * appropriate.
    668  */
    669 static int
    670 namei_start(struct namei_state *state, int isnfsd,
    671     struct vnode **startdir_ret)
    672 {
    673 	struct nameidata *ndp = state->ndp;
    674 	struct vnode *startdir;
    675 
    676 	/* length includes null terminator (was originally from copyinstr) */
    677 	ndp->ni_pathlen = strlen(ndp->ni_pnbuf) + 1;
    678 
    679 	/*
    680 	 * POSIX.1 requirement: "" is not a valid file name.
    681 	 */
    682 	if (ndp->ni_pathlen == 1) {
    683 		ndp->ni_erootdir = NULL;
    684 		return ENOENT;
    685 	}
    686 
    687 	ndp->ni_loopcnt = 0;
    688 
    689 	/* Get starting directory, set up root, and ktrace. */
    690 	if (isnfsd) {
    691 		startdir = namei_getstartdir_for_nfsd(state);
    692 		/* no ktrace */
    693 	} else {
    694 		startdir = namei_getstartdir(state);
    695 		namei_ktrace(state);
    696 	}
    697 
    698 	if (startdir == NULL) {
    699 		return ENOENT;
    700 	}
    701 
    702 	/* NDAT may feed us with a non directory namei_getstartdir */
    703 	if (startdir->v_type != VDIR) {
    704 		vrele(startdir);
    705 		return ENOTDIR;
    706 	}
    707 
    708 	*startdir_ret = startdir;
    709 	return 0;
    710 }
    711 
    712 /*
    713  * Check for being at a symlink that we're going to follow.
    714  */
    715 static inline int
    716 namei_atsymlink(struct namei_state *state, struct vnode *foundobj)
    717 {
    718 
    719 	return (foundobj->v_type == VLNK) &&
    720 	    (state->cnp->cn_flags & (FOLLOW|REQUIREDIR));
    721 }
    722 
    723 /*
    724  * Follow a symlink.
    725  *
    726  * Updates searchdir. inhibitmagic causes magic symlinks to not be
    727  * interpreted; this is used by nfsd.
    728  *
    729  * Unlocks foundobj on success (ugh)
    730  */
    731 static inline int
    732 namei_follow(struct namei_state *state, int inhibitmagic,
    733     struct vnode *searchdir, struct vnode *foundobj,
    734     struct vnode **newsearchdir_ret)
    735 {
    736 	struct nameidata *ndp = state->ndp;
    737 	struct componentname *cnp = state->cnp;
    738 
    739 	struct lwp *self = curlwp;	/* thread doing namei() */
    740 	struct iovec aiov;		/* uio for reading symbolic links */
    741 	struct uio auio;
    742 	char *cp;			/* pointer into pathname argument */
    743 	size_t linklen;
    744 	int error;
    745 
    746 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
    747 		return ELOOP;
    748 	}
    749 
    750 	vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
    751 	if (foundobj->v_mount->mnt_flag & MNT_SYMPERM) {
    752 		error = VOP_ACCESS(foundobj, VEXEC, cnp->cn_cred);
    753 		if (error != 0) {
    754 			VOP_UNLOCK(foundobj);
    755 			return error;
    756 		}
    757 	}
    758 
    759 	/* FUTURE: fix this to not use a second buffer */
    760 	cp = PNBUF_GET();
    761 	aiov.iov_base = cp;
    762 	aiov.iov_len = MAXPATHLEN;
    763 	auio.uio_iov = &aiov;
    764 	auio.uio_iovcnt = 1;
    765 	auio.uio_offset = 0;
    766 	auio.uio_rw = UIO_READ;
    767 	auio.uio_resid = MAXPATHLEN;
    768 	UIO_SETUP_SYSSPACE(&auio);
    769 	error = VOP_READLINK(foundobj, &auio, cnp->cn_cred);
    770 	VOP_UNLOCK(foundobj);
    771 	if (error) {
    772 		PNBUF_PUT(cp);
    773 		return error;
    774 	}
    775 	linklen = MAXPATHLEN - auio.uio_resid;
    776 	if (linklen == 0) {
    777 		PNBUF_PUT(cp);
    778 		return ENOENT;
    779 	}
    780 
    781 	/*
    782 	 * Do symlink substitution, if appropriate, and
    783 	 * check length for potential overflow.
    784 	 *
    785 	 * Inhibit symlink substitution for nfsd.
    786 	 * XXX: This is how it was before; is that a bug or a feature?
    787 	 */
    788 	if ((!inhibitmagic && vfs_magiclinks &&
    789 		symlink_magic(self->l_proc, cp, &linklen)) ||
    790 	    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
    791 		PNBUF_PUT(cp);
    792 		return ENAMETOOLONG;
    793 	}
    794 	if (ndp->ni_pathlen > 1) {
    795 		/* includes a null-terminator */
    796 		memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
    797 	} else {
    798 		cp[linklen] = '\0';
    799 	}
    800 	ndp->ni_pathlen += linklen;
    801 	memcpy(ndp->ni_pnbuf, cp, ndp->ni_pathlen);
    802 	PNBUF_PUT(cp);
    803 
    804 	/* we're now starting from the beginning of the buffer again */
    805 	cnp->cn_nameptr = ndp->ni_pnbuf;
    806 
    807 	/*
    808 	 * Check if root directory should replace current directory.
    809 	 */
    810 	if (ndp->ni_pnbuf[0] == '/') {
    811 		vrele(searchdir);
    812 		/* Keep absolute symbolic links inside emulation root */
    813 		searchdir = ndp->ni_erootdir;
    814 		if (searchdir == NULL ||
    815 		    (ndp->ni_pnbuf[1] == '.'
    816 			&& ndp->ni_pnbuf[2] == '.'
    817 			&& ndp->ni_pnbuf[3] == '/')) {
    818 			ndp->ni_erootdir = NULL;
    819 			searchdir = ndp->ni_rootdir;
    820 		}
    821 		vref(searchdir);
    822 		while (cnp->cn_nameptr[0] == '/') {
    823 			cnp->cn_nameptr++;
    824 			ndp->ni_pathlen--;
    825 		}
    826 	}
    827 
    828 	*newsearchdir_ret = searchdir;
    829 	return 0;
    830 }
    831 
    832 //////////////////////////////
    833 
    834 /*
    835  * Inspect the leading path component and update the state accordingly.
    836  */
    837 static int
    838 lookup_parsepath(struct namei_state *state, struct vnode *searchdir)
    839 {
    840 	const char *cp;			/* pointer into pathname argument */
    841 	int error;
    842 	struct componentname *cnp = state->cnp;
    843 	struct nameidata *ndp = state->ndp;
    844 
    845 	KASSERT(cnp == &ndp->ni_cnd);
    846 
    847 	/*
    848 	 * Search a new directory.
    849 	 *
    850 	 * The last component of the filename is left accessible via
    851 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    852 	 * the name set the SAVENAME flag. When done, they assume
    853 	 * responsibility for freeing the pathname buffer.
    854 	 *
    855 	 * At this point, our only vnode state is that the search dir
    856 	 * is held.
    857 	 */
    858 	error = VOP_PARSEPATH(searchdir, cnp->cn_nameptr, &cnp->cn_namelen);
    859 	if (error) {
    860 		return error;
    861 	}
    862 	cp = cnp->cn_nameptr + cnp->cn_namelen;
    863 	if (cnp->cn_namelen > KERNEL_NAME_MAX) {
    864 		return ENAMETOOLONG;
    865 	}
    866 #ifdef NAMEI_DIAGNOSTIC
    867 	{ char c = *cp;
    868 		*(char *)cp = '\0';
    869 		printf("{%s}: ", cnp->cn_nameptr);
    870 		*(char *)cp = c; }
    871 #endif /* NAMEI_DIAGNOSTIC */
    872 	ndp->ni_pathlen -= cnp->cn_namelen;
    873 	ndp->ni_next = cp;
    874 	/*
    875 	 * If this component is followed by a slash, then move the pointer to
    876 	 * the next component forward, and remember that this component must be
    877 	 * a directory.
    878 	 */
    879 	if (*cp == '/') {
    880 		do {
    881 			cp++;
    882 		} while (*cp == '/');
    883 		state->slashes = cp - ndp->ni_next;
    884 		ndp->ni_pathlen -= state->slashes;
    885 		ndp->ni_next = cp;
    886 		cnp->cn_flags |= REQUIREDIR;
    887 	} else {
    888 		state->slashes = 0;
    889 		cnp->cn_flags &= ~REQUIREDIR;
    890 	}
    891 	/*
    892 	 * We do special processing on the last component, whether or not it's
    893 	 * a directory.  Cache all intervening lookups, but not the final one.
    894 	 */
    895 	if (*cp == '\0') {
    896 		if (state->docache)
    897 			cnp->cn_flags |= MAKEENTRY;
    898 		else
    899 			cnp->cn_flags &= ~MAKEENTRY;
    900 		cnp->cn_flags |= ISLASTCN;
    901 	} else {
    902 		cnp->cn_flags |= MAKEENTRY;
    903 		cnp->cn_flags &= ~ISLASTCN;
    904 	}
    905 	if (cnp->cn_namelen == 2 &&
    906 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
    907 		cnp->cn_flags |= ISDOTDOT;
    908 	else
    909 		cnp->cn_flags &= ~ISDOTDOT;
    910 
    911 	return 0;
    912 }
    913 
    914 /*
    915  * Take care of crossing a mounted-on vnode.  On error, foundobj_ret will be
    916  * vrele'd, but searchdir is left alone.
    917  */
    918 static int
    919 lookup_crossmount(struct namei_state *state,
    920     struct vnode **searchdir_ret,
    921     struct vnode **foundobj_ret,
    922     bool *searchdir_locked)
    923 {
    924 	struct componentname *cnp = state->cnp;
    925 	struct vnode *foundobj, *vp;
    926 	struct vnode *searchdir;
    927 	struct mount *mp;
    928 	int error, lktype;
    929 
    930 	searchdir = *searchdir_ret;
    931 	foundobj = *foundobj_ret;
    932 	error = 0;
    933 
    934 	KASSERT((cnp->cn_flags & NOCROSSMOUNT) == 0);
    935 
    936 	/* First, unlock searchdir (oof). */
    937 	if (*searchdir_locked) {
    938 		KASSERT(searchdir != NULL);
    939 		lktype = VOP_ISLOCKED(searchdir);
    940 		VOP_UNLOCK(searchdir);
    941 		*searchdir_locked = false;
    942 	} else {
    943 		lktype = LK_NONE;
    944 	}
    945 
    946 	/*
    947 	 * Do an unlocked check to see if the vnode has been mounted on; if
    948 	 * so find the root of the mounted file system.
    949 	 */
    950 	while (foundobj->v_type == VDIR &&
    951 	    (mp = foundobj->v_mountedhere) != NULL &&
    952 	    (cnp->cn_flags & NOCROSSMOUNT) == 0) {
    953 		/*
    954 		 * Try the namecache first.  If that doesn't work, do
    955 		 * it the hard way.
    956 		 */
    957 		if (cache_lookup_mount(foundobj, &vp)) {
    958 			vrele(foundobj);
    959 			foundobj = vp;
    960 		} else {
    961 			/* First get the vnodes mount stable. */
    962 			while ((mp = foundobj->v_mountedhere) != NULL) {
    963 				fstrans_start(mp);
    964 				if (fstrans_held(mp) &&
    965 				    mp == foundobj->v_mountedhere) {
    966 					break;
    967 				}
    968 				fstrans_done(mp);
    969 			}
    970 			if (mp == NULL) {
    971 				break;
    972 			}
    973 
    974 			/*
    975 			 * Now get a reference on the root vnode.
    976 			 * XXX Future - maybe allow only VDIR here.
    977 			 */
    978 			error = VFS_ROOT(mp, LK_NONE, &vp);
    979 
    980 			/*
    981 			 * If successful, enter it into the cache while
    982 			 * holding the mount busy (competing with unmount).
    983 			 */
    984 			if (error == 0) {
    985 				cache_enter_mount(foundobj, vp);
    986 			}
    987 
    988 			/*
    989 			 * Finally, drop references to foundobj & mountpoint.
    990 			 */
    991 			vrele(foundobj);
    992 			fstrans_done(mp);
    993 			if (error) {
    994 				foundobj = NULL;
    995 				break;
    996 			}
    997 			foundobj = vp;
    998 		}
    999 
   1000 		/*
   1001 		 * Avoid locking vnodes from two filesystems because
   1002 		 * it's prone to deadlock, e.g. when using puffs.
   1003 		 * Also, it isn't a good idea to propagate slowness of
   1004 		 * a filesystem up to the root directory. For now,
   1005 		 * only handle the common case, where foundobj is
   1006 		 * VDIR.
   1007 		 *
   1008 		 * In this case set searchdir to null to avoid using
   1009 		 * it again. It is not correct to set searchdir ==
   1010 		 * foundobj here as that will confuse the caller.
   1011 		 * (See PR 40740.)
   1012 		 */
   1013 		if (searchdir == NULL) {
   1014 			/* already been here once; do nothing further */
   1015 		} else if (foundobj->v_type == VDIR) {
   1016 			vrele(searchdir);
   1017 			*searchdir_ret = searchdir = NULL;
   1018 			lktype = LK_NONE;
   1019 		}
   1020 	}
   1021 
   1022 	/* If searchdir is still around, re-lock it. */
   1023  	if (error == 0 && lktype != LK_NONE) {
   1024 		vn_lock(searchdir, lktype | LK_RETRY);
   1025 		*searchdir_locked = true;
   1026 	}
   1027 	*foundobj_ret = foundobj;
   1028 	return error;
   1029 }
   1030 
   1031 /*
   1032  * Determine the desired locking mode for the directory of a lookup.
   1033  */
   1034 static int
   1035 lookup_lktype(struct vnode *searchdir, struct componentname *cnp)
   1036 {
   1037 
   1038 	/*
   1039 	 * If the file system supports VOP_LOOKUP() with a shared lock, and
   1040 	 * we are not making any modifications (nameiop LOOKUP) or this is
   1041 	 * not the last component then get a shared lock.  Where we can't do
   1042 	 * fast-forwarded lookups (for example with layered file systems)
   1043 	 * then this is the fallback for reducing lock contention.
   1044 	 */
   1045 	if ((searchdir->v_mount->mnt_iflag & IMNT_SHRLOOKUP) != 0 &&
   1046 	    (cnp->cn_nameiop == LOOKUP || (cnp->cn_flags & ISLASTCN) == 0)) {
   1047 		return LK_SHARED;
   1048 	} else {
   1049 		return LK_EXCLUSIVE;
   1050 	}
   1051 }
   1052 
   1053 /*
   1054  * Call VOP_LOOKUP for a single lookup; return a new search directory
   1055  * (used when crossing mountpoints up or searching union mounts down) and
   1056  * the found object, which for create operations may be NULL on success.
   1057  *
   1058  * Note that the new search directory may be null, which means the
   1059  * searchdir was unlocked and released. This happens in the common case
   1060  * when crossing a mount point downwards, in order to avoid coupling
   1061  * locks between different file system volumes. Importantly, this can
   1062  * happen even if the call fails. (XXX: this is gross and should be
   1063  * tidied somehow.)
   1064  */
   1065 static int
   1066 lookup_once(struct namei_state *state,
   1067     struct vnode *searchdir,
   1068     struct vnode **newsearchdir_ret,
   1069     struct vnode **foundobj_ret,
   1070     bool *newsearchdir_locked_ret)
   1071 {
   1072 	struct vnode *tmpvn;		/* scratch vnode */
   1073 	struct vnode *foundobj;		/* result */
   1074 	struct lwp *l = curlwp;
   1075 	bool searchdir_locked = false;
   1076 	int error, lktype;
   1077 
   1078 	struct componentname *cnp = state->cnp;
   1079 	struct nameidata *ndp = state->ndp;
   1080 
   1081 	KASSERT(cnp == &ndp->ni_cnd);
   1082 	*newsearchdir_ret = searchdir;
   1083 
   1084 	/*
   1085 	 * Handle "..": two special cases.
   1086 	 * 1. If at root directory (e.g. after chroot)
   1087 	 *    or at absolute root directory
   1088 	 *    then ignore it so can't get out.
   1089 	 * 1a. If at the root of the emulation filesystem go to the real
   1090 	 *    root. So "/../<path>" is always absolute.
   1091 	 * 1b. If we have somehow gotten out of a jail, warn
   1092 	 *    and also ignore it so we can't get farther out.
   1093 	 * 2. If this vnode is the root of a mounted
   1094 	 *    filesystem, then replace it with the
   1095 	 *    vnode which was mounted on so we take the
   1096 	 *    .. in the other file system.
   1097 	 */
   1098 	if (cnp->cn_flags & ISDOTDOT) {
   1099 		struct proc *p = l->l_proc;
   1100 
   1101 		for (;;) {
   1102 			if (searchdir == ndp->ni_rootdir ||
   1103 			    searchdir == rootvnode) {
   1104 				foundobj = searchdir;
   1105 				vref(foundobj);
   1106 				*foundobj_ret = foundobj;
   1107 				if (cnp->cn_flags & LOCKPARENT) {
   1108 					lktype = lookup_lktype(searchdir, cnp);
   1109 					vn_lock(searchdir, lktype | LK_RETRY);
   1110 					searchdir_locked = true;
   1111 				}
   1112 				error = 0;
   1113 				goto done;
   1114 			}
   1115 			if (ndp->ni_rootdir != rootvnode) {
   1116 				int retval;
   1117 
   1118 				retval = vn_isunder(searchdir, ndp->ni_rootdir,
   1119 				    l);
   1120 				if (!retval) {
   1121 					/* Oops! We got out of jail! */
   1122 					log(LOG_WARNING,
   1123 					    "chrooted pid %d uid %d (%s) "
   1124 					    "detected outside of its chroot\n",
   1125 					    p->p_pid,
   1126 					    kauth_cred_geteuid(l->l_cred),
   1127 					    p->p_comm);
   1128 					/* Put us at the jail root. */
   1129 					vrele(searchdir);
   1130 					searchdir = NULL;
   1131 					foundobj = ndp->ni_rootdir;
   1132 					vref(foundobj);
   1133 					vref(foundobj);
   1134 					*newsearchdir_ret = foundobj;
   1135 					*foundobj_ret = foundobj;
   1136 					error = 0;
   1137 					goto done;
   1138 				}
   1139 			}
   1140 			if ((searchdir->v_vflag & VV_ROOT) == 0 ||
   1141 			    (cnp->cn_flags & NOCROSSMOUNT))
   1142 				break;
   1143 			tmpvn = searchdir;
   1144 			searchdir = searchdir->v_mount->mnt_vnodecovered;
   1145 			vref(searchdir);
   1146 			vrele(tmpvn);
   1147 			*newsearchdir_ret = searchdir;
   1148 		}
   1149 	}
   1150 
   1151 	lktype = lookup_lktype(searchdir, cnp);
   1152 
   1153 	/*
   1154 	 * We now have a segment name to search for, and a directory to search.
   1155 	 * Our vnode state here is that "searchdir" is held.
   1156 	 */
   1157 unionlookup:
   1158 	foundobj = NULL;
   1159 	if (!searchdir_locked) {
   1160 		vn_lock(searchdir, lktype | LK_RETRY);
   1161 		searchdir_locked = true;
   1162 	}
   1163 	error = VOP_LOOKUP(searchdir, &foundobj, cnp);
   1164 
   1165 	if (error != 0) {
   1166 		KASSERTMSG((foundobj == NULL),
   1167 		    "leaf `%s' should be empty but is %p",
   1168 		    cnp->cn_nameptr, foundobj);
   1169 #ifdef NAMEI_DIAGNOSTIC
   1170 		printf("not found\n");
   1171 #endif /* NAMEI_DIAGNOSTIC */
   1172 
   1173 		/*
   1174 		 * If ENOLCK, the file system needs us to retry the lookup
   1175 		 * with an exclusive lock.  It's likely nothing was found in
   1176 		 * cache and/or modifications need to be made.
   1177 		 */
   1178 		if (error == ENOLCK) {
   1179 			KASSERT(VOP_ISLOCKED(searchdir) == LK_SHARED);
   1180 			KASSERT(searchdir_locked);
   1181 			if (vn_lock(searchdir, LK_UPGRADE | LK_NOWAIT)) {
   1182 				VOP_UNLOCK(searchdir);
   1183 				searchdir_locked = false;
   1184 			}
   1185 			lktype = LK_EXCLUSIVE;
   1186 			goto unionlookup;
   1187 		}
   1188 
   1189 		if ((error == ENOENT) &&
   1190 		    (searchdir->v_vflag & VV_ROOT) &&
   1191 		    (searchdir->v_mount->mnt_flag & MNT_UNION)) {
   1192 			tmpvn = searchdir;
   1193 			searchdir = searchdir->v_mount->mnt_vnodecovered;
   1194 			vref(searchdir);
   1195 			vput(tmpvn);
   1196 			searchdir_locked = false;
   1197 			*newsearchdir_ret = searchdir;
   1198 			goto unionlookup;
   1199 		}
   1200 
   1201 		if (error != EJUSTRETURN)
   1202 			goto done;
   1203 
   1204 		/*
   1205 		 * If this was not the last component, or there were trailing
   1206 		 * slashes, and we are not going to create a directory,
   1207 		 * then the name must exist.
   1208 		 */
   1209 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
   1210 			error = ENOENT;
   1211 			goto done;
   1212 		}
   1213 
   1214 		/*
   1215 		 * If creating and at end of pathname, then can consider
   1216 		 * allowing file to be created.
   1217 		 */
   1218 		if (state->rdonly) {
   1219 			error = EROFS;
   1220 			goto done;
   1221 		}
   1222 
   1223 		/*
   1224 		 * We return success and a NULL foundobj to indicate
   1225 		 * that the entry doesn't currently exist, leaving a
   1226 		 * pointer to the (normally, locked) directory vnode
   1227 		 * as searchdir.
   1228 		 */
   1229 		*foundobj_ret = NULL;
   1230 		error = 0;
   1231 		goto done;
   1232 	}
   1233 #ifdef NAMEI_DIAGNOSTIC
   1234 	printf("found\n");
   1235 #endif /* NAMEI_DIAGNOSTIC */
   1236 
   1237 	/* Unlock, unless the caller needs the parent locked. */
   1238 	if (searchdir != NULL) {
   1239 		KASSERT(searchdir_locked);
   1240 		if ((cnp->cn_flags & (ISLASTCN | LOCKPARENT)) !=
   1241 		    (ISLASTCN | LOCKPARENT)) {
   1242 		    	VOP_UNLOCK(searchdir);
   1243 		    	searchdir_locked = false;
   1244 		}
   1245 	} else {
   1246 		KASSERT(!searchdir_locked);
   1247 	}
   1248 
   1249 	*foundobj_ret = foundobj;
   1250 	error = 0;
   1251 done:
   1252 	*newsearchdir_locked_ret = searchdir_locked;
   1253 	return error;
   1254 }
   1255 
   1256 /*
   1257  * Parse out the first path name component that we need to to consider.
   1258  *
   1259  * While doing this, attempt to use the name cache to fast-forward through
   1260  * as many "easy" to find components of the path as possible.
   1261  *
   1262  * We use the namecache's node locks to form a chain, and avoid as many
   1263  * vnode references and locks as possible.  In the ideal case, only the
   1264  * final vnode will have its reference count adjusted and lock taken.
   1265  */
   1266 static int
   1267 lookup_fastforward(struct namei_state *state, struct vnode **searchdir_ret,
   1268     struct vnode **foundobj_ret)
   1269 {
   1270 	struct componentname *cnp = state->cnp;
   1271 	struct nameidata *ndp = state->ndp;
   1272 	krwlock_t *plock;
   1273 	struct vnode *foundobj, *searchdir;
   1274 	int error, error2;
   1275 	size_t oldpathlen;
   1276 	const char *oldnameptr;
   1277 	bool terminal;
   1278 
   1279 	/*
   1280 	 * Eat as many path name components as possible before giving up and
   1281 	 * letting lookup_once() handle it.  Remember the starting point in
   1282 	 * case we can't get vnode references and need to roll back.
   1283 	 */
   1284 	plock = NULL;
   1285 	searchdir = *searchdir_ret;
   1286 	oldnameptr = cnp->cn_nameptr;
   1287 	oldpathlen = ndp->ni_pathlen;
   1288 	terminal = false;
   1289 	for (;;) {
   1290 		foundobj = NULL;
   1291 
   1292 		/*
   1293 		 * Get the next component name.  There should be no slashes
   1294 		 * here, and we shouldn't have looped around if we were
   1295 		 * done.
   1296 		 */
   1297 		KASSERT(cnp->cn_nameptr[0] != '/');
   1298 		KASSERT(cnp->cn_nameptr[0] != '\0');
   1299 		if ((error = lookup_parsepath(state, searchdir)) != 0) {
   1300 			break;
   1301 		}
   1302 
   1303 		/*
   1304 		 * Can't deal with DOTDOT lookups if NOCROSSMOUNT or the
   1305 		 * lookup is chrooted.
   1306 		 */
   1307 		if ((cnp->cn_flags & ISDOTDOT) != 0) {
   1308 			if ((searchdir->v_vflag & VV_ROOT) != 0 &&
   1309 			    (cnp->cn_flags & NOCROSSMOUNT)) {
   1310 			    	error = EOPNOTSUPP;
   1311 				break;
   1312 			}
   1313 			if (ndp->ni_rootdir != rootvnode) {
   1314 			    	error = EOPNOTSUPP;
   1315 				break;
   1316 			}
   1317 		}
   1318 
   1319 		/*
   1320 		 * Can't deal with last component when modifying; this needs
   1321 		 * searchdir locked and VOP_LOOKUP() called (which can and
   1322 		 * does modify state, despite the name).  NB: this case means
   1323 		 * terminal is never set true when LOCKPARENT.
   1324 		 */
   1325 		if ((cnp->cn_flags & ISLASTCN) != 0) {
   1326 			if (cnp->cn_nameiop != LOOKUP ||
   1327 			    (cnp->cn_flags & LOCKPARENT) != 0) {
   1328 				error = EOPNOTSUPP;
   1329 				break;
   1330 			}
   1331 		}
   1332 
   1333 		/*
   1334 		 * Good, now look for it in cache.  cache_lookup_linked()
   1335 		 * will fail if there's nothing there, or if there's no
   1336 		 * ownership info for the directory, or if the user doesn't
   1337 		 * have permission to look up files in this directory.
   1338 		 */
   1339 		if (!cache_lookup_linked(searchdir, cnp->cn_nameptr,
   1340 			cnp->cn_namelen, &foundobj, &plock, cnp->cn_cred)) {
   1341 			error = EOPNOTSUPP;
   1342 			break;
   1343 		}
   1344 		KASSERT(plock != NULL);
   1345 		KASSERT(rw_lock_held(plock));
   1346 
   1347 		/*
   1348 		 * Scored a hit.  Negative is good too (ENOENT).  If there's
   1349 		 * a '-o union' mount here, punt and let lookup_once() deal
   1350 		 * with it.
   1351 		 */
   1352 		if (foundobj == NULL) {
   1353 			if ((searchdir->v_vflag & VV_ROOT) != 0 &&
   1354 			    (searchdir->v_mount->mnt_flag & MNT_UNION) != 0) {
   1355 			    	error = EOPNOTSUPP;
   1356 			} else {
   1357 				error = ENOENT;
   1358 				terminal = ((cnp->cn_flags & ISLASTCN) != 0);
   1359 			}
   1360 			break;
   1361 		}
   1362 
   1363 		/*
   1364 		 * Stop and get a hold on the vnode if we've encountered
   1365 		 * something other than a dirctory.
   1366 		 */
   1367 		if (foundobj->v_type != VDIR) {
   1368 			error = vcache_tryvget(foundobj);
   1369 			if (error != 0) {
   1370 				foundobj = NULL;
   1371 				error = EOPNOTSUPP;
   1372 			} else {
   1373 				terminal = (foundobj->v_type != VLNK &&
   1374 				    (cnp->cn_flags & ISLASTCN) != 0);
   1375 			}
   1376 			break;
   1377 		}
   1378 
   1379 		/*
   1380 		 * Try to cross mountpoints, bearing in mind that they can
   1381 		 * be stacked.  If at any point we can't go further, stop
   1382 		 * and try to get a reference on the vnode.  If we are able
   1383 		 * to get a ref then lookup_crossmount() will take care of
   1384 		 * it, otherwise we'll fall through to lookup_once().
   1385 		 */
   1386 		if (foundobj->v_mountedhere != NULL) {
   1387 			while (foundobj->v_mountedhere != NULL &&
   1388 			    (cnp->cn_flags & NOCROSSMOUNT) == 0 &&
   1389 			    cache_cross_mount(&foundobj, &plock)) {
   1390 				KASSERT(foundobj != NULL);
   1391 				KASSERT(foundobj->v_type == VDIR);
   1392 			}
   1393 			if (foundobj->v_mountedhere != NULL) {
   1394 				error = vcache_tryvget(foundobj);
   1395 				if (error != 0) {
   1396 					foundobj = NULL;
   1397 					error = EOPNOTSUPP;
   1398 				}
   1399 				break;
   1400 			} else {
   1401 				searchdir = NULL;
   1402 			}
   1403 		}
   1404 
   1405 		/*
   1406 		 * Time to stop if we found the last component & traversed
   1407 		 * all mounts.
   1408 		 */
   1409 		if ((cnp->cn_flags & ISLASTCN) != 0) {
   1410 			error = vcache_tryvget(foundobj);
   1411 			if (error != 0) {
   1412 				foundobj = NULL;
   1413 				error = EOPNOTSUPP;
   1414 			} else {
   1415 				terminal = (foundobj->v_type != VLNK);
   1416 			}
   1417 			break;
   1418 		}
   1419 
   1420 		/*
   1421 		 * Otherwise, we're still in business.  Set the found VDIR
   1422 		 * vnode as the search dir for the next component and
   1423 		 * continue on to it.
   1424 		 */
   1425 		cnp->cn_nameptr = ndp->ni_next;
   1426 		searchdir = foundobj;
   1427 	}
   1428 
   1429 	if (terminal) {
   1430 		/*
   1431 		 * If we exited the loop above having successfully located
   1432 		 * the last component with a zero error code, and it's not a
   1433 		 * symbolic link, then the parent directory is not needed.
   1434 		 * Release reference to the starting parent and make the
   1435 		 * terminal parent disappear into thin air.
   1436 		 */
   1437 		KASSERT(plock != NULL);
   1438 		rw_exit(plock);
   1439 		vrele(*searchdir_ret);
   1440 		*searchdir_ret = NULL;
   1441 	} else if (searchdir != *searchdir_ret) {
   1442 		/*
   1443 		 * Otherwise we need to return the parent.  If we ended up
   1444 		 * with a new search dir, ref it before dropping the
   1445 		 * namecache's lock.  The lock prevents both searchdir and
   1446 		 * foundobj from disappearing.  If we can't ref the new
   1447 		 * searchdir, we have a bit of a problem.  Roll back the
   1448 		 * fastforward to the beginning and let lookup_once() take
   1449 		 * care of it.
   1450 		 */
   1451 		if (searchdir == NULL) {
   1452 			/*
   1453 			 * It's possible for searchdir to be NULL in the
   1454 			 * case of a root vnode being reclaimed while
   1455 			 * trying to cross a mount.
   1456 			 */
   1457 			error2 = EOPNOTSUPP;
   1458 		} else {
   1459 			error2 = vcache_tryvget(searchdir);
   1460 		}
   1461 		KASSERT(plock != NULL);
   1462 		rw_exit(plock);
   1463 		if (__predict_true(error2 == 0)) {
   1464 			/* Returning new searchdir, and maybe new foundobj. */
   1465 			vrele(*searchdir_ret);
   1466 			*searchdir_ret = searchdir;
   1467 		} else {
   1468 			/* Returning nothing. */
   1469 			if (foundobj != NULL) {
   1470 				vrele(foundobj);
   1471 				foundobj = NULL;
   1472 			}
   1473 			cnp->cn_nameptr = oldnameptr;
   1474 			ndp->ni_pathlen = oldpathlen;
   1475 			error = lookup_parsepath(state, *searchdir_ret);
   1476 			if (error == 0) {
   1477 				error = EOPNOTSUPP;
   1478 			}
   1479 		}
   1480 	} else if (plock != NULL) {
   1481 		/* Drop any namecache lock still held. */
   1482 		rw_exit(plock);
   1483 	}
   1484 
   1485 	KASSERT(error == 0 ? foundobj != NULL : foundobj == NULL);
   1486 	*foundobj_ret = foundobj;
   1487 	return error;
   1488 }
   1489 
   1490 //////////////////////////////
   1491 
   1492 /*
   1493  * Do a complete path search from a single root directory.
   1494  * (This is called up to twice if TRYEMULROOT is in effect.)
   1495  */
   1496 static int
   1497 namei_oneroot(struct namei_state *state,
   1498     int neverfollow, int inhibitmagic, int isnfsd)
   1499 {
   1500 	struct nameidata *ndp = state->ndp;
   1501 	struct componentname *cnp = state->cnp;
   1502 	struct vnode *searchdir, *foundobj;
   1503 	bool searchdir_locked = false;
   1504 	int error;
   1505 
   1506 	error = namei_start(state, isnfsd, &searchdir);
   1507 	if (error) {
   1508 		ndp->ni_dvp = NULL;
   1509 		ndp->ni_vp = NULL;
   1510 		return error;
   1511 	}
   1512 	KASSERT(searchdir->v_type == VDIR);
   1513 
   1514 	/*
   1515 	 * Setup: break out flag bits into variables.
   1516 	 */
   1517 	state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
   1518 	if (cnp->cn_nameiop == DELETE)
   1519 		state->docache = 0;
   1520 	state->rdonly = cnp->cn_flags & RDONLY;
   1521 
   1522 	/*
   1523 	 * Keep going until we run out of path components.
   1524 	 */
   1525 	cnp->cn_nameptr = ndp->ni_pnbuf;
   1526 
   1527 	/* drop leading slashes (already used them to choose startdir) */
   1528 	while (cnp->cn_nameptr[0] == '/') {
   1529 		cnp->cn_nameptr++;
   1530 		ndp->ni_pathlen--;
   1531 	}
   1532 	/* was it just "/"? */
   1533 	if (cnp->cn_nameptr[0] == '\0') {
   1534 		foundobj = searchdir;
   1535 		searchdir = NULL;
   1536 		cnp->cn_flags |= ISLASTCN;
   1537 
   1538 		/* bleh */
   1539 		goto skiploop;
   1540 	}
   1541 
   1542 	for (;;) {
   1543 		KASSERT(searchdir != NULL);
   1544 		KASSERT(!searchdir_locked);
   1545 
   1546 		/*
   1547 		 * Parse out the first path name component that we need to
   1548 		 * to consider.  While doing this, attempt to use the name
   1549 		 * cache to fast-forward through as many "easy" to find
   1550 		 * components of the path as possible.
   1551 		 */
   1552 		error = lookup_fastforward(state, &searchdir, &foundobj);
   1553 
   1554 		/*
   1555 		 * If we didn't get a good answer from the namecache, then
   1556 		 * go directly to the file system.
   1557 		 */
   1558 		if (error == EOPNOTSUPP) {
   1559 			error = lookup_once(state, searchdir, &searchdir,
   1560 			    &foundobj, &searchdir_locked);
   1561 		}
   1562 
   1563 		/*
   1564 		 * If the vnode we found is mounted on, then cross the mount
   1565 		 * and get the root vnode in foundobj.  If this encounters
   1566 		 * an error, it will dispose of foundobj, but searchdir is
   1567 		 * untouched.
   1568 		 */
   1569 		if (error == 0 && foundobj != NULL &&
   1570 		    foundobj->v_type == VDIR &&
   1571 		    foundobj->v_mountedhere != NULL &&
   1572 		    (cnp->cn_flags & NOCROSSMOUNT) == 0) {
   1573 		    	error = lookup_crossmount(state, &searchdir,
   1574 		    	    &foundobj, &searchdir_locked);
   1575 		}
   1576 
   1577 		if (error) {
   1578 			if (searchdir != NULL) {
   1579 				if (searchdir_locked) {
   1580 					searchdir_locked = false;
   1581 					vput(searchdir);
   1582 				} else {
   1583 					vrele(searchdir);
   1584 				}
   1585 			}
   1586 			ndp->ni_dvp = NULL;
   1587 			ndp->ni_vp = NULL;
   1588 			/*
   1589 			 * Note that if we're doing TRYEMULROOT we can
   1590 			 * retry with the normal root. Where this is
   1591 			 * currently set matches previous practice,
   1592 			 * but the previous practice didn't make much
   1593 			 * sense and somebody should sit down and
   1594 			 * figure out which cases should cause retry
   1595 			 * and which shouldn't. XXX.
   1596 			 */
   1597 			state->attempt_retry = 1;
   1598 			return error;
   1599 		}
   1600 
   1601 		if (foundobj == NULL) {
   1602 			/*
   1603 			 * Success with no object returned means we're
   1604 			 * creating something and it isn't already
   1605 			 * there. Break out of the main loop now so
   1606 			 * the code below doesn't have to test for
   1607 			 * foundobj == NULL.
   1608 			 */
   1609 			/* lookup_once can't have dropped the searchdir */
   1610 			KASSERT(searchdir != NULL ||
   1611 			    (cnp->cn_flags & ISLASTCN) != 0);
   1612 			break;
   1613 		}
   1614 
   1615 		/*
   1616 		 * Check for symbolic link. If we've reached one,
   1617 		 * follow it, unless we aren't supposed to. Back up
   1618 		 * over any slashes that we skipped, as we will need
   1619 		 * them again.
   1620 		 */
   1621 		if (namei_atsymlink(state, foundobj)) {
   1622 			/* Don't need searchdir locked any more. */
   1623 			if (searchdir_locked) {
   1624 				searchdir_locked = false;
   1625 				VOP_UNLOCK(searchdir);
   1626 			}
   1627 			ndp->ni_pathlen += state->slashes;
   1628 			ndp->ni_next -= state->slashes;
   1629 			if (neverfollow) {
   1630 				error = EINVAL;
   1631 			} else if (searchdir == NULL) {
   1632 				/*
   1633 				 * dholland 20160410: lookup_once only
   1634 				 * drops searchdir if it crossed a
   1635 				 * mount point. Therefore, if we get
   1636 				 * here it means we crossed a mount
   1637 				 * point to a mounted filesystem whose
   1638 				 * root vnode is a symlink. In theory
   1639 				 * we could continue at this point by
   1640 				 * using the pre-crossing searchdir
   1641 				 * (e.g. just take out an extra
   1642 				 * reference on it before calling
   1643 				 * lookup_once so we still have it),
   1644 				 * but this will make an ugly mess and
   1645 				 * it should never happen in practice
   1646 				 * as only badly broken filesystems
   1647 				 * have non-directory root vnodes. (I
   1648 				 * have seen this sort of thing with
   1649 				 * NFS occasionally but even then it
   1650 				 * means something's badly wrong.)
   1651 				 */
   1652 				error = ENOTDIR;
   1653 			} else {
   1654 				/*
   1655 				 * dholland 20110410: if we're at a
   1656 				 * union mount it might make sense to
   1657 				 * use the top of the union stack here
   1658 				 * rather than the layer we found the
   1659 				 * symlink in. (FUTURE)
   1660 				 */
   1661 				error = namei_follow(state, inhibitmagic,
   1662 				    searchdir, foundobj,
   1663 				    &searchdir);
   1664 			}
   1665 			if (error) {
   1666 				KASSERT(searchdir != foundobj);
   1667 				if (searchdir != NULL) {
   1668 					vrele(searchdir);
   1669 				}
   1670 				vrele(foundobj);
   1671 				ndp->ni_dvp = NULL;
   1672 				ndp->ni_vp = NULL;
   1673 				return error;
   1674 			}
   1675 			vrele(foundobj);
   1676 			foundobj = NULL;
   1677 
   1678 			/*
   1679 			 * If we followed a symlink to `/' and there
   1680 			 * are no more components after the symlink,
   1681 			 * we're done with the loop and what we found
   1682 			 * is the searchdir.
   1683 			 */
   1684 			if (cnp->cn_nameptr[0] == '\0') {
   1685 				KASSERT(searchdir != NULL);
   1686 				foundobj = searchdir;
   1687 				searchdir = NULL;
   1688 				cnp->cn_flags |= ISLASTCN;
   1689 				break;
   1690 			}
   1691 
   1692 			continue;
   1693 		}
   1694 
   1695 		/*
   1696 		 * Not a symbolic link.
   1697 		 *
   1698 		 * Check for directory, if the component was
   1699 		 * followed by a series of slashes.
   1700 		 */
   1701 		if ((foundobj->v_type != VDIR) &&
   1702 		    (cnp->cn_flags & REQUIREDIR)) {
   1703 			KASSERT(foundobj != searchdir);
   1704 			if (searchdir) {
   1705 				if (searchdir_locked) {
   1706 					searchdir_locked = false;
   1707 					vput(searchdir);
   1708 				} else {
   1709 					vrele(searchdir);
   1710 				}
   1711 			} else {
   1712 				KASSERT(!searchdir_locked);
   1713 			}
   1714 			vrele(foundobj);
   1715 			ndp->ni_dvp = NULL;
   1716 			ndp->ni_vp = NULL;
   1717 			state->attempt_retry = 1;
   1718 			return ENOTDIR;
   1719 		}
   1720 
   1721 		/*
   1722 		 * Stop if we've reached the last component.
   1723 		 */
   1724 		if (cnp->cn_flags & ISLASTCN) {
   1725 			break;
   1726 		}
   1727 
   1728 		/*
   1729 		 * Continue with the next component.
   1730 		 */
   1731 		cnp->cn_nameptr = ndp->ni_next;
   1732 		if (searchdir != NULL) {
   1733 			if (searchdir_locked) {
   1734 				searchdir_locked = false;
   1735 				vput(searchdir);
   1736 			} else {
   1737 				vrele(searchdir);
   1738 			}
   1739 		}
   1740 		searchdir = foundobj;
   1741 		foundobj = NULL;
   1742 	}
   1743 
   1744 	KASSERT((cnp->cn_flags & LOCKPARENT) == 0 || searchdir == NULL ||
   1745 	    VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
   1746 
   1747 skiploop:
   1748 	if (foundobj != NULL) {
   1749 		if (foundobj == ndp->ni_erootdir) {
   1750 			/*
   1751 			 * We are about to return the emulation root.
   1752 			 * This isn't a good idea because code might
   1753 			 * repeatedly lookup ".." until the file
   1754 			 * matches that returned for "/" and loop
   1755 			 * forever.  So convert it to the real root.
   1756 			 */
   1757 			if (searchdir != NULL) {
   1758 				if (searchdir_locked) {
   1759 					vput(searchdir);
   1760 					searchdir_locked = false;
   1761 				} else {
   1762 					vrele(searchdir);
   1763 				}
   1764 				searchdir = NULL;
   1765 			}
   1766 			vrele(foundobj);
   1767 			foundobj = ndp->ni_rootdir;
   1768 			vref(foundobj);
   1769 		}
   1770 
   1771 		/*
   1772 		 * If the caller requested the parent node (i.e. it's
   1773 		 * a CREATE, DELETE, or RENAME), and we don't have one
   1774 		 * (because this is the root directory, or we crossed
   1775 		 * a mount point), then we must fail.
   1776 		 *
   1777 		 * 20210604 dholland when NONEXCLHACK is set (open
   1778 		 * with O_CREAT but not O_EXCL) skip this logic. Since
   1779 		 * we have a foundobj, open will not be creating, so
   1780 		 * it doesn't actually need or use the searchdir, so
   1781 		 * it's ok to return it even if it's on a different
   1782 		 * volume, and it's also ok to return NULL; by setting
   1783 		 * NONEXCLHACK the open code promises to cope with
   1784 		 * those cases correctly. (That is, it should do what
   1785 		 * it would do anyway, that is, just release the
   1786 		 * searchdir, except not crash if it's null.) This is
   1787 		 * needed because otherwise opening mountpoints with
   1788 		 * O_CREAT but not O_EXCL fails... which is a silly
   1789 		 * thing to do but ought to work. (This whole issue
   1790 		 * came to light because 3rd party code wanted to open
   1791 		 * certain procfs nodes with O_CREAT for some 3rd
   1792 		 * party reason, and it failed.)
   1793 		 *
   1794 		 * Note that NONEXCLHACK is properly a different
   1795 		 * nameiop (it is partway between LOOKUP and CREATE)
   1796 		 * but it was stuffed in as a flag instead to make the
   1797 		 * resulting patch less invasive for pullup. Blah.
   1798 		 */
   1799 		if (cnp->cn_nameiop != LOOKUP &&
   1800 		    (searchdir == NULL ||
   1801 			searchdir->v_mount != foundobj->v_mount) &&
   1802 		    (cnp->cn_flags & NONEXCLHACK) == 0) {
   1803 			if (searchdir) {
   1804 				if (searchdir_locked) {
   1805 					vput(searchdir);
   1806 					searchdir_locked = false;
   1807 				} else {
   1808 					vrele(searchdir);
   1809 				}
   1810 				searchdir = NULL;
   1811 			}
   1812 			vrele(foundobj);
   1813 			foundobj = NULL;
   1814 			ndp->ni_dvp = NULL;
   1815 			ndp->ni_vp = NULL;
   1816 			state->attempt_retry = 1;
   1817 
   1818 			switch (cnp->cn_nameiop) {
   1819 			case CREATE:
   1820 				return EEXIST;
   1821 			case DELETE:
   1822 			case RENAME:
   1823 				return EBUSY;
   1824 			default:
   1825 				break;
   1826 			}
   1827 			panic("Invalid nameiop\n");
   1828 		}
   1829 
   1830 		/*
   1831 		 * Disallow directory write attempts on read-only lookups.
   1832 		 * Prefers EEXIST over EROFS for the CREATE case.
   1833 		 */
   1834 		if (state->rdonly &&
   1835 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
   1836 			if (searchdir) {
   1837 				if (searchdir_locked) {
   1838 					vput(searchdir);
   1839 					searchdir_locked = false;
   1840 				} else {
   1841 					vrele(searchdir);
   1842 				}
   1843 				searchdir = NULL;
   1844 			}
   1845 			vrele(foundobj);
   1846 			foundobj = NULL;
   1847 			ndp->ni_dvp = NULL;
   1848 			ndp->ni_vp = NULL;
   1849 			state->attempt_retry = 1;
   1850 			return EROFS;
   1851 		}
   1852 
   1853 		/* Lock the leaf node if requested. */
   1854 		if ((cnp->cn_flags & (LOCKLEAF | LOCKPARENT)) == LOCKPARENT &&
   1855 		    searchdir == foundobj) {
   1856 			/*
   1857 			 * Note: if LOCKPARENT but not LOCKLEAF is
   1858 			 * set, and searchdir == foundobj, this code
   1859 			 * necessarily unlocks the parent as well as
   1860 			 * the leaf. That is, just because you specify
   1861 			 * LOCKPARENT doesn't mean you necessarily get
   1862 			 * a locked parent vnode. The code in
   1863 			 * vfs_syscalls.c, and possibly elsewhere,
   1864 			 * that uses this combination "knows" this, so
   1865 			 * it can't be safely changed. Feh. XXX
   1866 			 */
   1867 			KASSERT(searchdir_locked);
   1868 		    	VOP_UNLOCK(searchdir);
   1869 		    	searchdir_locked = false;
   1870 		} else if ((cnp->cn_flags & LOCKLEAF) != 0 &&
   1871 		    (searchdir != foundobj ||
   1872 			(cnp->cn_flags & LOCKPARENT) == 0)) {
   1873 			const int lktype = (cnp->cn_flags & LOCKSHARED) != 0 ?
   1874 			    LK_SHARED : LK_EXCLUSIVE;
   1875 			vn_lock(foundobj, lktype | LK_RETRY);
   1876 		}
   1877 	}
   1878 
   1879 	/*
   1880 	 * Done.
   1881 	 */
   1882 
   1883 	/*
   1884 	 * If LOCKPARENT is not set, the parent directory isn't returned.
   1885 	 */
   1886 	if ((cnp->cn_flags & LOCKPARENT) == 0 && searchdir != NULL) {
   1887 		vrele(searchdir);
   1888 		searchdir = NULL;
   1889 	}
   1890 
   1891 	ndp->ni_dvp = searchdir;
   1892 	ndp->ni_vp = foundobj;
   1893 	return 0;
   1894 }
   1895 
   1896 /*
   1897  * Do namei; wrapper layer that handles TRYEMULROOT.
   1898  */
   1899 static int
   1900 namei_tryemulroot(struct namei_state *state,
   1901     int neverfollow, int inhibitmagic, int isnfsd)
   1902 {
   1903 	int error;
   1904 
   1905 	struct nameidata *ndp = state->ndp;
   1906 	struct componentname *cnp = state->cnp;
   1907 	const char *savepath = NULL;
   1908 
   1909 	KASSERT(cnp == &ndp->ni_cnd);
   1910 
   1911 	if (cnp->cn_flags & TRYEMULROOT) {
   1912 		savepath = pathbuf_stringcopy_get(ndp->ni_pathbuf);
   1913 	}
   1914 
   1915 emul_retry:
   1916 	state->attempt_retry = 0;
   1917 
   1918 	error = namei_oneroot(state, neverfollow, inhibitmagic, isnfsd);
   1919 	if (error) {
   1920 		/*
   1921 		 * Once namei has started up, the existence of ni_erootdir
   1922 		 * tells us whether we're working from an emulation root.
   1923 		 * The TRYEMULROOT flag isn't necessarily authoritative.
   1924 		 */
   1925 		if (ndp->ni_erootdir != NULL && state->attempt_retry) {
   1926 			/* Retry the whole thing using the normal root */
   1927 			cnp->cn_flags &= ~TRYEMULROOT;
   1928 			state->attempt_retry = 0;
   1929 
   1930 			/* kinda gross */
   1931 			strcpy(ndp->ni_pathbuf->pb_path, savepath);
   1932 			pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
   1933 			savepath = NULL;
   1934 
   1935 			goto emul_retry;
   1936 		}
   1937 	}
   1938 	if (savepath != NULL) {
   1939 		pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
   1940 	}
   1941 	return error;
   1942 }
   1943 
   1944 /*
   1945  * External interface.
   1946  */
   1947 int
   1948 namei(struct nameidata *ndp)
   1949 {
   1950 	struct namei_state state;
   1951 	int error;
   1952 
   1953 	namei_init(&state, ndp);
   1954 	error = namei_tryemulroot(&state,
   1955 	    0/*!neverfollow*/, 0/*!inhibitmagic*/, 0/*isnfsd*/);
   1956 	namei_cleanup(&state);
   1957 
   1958 	if (error) {
   1959 		/* make sure no stray refs leak out */
   1960 		KASSERT(ndp->ni_dvp == NULL);
   1961 		KASSERT(ndp->ni_vp == NULL);
   1962 	}
   1963 
   1964 	return error;
   1965 }
   1966 
   1967 ////////////////////////////////////////////////////////////
   1968 
   1969 /*
   1970  * External interface used by nfsd. This is basically different from
   1971  * namei only in that it has the ability to pass in the "current
   1972  * directory", and uses an extra flag "neverfollow" for which there's
   1973  * no physical flag defined in namei.h. (There used to be a cut&paste
   1974  * copy of about half of namei in nfsd to allow these minor
   1975  * adjustments to exist.)
   1976  *
   1977  * XXX: the namei interface should be adjusted so nfsd can just use
   1978  * ordinary namei().
   1979  */
   1980 int
   1981 lookup_for_nfsd(struct nameidata *ndp, struct vnode *forcecwd, int neverfollow)
   1982 {
   1983 	struct namei_state state;
   1984 	int error;
   1985 
   1986 	KASSERT(ndp->ni_atdir == NULL);
   1987 	ndp->ni_atdir = forcecwd;
   1988 
   1989 	namei_init(&state, ndp);
   1990 	error = namei_tryemulroot(&state,
   1991 	    neverfollow, 1/*inhibitmagic*/, 1/*isnfsd*/);
   1992 	namei_cleanup(&state);
   1993 
   1994 	if (error) {
   1995 		/* make sure no stray refs leak out */
   1996 		KASSERT(ndp->ni_dvp == NULL);
   1997 		KASSERT(ndp->ni_vp == NULL);
   1998 	}
   1999 
   2000 	return error;
   2001 }
   2002 
   2003 /*
   2004  * A second external interface used by nfsd. This turns out to be a
   2005  * single lookup used by the WebNFS code (ha!) to get "index.html" or
   2006  * equivalent when asked for a directory. It should eventually evolve
   2007  * into some kind of namei_once() call; for the time being it's kind
   2008  * of a mess. XXX.
   2009  *
   2010  * dholland 20110109: I don't think it works, and I don't think it
   2011  * worked before I started hacking and slashing either, and I doubt
   2012  * anyone will ever notice.
   2013  */
   2014 
   2015 /*
   2016  * Internals. This calls lookup_once() after setting up the assorted
   2017  * pieces of state the way they ought to be.
   2018  */
   2019 static int
   2020 do_lookup_for_nfsd_index(struct namei_state *state)
   2021 {
   2022 	int error;
   2023 
   2024 	struct componentname *cnp = state->cnp;
   2025 	struct nameidata *ndp = state->ndp;
   2026 	struct vnode *startdir;
   2027 	struct vnode *foundobj;
   2028 	bool startdir_locked;
   2029 	const char *cp;			/* pointer into pathname argument */
   2030 
   2031 	KASSERT(cnp == &ndp->ni_cnd);
   2032 
   2033 	startdir = state->ndp->ni_atdir;
   2034 
   2035 	cnp->cn_nameptr = ndp->ni_pnbuf;
   2036 	state->docache = 1;
   2037 	state->rdonly = cnp->cn_flags & RDONLY;
   2038 	ndp->ni_dvp = NULL;
   2039 
   2040 	error = VOP_PARSEPATH(startdir, cnp->cn_nameptr, &cnp->cn_namelen);
   2041 	if (error) {
   2042 		return error;
   2043 	}
   2044 
   2045 	cp = cnp->cn_nameptr + cnp->cn_namelen;
   2046 	KASSERT(cnp->cn_namelen <= KERNEL_NAME_MAX);
   2047 	ndp->ni_pathlen -= cnp->cn_namelen;
   2048 	ndp->ni_next = cp;
   2049 	state->slashes = 0;
   2050 	cnp->cn_flags &= ~REQUIREDIR;
   2051 	cnp->cn_flags |= MAKEENTRY|ISLASTCN;
   2052 
   2053 	if (cnp->cn_namelen == 2 &&
   2054 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
   2055 		cnp->cn_flags |= ISDOTDOT;
   2056 	else
   2057 		cnp->cn_flags &= ~ISDOTDOT;
   2058 
   2059 	/*
   2060 	 * Because lookup_once can change the startdir, we need our
   2061 	 * own reference to it to avoid consuming the caller's.
   2062 	 */
   2063 	vref(startdir);
   2064 	error = lookup_once(state, startdir, &startdir, &foundobj,
   2065 	    &startdir_locked);
   2066 
   2067 	KASSERT((cnp->cn_flags & LOCKPARENT) == 0);
   2068 	if (startdir_locked) {
   2069 		VOP_UNLOCK(startdir);
   2070 		startdir_locked = false;
   2071 	}
   2072 
   2073 	/*
   2074 	 * If the vnode we found is mounted on, then cross the mount and get
   2075 	 * the root vnode in foundobj.  If this encounters an error, it will
   2076 	 * dispose of foundobj, but searchdir is untouched.
   2077 	 */
   2078 	if (error == 0 && foundobj != NULL &&
   2079 	    foundobj->v_type == VDIR &&
   2080 	    foundobj->v_mountedhere != NULL &&
   2081 	    (cnp->cn_flags & NOCROSSMOUNT) == 0) {
   2082 		error = lookup_crossmount(state, &startdir, &foundobj,
   2083 		    &startdir_locked);
   2084 	}
   2085 
   2086 	/* Now toss startdir and see if we have an error. */
   2087 	if (startdir != NULL)
   2088 		vrele(startdir);
   2089 	if (error)
   2090 		foundobj = NULL;
   2091 	else if (foundobj != NULL && (cnp->cn_flags & LOCKLEAF) != 0)
   2092 		vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
   2093 
   2094 	ndp->ni_vp = foundobj;
   2095 	return error;
   2096 }
   2097 
   2098 /*
   2099  * External interface. The partitioning between this function and the
   2100  * above isn't very clear - the above function exists mostly so code
   2101  * that uses "state->" can be shuffled around without having to change
   2102  * it to "state.".
   2103  */
   2104 int
   2105 lookup_for_nfsd_index(struct nameidata *ndp, struct vnode *startdir)
   2106 {
   2107 	struct namei_state state;
   2108 	int error;
   2109 
   2110 	KASSERT(ndp->ni_atdir == NULL);
   2111 	ndp->ni_atdir = startdir;
   2112 
   2113 	/*
   2114 	 * Note: the name sent in here (is not|should not be) allowed
   2115 	 * to contain a slash.
   2116 	 */
   2117 	if (strlen(ndp->ni_pathbuf->pb_path) > KERNEL_NAME_MAX) {
   2118 		return ENAMETOOLONG;
   2119 	}
   2120 	if (strchr(ndp->ni_pathbuf->pb_path, '/')) {
   2121 		return EINVAL;
   2122 	}
   2123 
   2124 	ndp->ni_pathlen = strlen(ndp->ni_pathbuf->pb_path) + 1;
   2125 	ndp->ni_pnbuf = NULL;
   2126 	ndp->ni_cnd.cn_nameptr = NULL;
   2127 
   2128 	namei_init(&state, ndp);
   2129 	error = do_lookup_for_nfsd_index(&state);
   2130 	namei_cleanup(&state);
   2131 
   2132 	return error;
   2133 }
   2134 
   2135 ////////////////////////////////////////////////////////////
   2136 
   2137 /*
   2138  * Reacquire a path name component.
   2139  * dvp is locked on entry and exit.
   2140  * *vpp is locked on exit unless it's NULL.
   2141  */
   2142 int
   2143 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
   2144     int dummy)
   2145 {
   2146 	int rdonly;			/* lookup read-only flag bit */
   2147 	int error = 0;
   2148 #ifdef DEBUG
   2149 	size_t newlen;			/* DEBUG: check name len */
   2150 	const char *cp;			/* DEBUG: check name ptr */
   2151 #endif /* DEBUG */
   2152 
   2153 	(void)dummy;
   2154 
   2155 	/*
   2156 	 * Setup: break out flag bits into variables.
   2157 	 */
   2158 	rdonly = cnp->cn_flags & RDONLY;
   2159 
   2160 	/*
   2161 	 * Search a new directory.
   2162 	 *
   2163 	 * The cn_hash value is for use by vfs_cache.
   2164 	 * The last component of the filename is left accessible via
   2165 	 * cnp->cn_nameptr for callers that need the name. Callers needing
   2166 	 * the name set the SAVENAME flag. When done, they assume
   2167 	 * responsibility for freeing the pathname buffer.
   2168 	 */
   2169 #ifdef DEBUG
   2170 #if 0
   2171 	cp = NULL;
   2172 	newhash = namei_hash(cnp->cn_nameptr, &cp);
   2173 	if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
   2174 		panic("relookup: bad hash");
   2175 #endif
   2176 	error = VOP_PARSEPATH(dvp, cnp->cn_nameptr, &newlen);
   2177 	if (error) {
   2178 		panic("relookup: parsepath failed with error %d", error);
   2179 	}
   2180 	if (cnp->cn_namelen != newlen)
   2181 		panic("relookup: bad len");
   2182 	cp = cnp->cn_nameptr + cnp->cn_namelen;
   2183 	while (*cp == '/')
   2184 		cp++;
   2185 	if (*cp != 0)
   2186 		panic("relookup: not last component");
   2187 #endif /* DEBUG */
   2188 
   2189 	/*
   2190 	 * Check for degenerate name (e.g. / or "")
   2191 	 * which is a way of talking about a directory,
   2192 	 * e.g. like "/." or ".".
   2193 	 */
   2194 	if (cnp->cn_nameptr[0] == '\0')
   2195 		panic("relookup: null name");
   2196 
   2197 	if (cnp->cn_flags & ISDOTDOT)
   2198 		panic("relookup: lookup on dot-dot");
   2199 
   2200 	/*
   2201 	 * We now have a segment name to search for, and a directory to search.
   2202 	 */
   2203 	*vpp = NULL;
   2204 	error = VOP_LOOKUP(dvp, vpp, cnp);
   2205 	if ((error) != 0) {
   2206 		KASSERTMSG((*vpp == NULL),
   2207 		    "leaf `%s' should be empty but is %p",
   2208 		    cnp->cn_nameptr, *vpp);
   2209 		if (error != EJUSTRETURN)
   2210 			goto bad;
   2211 	}
   2212 
   2213 	/*
   2214 	 * Check for symbolic link
   2215 	 */
   2216 	KASSERTMSG((*vpp == NULL || (*vpp)->v_type != VLNK ||
   2217 		(cnp->cn_flags & FOLLOW) == 0),
   2218 	    "relookup: symlink found");
   2219 
   2220 	/*
   2221 	 * Check for read-only lookups.
   2222 	 */
   2223 	if (rdonly && cnp->cn_nameiop != LOOKUP) {
   2224 		error = EROFS;
   2225 		if (*vpp) {
   2226 			vrele(*vpp);
   2227 		}
   2228 		goto bad;
   2229 	}
   2230 	/*
   2231 	 * Lock result.
   2232 	 */
   2233 	if (*vpp && *vpp != dvp) {
   2234 		error = vn_lock(*vpp, LK_EXCLUSIVE);
   2235 		if (error != 0) {
   2236 			vrele(*vpp);
   2237 			goto bad;
   2238 		}
   2239 	}
   2240 	return 0;
   2241 
   2242 bad:
   2243 	*vpp = NULL;
   2244 	return error;
   2245 }
   2246 
   2247 /*
   2248  * namei_simple - simple forms of namei.
   2249  *
   2250  * These are wrappers to allow the simple case callers of namei to be
   2251  * left alone while everything else changes under them.
   2252  */
   2253 
   2254 /* Flags */
   2255 struct namei_simple_flags_type {
   2256 	int dummy;
   2257 };
   2258 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
   2259 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
   2260 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
   2261 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
   2262 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
   2263 
   2264 static int
   2265 namei_simple_convert_flags(namei_simple_flags_t sflags)
   2266 {
   2267 
   2268 	if (sflags == NSM_NOFOLLOW_NOEMULROOT)
   2269 		return NOFOLLOW | 0;
   2270 	if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
   2271 		return NOFOLLOW | TRYEMULROOT;
   2272 	if (sflags == NSM_FOLLOW_NOEMULROOT)
   2273 		return FOLLOW | 0;
   2274 	if (sflags == NSM_FOLLOW_TRYEMULROOT)
   2275 		return FOLLOW | TRYEMULROOT;
   2276 	panic("namei_simple_convert_flags: bogus sflags\n");
   2277 	return 0;
   2278 }
   2279 
   2280 int
   2281 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
   2282     struct vnode **vp_ret)
   2283 {
   2284 
   2285 	return nameiat_simple_kernel(NULL, path, sflags, vp_ret);
   2286 }
   2287 
   2288 int
   2289 nameiat_simple(struct vnode *dvp, struct pathbuf *pb,
   2290     namei_simple_flags_t sflags, struct vnode **vp_ret)
   2291 {
   2292 	struct nameidata nd;
   2293 	int error;
   2294 
   2295 	NDINIT(&nd, LOOKUP, namei_simple_convert_flags(sflags), pb);
   2296 
   2297 	if (dvp != NULL)
   2298 		NDAT(&nd, dvp);
   2299 
   2300 	error = namei(&nd);
   2301 	if (error != 0)
   2302 		return error;
   2303 
   2304 	*vp_ret = nd.ni_vp;
   2305 	return 0;
   2306 }
   2307 
   2308 int
   2309 nameiat_simple_kernel(struct vnode *dvp, const char *path,
   2310     namei_simple_flags_t sflags, struct vnode **vp_ret)
   2311 {
   2312 	struct pathbuf *pb;
   2313 	int error;
   2314 
   2315 	pb = pathbuf_create(path);
   2316 	if (pb == NULL)
   2317 		return ENOMEM;
   2318 
   2319 	error = nameiat_simple(dvp, pb, sflags, vp_ret);
   2320 
   2321 	pathbuf_destroy(pb);
   2322 	return error;
   2323 }
   2324 
   2325 int
   2326 namei_simple_user(const char *path, namei_simple_flags_t sflags,
   2327     struct vnode **vp_ret)
   2328 {
   2329 
   2330 	return nameiat_simple_user(NULL, path, sflags, vp_ret);
   2331 }
   2332 
   2333 int
   2334 nameiat_simple_user(struct vnode *dvp, const char *path,
   2335     namei_simple_flags_t sflags, struct vnode **vp_ret)
   2336 {
   2337 	struct pathbuf *pb;
   2338 	int error;
   2339 
   2340 	error = pathbuf_copyin(path, &pb);
   2341 	if (error)
   2342 		return error;
   2343 
   2344 	error = nameiat_simple(dvp, pb, sflags, vp_ret);
   2345 
   2346 	pathbuf_destroy(pb);
   2347 	return error;
   2348 }
   2349