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