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