Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.215
      1 /*	$NetBSD: vfs_lookup.c,v 1.215 2020/04/04 20:49: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.215 2020/04/04 20:49: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/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 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 	/* NB: must not block while inspecting the cwdinfo. */
    550 	cwdi = cwdenter(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 	cwdexit(cwdi);
    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.
    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  * Take care of crossing a mounted-on vnode.  On error, foundobj_ret will be
    918  * vrele'd, but searchdir is left alone.
    919  */
    920 static int
    921 lookup_crossmount(struct namei_state *state,
    922 		  struct vnode **searchdir_ret,
    923 		  struct vnode **foundobj_ret,
    924 		  bool *searchdir_locked)
    925 {
    926 	struct componentname *cnp = state->cnp;
    927 	struct vnode *foundobj;
    928 	struct vnode *searchdir;
    929 	struct mount *mp;
    930 	int error, lktype;
    931 
    932 	searchdir = *searchdir_ret;
    933 	foundobj = *foundobj_ret;
    934 	error = 0;
    935 
    936 	KASSERT((cnp->cn_flags & NOCROSSMOUNT) == 0);
    937 	KASSERT(searchdir != NULL);
    938 
    939 	/* First, unlock searchdir (oof). */
    940 	if (*searchdir_locked) {
    941 		lktype = VOP_ISLOCKED(searchdir);
    942 		VOP_UNLOCK(searchdir);
    943 		*searchdir_locked = false;
    944 	} else {
    945 		lktype = LK_NONE;
    946 	}
    947 
    948 	/*
    949 	 * Do an unlocked check to see if the vnode has been mounted on; if
    950 	 * so find the root of the mounted file system.
    951 	 */
    952 	while (foundobj->v_type == VDIR &&
    953 	    (mp = foundobj->v_mountedhere) != NULL &&
    954 	    (cnp->cn_flags & NOCROSSMOUNT) == 0) {
    955 		KASSERTMSG(searchdir != foundobj, "same vn %p", searchdir);
    956 		/*
    957 		 * First get the vnode stable.  LK_SHARED works brilliantly
    958 		 * here because almost nothing else wants to lock the
    959 		 * covered vnode.
    960 		 */
    961 		error = vn_lock(foundobj, LK_SHARED);
    962 		if (error != 0) {
    963 			vrele(foundobj);
    964 			*foundobj_ret = NULL;
    965 			break;
    966 		}
    967 
    968 		/* Then check to see if something is still mounted on it. */
    969 		if ((mp = foundobj->v_mountedhere) == NULL) {
    970 			VOP_UNLOCK(foundobj);
    971 			break;
    972 		}
    973 
    974 		/* Get a reference to the mountpoint, and ditch foundobj. */
    975 		error = vfs_busy(mp);
    976 		vput(foundobj);
    977 		if (error != 0) {
    978 			*foundobj_ret = NULL;
    979 			break;
    980 		}
    981 
    982 		/* Now get a reference on the root vnode, and drop mount. */
    983 		error = VFS_ROOT(mp, LK_NONE, &foundobj);
    984 		vfs_unbusy(mp);
    985 		if (error) {
    986 			*foundobj_ret = NULL;
    987 			break;
    988 		}
    989 
    990 		/*
    991 		 * Avoid locking vnodes from two filesystems because
    992 		 * it's prone to deadlock, e.g. when using puffs.
    993 		 * Also, it isn't a good idea to propagate slowness of
    994 		 * a filesystem up to the root directory. For now,
    995 		 * only handle the common case, where foundobj is
    996 		 * VDIR.
    997 		 *
    998 		 * In this case set searchdir to null to avoid using
    999 		 * it again. It is not correct to set searchdir ==
   1000 		 * foundobj here as that will confuse the caller.
   1001 		 * (See PR 40740.)
   1002 		 */
   1003 		if (searchdir == NULL) {
   1004 			/* already been here once; do nothing further */
   1005 		} else if (foundobj->v_type == VDIR) {
   1006 			vrele(searchdir);
   1007 			*searchdir_ret = searchdir = NULL;
   1008 			*foundobj_ret = foundobj;
   1009 			lktype = LK_NONE;
   1010 		}
   1011 	}
   1012 
   1013 	/* If searchdir is still around, re-lock it. */
   1014  	if (error == 0 && lktype != LK_NONE) {
   1015 		vn_lock(searchdir, lktype | LK_RETRY);
   1016 		*searchdir_locked = true;
   1017 	}
   1018 	return error;
   1019 }
   1020 
   1021 /*
   1022  * Call VOP_LOOKUP for a single lookup; return a new search directory
   1023  * (used when crossing mountpoints up or searching union mounts down) and
   1024  * the found object, which for create operations may be NULL on success.
   1025  *
   1026  * Note that the new search directory may be null, which means the
   1027  * searchdir was unlocked and released. This happens in the common case
   1028  * when crossing a mount point downwards, in order to avoid coupling
   1029  * locks between different file system volumes. Importantly, this can
   1030  * happen even if the call fails. (XXX: this is gross and should be
   1031  * tidied somehow.)
   1032  */
   1033 static int
   1034 lookup_once(struct namei_state *state,
   1035 	    struct vnode *searchdir,
   1036 	    struct vnode **newsearchdir_ret,
   1037 	    struct vnode **foundobj_ret,
   1038 	    bool *newsearchdir_locked_ret)
   1039 {
   1040 	struct vnode *tmpvn;		/* scratch vnode */
   1041 	struct vnode *foundobj;		/* result */
   1042 	struct lwp *l = curlwp;
   1043 	bool searchdir_locked = false;
   1044 	int error, lktype;
   1045 
   1046 	struct componentname *cnp = state->cnp;
   1047 	struct nameidata *ndp = state->ndp;
   1048 
   1049 	KASSERT(cnp == &ndp->ni_cnd);
   1050 	*newsearchdir_ret = searchdir;
   1051 
   1052 	/*
   1053 	 * Handle "..": two special cases.
   1054 	 * 1. If at root directory (e.g. after chroot)
   1055 	 *    or at absolute root directory
   1056 	 *    then ignore it so can't get out.
   1057 	 * 1a. If at the root of the emulation filesystem go to the real
   1058 	 *    root. So "/../<path>" is always absolute.
   1059 	 * 1b. If we have somehow gotten out of a jail, warn
   1060 	 *    and also ignore it so we can't get farther out.
   1061 	 * 2. If this vnode is the root of a mounted
   1062 	 *    filesystem, then replace it with the
   1063 	 *    vnode which was mounted on so we take the
   1064 	 *    .. in the other file system.
   1065 	 */
   1066 	if (cnp->cn_flags & ISDOTDOT) {
   1067 		struct proc *p = l->l_proc;
   1068 
   1069 		for (;;) {
   1070 			if (searchdir == ndp->ni_rootdir ||
   1071 			    searchdir == rootvnode) {
   1072 				foundobj = searchdir;
   1073 				vref(foundobj);
   1074 				*foundobj_ret = foundobj;
   1075 				error = 0;
   1076 				goto done;
   1077 			}
   1078 			if (ndp->ni_rootdir != rootvnode) {
   1079 				int retval;
   1080 
   1081 				retval = vn_isunder(searchdir, ndp->ni_rootdir, l);
   1082 				if (!retval) {
   1083 				    /* Oops! We got out of jail! */
   1084 				    log(LOG_WARNING,
   1085 					"chrooted pid %d uid %d (%s) "
   1086 					"detected outside of its chroot\n",
   1087 					p->p_pid, kauth_cred_geteuid(l->l_cred),
   1088 					p->p_comm);
   1089 				    /* Put us at the jail root. */
   1090 				    vrele(searchdir);
   1091 				    searchdir = NULL;
   1092 				    foundobj = ndp->ni_rootdir;
   1093 				    vref(foundobj);
   1094 				    vref(foundobj);
   1095 				    *newsearchdir_ret = foundobj;
   1096 				    *foundobj_ret = foundobj;
   1097 				    error = 0;
   1098 				    goto done;
   1099 				}
   1100 			}
   1101 			if ((searchdir->v_vflag & VV_ROOT) == 0 ||
   1102 			    (cnp->cn_flags & NOCROSSMOUNT))
   1103 				break;
   1104 			tmpvn = searchdir;
   1105 			searchdir = searchdir->v_mount->mnt_vnodecovered;
   1106 			vref(searchdir);
   1107 			vrele(tmpvn);
   1108 			*newsearchdir_ret = searchdir;
   1109 		}
   1110 	}
   1111 
   1112 	/*
   1113 	 * If the file system supports VOP_LOOKUP() with a shared lock, and
   1114 	 * we are not making any modifications (nameiop LOOKUP) or this is
   1115 	 * not the last component then get a shared lock.  Where we can't do
   1116 	 * fast-forwarded lookups (for example with layered file systems)
   1117 	 * then this is the fallback for reducing lock contention.
   1118 	 */
   1119 	if ((searchdir->v_mount->mnt_iflag & IMNT_SHRLOOKUP) != 0 &&
   1120 	    (cnp->cn_nameiop == LOOKUP || (cnp->cn_flags & ISLASTCN) == 0)) {
   1121 	    	lktype = LK_SHARED;
   1122 	} else {
   1123 		lktype = LK_EXCLUSIVE;
   1124 	}
   1125 
   1126 	/*
   1127 	 * We now have a segment name to search for, and a directory to search.
   1128 	 * Our vnode state here is that "searchdir" is held.
   1129 	 */
   1130 unionlookup:
   1131 	foundobj = NULL;
   1132 	if (!searchdir_locked) {
   1133 		vn_lock(searchdir, lktype | LK_RETRY);
   1134 		searchdir_locked = true;
   1135 	}
   1136 	error = VOP_LOOKUP(searchdir, &foundobj, cnp);
   1137 
   1138 	if (error != 0) {
   1139 		KASSERTMSG((foundobj == NULL),
   1140 		    "leaf `%s' should be empty but is %p",
   1141 		    cnp->cn_nameptr, foundobj);
   1142 #ifdef NAMEI_DIAGNOSTIC
   1143 		printf("not found\n");
   1144 #endif /* NAMEI_DIAGNOSTIC */
   1145 
   1146 		/*
   1147 		 * If ENOLCK, the file system needs us to retry the lookup
   1148 		 * with an exclusive lock.  It's likely nothing was found in
   1149 		 * cache and/or modifications need to be made.
   1150 		 */
   1151 		if (error == ENOLCK) {
   1152 			KASSERT(VOP_ISLOCKED(searchdir) == LK_SHARED);
   1153 			KASSERT(searchdir_locked);
   1154 			if (vn_lock(searchdir, LK_UPGRADE | LK_NOWAIT)) {
   1155 				VOP_UNLOCK(searchdir);
   1156 				searchdir_locked = false;
   1157 			}
   1158 			lktype = LK_EXCLUSIVE;
   1159 			goto unionlookup;
   1160 		}
   1161 
   1162 		if ((error == ENOENT) &&
   1163 		    (searchdir->v_vflag & VV_ROOT) &&
   1164 		    (searchdir->v_mount->mnt_flag & MNT_UNION)) {
   1165 			tmpvn = searchdir;
   1166 			searchdir = searchdir->v_mount->mnt_vnodecovered;
   1167 			vref(searchdir);
   1168 			vput(tmpvn);
   1169 			searchdir_locked = false;
   1170 			*newsearchdir_ret = searchdir;
   1171 			goto unionlookup;
   1172 		}
   1173 
   1174 		if (error != EJUSTRETURN)
   1175 			goto done;
   1176 
   1177 		/*
   1178 		 * If this was not the last component, or there were trailing
   1179 		 * slashes, and we are not going to create a directory,
   1180 		 * then the name must exist.
   1181 		 */
   1182 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
   1183 			error = ENOENT;
   1184 			goto done;
   1185 		}
   1186 
   1187 		/*
   1188 		 * If creating and at end of pathname, then can consider
   1189 		 * allowing file to be created.
   1190 		 */
   1191 		if (state->rdonly) {
   1192 			error = EROFS;
   1193 			goto done;
   1194 		}
   1195 
   1196 		/*
   1197 		 * We return success and a NULL foundobj to indicate
   1198 		 * that the entry doesn't currently exist, leaving a
   1199 		 * pointer to the (normally, locked) directory vnode
   1200 		 * as searchdir.
   1201 		 */
   1202 		*foundobj_ret = NULL;
   1203 		error = 0;
   1204 		goto done;
   1205 	}
   1206 #ifdef NAMEI_DIAGNOSTIC
   1207 	printf("found\n");
   1208 #endif /* NAMEI_DIAGNOSTIC */
   1209 
   1210 	/*
   1211 	 * Take into account any additional components consumed by the
   1212 	 * underlying filesystem.  This will include any trailing slashes after
   1213 	 * the last component consumed.
   1214 	 */
   1215 	if (cnp->cn_consume > 0) {
   1216 		ndp->ni_pathlen -= cnp->cn_consume - state->slashes;
   1217 		ndp->ni_next += cnp->cn_consume - state->slashes;
   1218 		cnp->cn_consume = 0;
   1219 		if (ndp->ni_next[0] == '\0')
   1220 			cnp->cn_flags |= ISLASTCN;
   1221 	}
   1222 
   1223 	/* Unlock, unless the caller needs the parent locked. */
   1224 	if (searchdir != NULL) {
   1225 		KASSERT(searchdir_locked);
   1226 		if ((cnp->cn_flags & (ISLASTCN | LOCKPARENT)) !=
   1227 		    (ISLASTCN | LOCKPARENT)) {
   1228 		    	VOP_UNLOCK(searchdir);
   1229 		    	searchdir_locked = false;
   1230 		}
   1231 	} else {
   1232 		KASSERT(!searchdir_locked);
   1233 	}
   1234 
   1235 	*foundobj_ret = foundobj;
   1236 	error = 0;
   1237 done:
   1238 	*newsearchdir_locked_ret = searchdir_locked;
   1239 	return error;
   1240 }
   1241 
   1242 /*
   1243  * Parse out the first path name component that we need to to consider.
   1244  *
   1245  * While doing this, attempt to use the name cache to fast-forward through
   1246  * as many "easy" to find components of the path as possible.
   1247  *
   1248  * We use the namecache's node locks to form a chain, and avoid as many
   1249  * vnode references and locks as possible.  In the ideal case, only the
   1250  * final vnode will have its reference count adjusted and lock taken.
   1251  */
   1252 static int
   1253 lookup_fastforward(struct namei_state *state, struct vnode **searchdir_ret,
   1254 		   struct vnode **foundobj_ret)
   1255 {
   1256 	struct componentname *cnp = state->cnp;
   1257 	struct nameidata *ndp = state->ndp;
   1258 	krwlock_t *plock;
   1259 	struct vnode *foundobj, *searchdir;
   1260 	int error, error2;
   1261 	size_t oldpathlen;
   1262 	const char *oldnameptr;
   1263 
   1264 	/*
   1265 	 * Eat as many path name components as possible before giving up and
   1266 	 * letting lookup_once() handle it.  Remember the starting point in
   1267 	 * case we can't get vnode references and need to roll back.
   1268 	 */
   1269 	plock = NULL;
   1270 	searchdir = *searchdir_ret;
   1271 	oldnameptr = cnp->cn_nameptr;
   1272 	oldpathlen = ndp->ni_pathlen;
   1273 	for (;;) {
   1274 		foundobj = NULL;
   1275 
   1276 		/*
   1277 		 * Get the next component name.  There should be no slashes
   1278 		 * here, and we shouldn't have looped around if we were
   1279 		 * done.
   1280 		 */
   1281 		KASSERT(cnp->cn_nameptr[0] != '/');
   1282 		KASSERT(cnp->cn_nameptr[0] != '\0');
   1283 		if ((error = lookup_parsepath(state)) != 0) {
   1284 			break;
   1285 		}
   1286 
   1287 		/*
   1288 		 * Can't deal with dotdot lookups, because it means lock
   1289 		 * order reversal, and there are checks in lookup_once()
   1290 		 * that need to be made.  Also check for missing mountpoints.
   1291 		 */
   1292 		if ((cnp->cn_flags & ISDOTDOT) != 0 ||
   1293 		    searchdir->v_mount == NULL) {
   1294 			error = EOPNOTSUPP;
   1295 			break;
   1296 		}
   1297 
   1298 		/*
   1299 		 * Can't deal with last component when modifying; this needs
   1300 		 * searchdir locked and VOP_LOOKUP() called (which can and
   1301 		 * does modify state, despite the name).
   1302 		 */
   1303 		if ((cnp->cn_flags & ISLASTCN) != 0) {
   1304 			if (cnp->cn_nameiop != LOOKUP ||
   1305 			    (cnp->cn_flags & LOCKPARENT) != 0) {
   1306 				error = EOPNOTSUPP;
   1307 				break;
   1308 			}
   1309 		}
   1310 
   1311 		/* Can't deal with -o union lookups. */
   1312 		if ((searchdir->v_vflag & VV_ROOT) != 0 &&
   1313 		    (searchdir->v_mount->mnt_flag & MNT_UNION) != 0) {
   1314 		    	error = EOPNOTSUPP;
   1315 		    	break;
   1316 		}
   1317 
   1318 		/*
   1319 		 * Good, now look for it in cache.  cache_lookup_linked()
   1320 		 * will fail if there's nothing there, or if there's no
   1321 		 * ownership info for the directory, or if the user doesn't
   1322 		 * have permission to look up files in this directory.
   1323 		 */
   1324 		if (!cache_lookup_linked(searchdir, cnp->cn_nameptr,
   1325 		    cnp->cn_namelen, &foundobj, &plock, cnp->cn_cred)) {
   1326 			error = EOPNOTSUPP;
   1327 			break;
   1328 		}
   1329 		KASSERT(plock != NULL && rw_lock_held(plock));
   1330 
   1331 		/* Scored a hit.  Negative is good too (ENOENT). */
   1332 		if (foundobj == NULL) {
   1333 			error = ENOENT;
   1334 			break;
   1335 		}
   1336 
   1337 		/*
   1338 		 * Stop and get a hold on the vnode if there's something
   1339 		 * that can't be handled here:
   1340 		 *
   1341 		 * - we've reached the last component.
   1342 		 * - or encountered a mount point that needs to be crossed.
   1343 		 * - or encountered something other than a directory.
   1344 		 */
   1345 		if ((cnp->cn_flags & ISLASTCN) != 0 ||
   1346 		    foundobj->v_type != VDIR ||
   1347 		    (foundobj->v_type == VDIR &&
   1348 		    foundobj->v_mountedhere != NULL)) {
   1349 		    	mutex_enter(foundobj->v_interlock);
   1350 			error = vcache_tryvget(foundobj);
   1351 			/* v_interlock now unheld */
   1352 			if (error != 0) {
   1353 				foundobj = NULL;
   1354 			}
   1355 			break;
   1356 		}
   1357 
   1358 		/*
   1359 		 * Otherwise, we're still in business.  Set the found VDIR
   1360 		 * vnode as the search dir for the next component and
   1361 		 * continue on to it.
   1362 		 */
   1363 		cnp->cn_nameptr = ndp->ni_next;
   1364 		searchdir = foundobj;
   1365 	}
   1366 
   1367 	/*
   1368 	 * If we ended up with a new search dir, ref it before dropping the
   1369 	 * namecache's lock.  The lock prevents both searchdir and foundobj
   1370 	 * from disappearing.  If we can't ref the new searchdir, we have a
   1371 	 * bit of a problem.  Roll back the fastforward to the beginning and
   1372 	 * let lookup_once() take care of it.
   1373 	 */
   1374 	if (searchdir != *searchdir_ret) {
   1375 		mutex_enter(searchdir->v_interlock);
   1376 		error2 = vcache_tryvget(searchdir);
   1377 		/* v_interlock now unheld */
   1378 		KASSERT(plock != NULL);
   1379 		rw_exit(plock);
   1380 		if (__predict_true(error2 == 0)) {
   1381 			/* Returning new searchdir, and maybe new foundobj. */
   1382 			vrele(*searchdir_ret);
   1383 			*searchdir_ret = searchdir;
   1384 		} else {
   1385 			/* Returning nothing. */
   1386 			if (foundobj != NULL) {
   1387 				vrele(foundobj);
   1388 				foundobj = NULL;
   1389 			}
   1390 			cnp->cn_nameptr = oldnameptr;
   1391 			ndp->ni_pathlen = oldpathlen;
   1392 			error = lookup_parsepath(state);
   1393 			if (error == 0) {
   1394 				error = EOPNOTSUPP;
   1395 			}
   1396 		}
   1397 	} else if (plock != NULL) {
   1398 		/* Drop any namecache lock still held. */
   1399 		rw_exit(plock);
   1400 	}
   1401 
   1402 	KASSERT(error == 0 ? foundobj != NULL : foundobj == NULL);
   1403 	*foundobj_ret = foundobj;
   1404 	return error;
   1405 }
   1406 
   1407 //////////////////////////////
   1408 
   1409 /*
   1410  * Do a complete path search from a single root directory.
   1411  * (This is called up to twice if TRYEMULROOT is in effect.)
   1412  */
   1413 static int
   1414 namei_oneroot(struct namei_state *state,
   1415 	 int neverfollow, int inhibitmagic, int isnfsd)
   1416 {
   1417 	struct nameidata *ndp = state->ndp;
   1418 	struct componentname *cnp = state->cnp;
   1419 	struct vnode *searchdir, *foundobj;
   1420 	bool searchdir_locked = false;
   1421 	int error;
   1422 
   1423 	error = namei_start(state, isnfsd, &searchdir);
   1424 	if (error) {
   1425 		ndp->ni_dvp = NULL;
   1426 		ndp->ni_vp = NULL;
   1427 		return error;
   1428 	}
   1429 	KASSERT(searchdir->v_type == VDIR);
   1430 
   1431 	/*
   1432 	 * Setup: break out flag bits into variables.
   1433 	 */
   1434 	state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
   1435 	if (cnp->cn_nameiop == DELETE)
   1436 		state->docache = 0;
   1437 	state->rdonly = cnp->cn_flags & RDONLY;
   1438 
   1439 	/*
   1440 	 * Keep going until we run out of path components.
   1441 	 */
   1442 	cnp->cn_nameptr = ndp->ni_pnbuf;
   1443 
   1444 	/* drop leading slashes (already used them to choose startdir) */
   1445 	while (cnp->cn_nameptr[0] == '/') {
   1446 		cnp->cn_nameptr++;
   1447 		ndp->ni_pathlen--;
   1448 	}
   1449 	/* was it just "/"? */
   1450 	if (cnp->cn_nameptr[0] == '\0') {
   1451 		foundobj = searchdir;
   1452 		searchdir = NULL;
   1453 		cnp->cn_flags |= ISLASTCN;
   1454 
   1455 		/* bleh */
   1456 		goto skiploop;
   1457 	}
   1458 
   1459 	for (;;) {
   1460 		KASSERT(searchdir != NULL);
   1461 		KASSERT(!searchdir_locked);
   1462 
   1463 		/*
   1464 		 * Parse out the first path name component that we need to
   1465 		 * to consider.  While doing this, attempt to use the name
   1466 		 * cache to fast-forward through as many "easy" to find
   1467 		 * components of the path as possible.
   1468 		 */
   1469 		error = lookup_fastforward(state, &searchdir, &foundobj);
   1470 
   1471 		/*
   1472 		 * If we didn't get a good answer from the namecache, then
   1473 		 * go directly to the file system.
   1474 		 */
   1475 		if (error != 0 && error != ENOENT) {
   1476 			error = lookup_once(state, searchdir, &searchdir,
   1477 			    &foundobj, &searchdir_locked);
   1478 		}
   1479 
   1480 		/*
   1481 		 * If the vnode we found is mounted on, then cross the mount
   1482 		 * and get the root vnode in foundobj.  If this encounters
   1483 		 * an error, it will dispose of foundobj, but searchdir is
   1484 		 * untouched.
   1485 		 */
   1486 		if (error == 0 && foundobj != NULL &&
   1487 		    foundobj->v_type == VDIR &&
   1488 		    foundobj->v_mountedhere != NULL &&
   1489 		    (cnp->cn_flags & NOCROSSMOUNT) == 0) {
   1490 		    	error = lookup_crossmount(state, &searchdir,
   1491 		    	    &foundobj, &searchdir_locked);
   1492 		}
   1493 
   1494 		if (error) {
   1495 			if (searchdir != NULL) {
   1496 				if (searchdir_locked) {
   1497 					searchdir_locked = false;
   1498 					vput(searchdir);
   1499 				} else {
   1500 					vrele(searchdir);
   1501 				}
   1502 			}
   1503 			ndp->ni_dvp = NULL;
   1504 			ndp->ni_vp = NULL;
   1505 			/*
   1506 			 * Note that if we're doing TRYEMULROOT we can
   1507 			 * retry with the normal root. Where this is
   1508 			 * currently set matches previous practice,
   1509 			 * but the previous practice didn't make much
   1510 			 * sense and somebody should sit down and
   1511 			 * figure out which cases should cause retry
   1512 			 * and which shouldn't. XXX.
   1513 			 */
   1514 			state->attempt_retry = 1;
   1515 			return (error);
   1516 		}
   1517 
   1518 		if (foundobj == NULL) {
   1519 			/*
   1520 			 * Success with no object returned means we're
   1521 			 * creating something and it isn't already
   1522 			 * there. Break out of the main loop now so
   1523 			 * the code below doesn't have to test for
   1524 			 * foundobj == NULL.
   1525 			 */
   1526 			/* lookup_once can't have dropped the searchdir */
   1527 			KASSERT(searchdir != NULL);
   1528 			break;
   1529 		}
   1530 
   1531 		/*
   1532 		 * Check for symbolic link. If we've reached one,
   1533 		 * follow it, unless we aren't supposed to. Back up
   1534 		 * over any slashes that we skipped, as we will need
   1535 		 * them again.
   1536 		 */
   1537 		if (namei_atsymlink(state, foundobj)) {
   1538 			/* Don't need searchdir locked any more. */
   1539 			if (searchdir_locked) {
   1540 				searchdir_locked = false;
   1541 				VOP_UNLOCK(searchdir);
   1542 			}
   1543 			ndp->ni_pathlen += state->slashes;
   1544 			ndp->ni_next -= state->slashes;
   1545 			if (neverfollow) {
   1546 				error = EINVAL;
   1547 			} else if (searchdir == NULL) {
   1548 				/*
   1549 				 * dholland 20160410: lookup_once only
   1550 				 * drops searchdir if it crossed a
   1551 				 * mount point. Therefore, if we get
   1552 				 * here it means we crossed a mount
   1553 				 * point to a mounted filesystem whose
   1554 				 * root vnode is a symlink. In theory
   1555 				 * we could continue at this point by
   1556 				 * using the pre-crossing searchdir
   1557 				 * (e.g. just take out an extra
   1558 				 * reference on it before calling
   1559 				 * lookup_once so we still have it),
   1560 				 * but this will make an ugly mess and
   1561 				 * it should never happen in practice
   1562 				 * as only badly broken filesystems
   1563 				 * have non-directory root vnodes. (I
   1564 				 * have seen this sort of thing with
   1565 				 * NFS occasionally but even then it
   1566 				 * means something's badly wrong.)
   1567 				 */
   1568 				error = ENOTDIR;
   1569 			} else {
   1570 				/*
   1571 				 * dholland 20110410: if we're at a
   1572 				 * union mount it might make sense to
   1573 				 * use the top of the union stack here
   1574 				 * rather than the layer we found the
   1575 				 * symlink in. (FUTURE)
   1576 				 */
   1577 				error = namei_follow(state, inhibitmagic,
   1578 						     searchdir, foundobj,
   1579 						     &searchdir);
   1580 			}
   1581 			if (error) {
   1582 				KASSERT(searchdir != foundobj);
   1583 				if (searchdir != NULL) {
   1584 					vrele(searchdir);
   1585 				}
   1586 				vrele(foundobj);
   1587 				ndp->ni_dvp = NULL;
   1588 				ndp->ni_vp = NULL;
   1589 				return error;
   1590 			}
   1591 			vrele(foundobj);
   1592 			foundobj = NULL;
   1593 
   1594 			/*
   1595 			 * If we followed a symlink to `/' and there
   1596 			 * are no more components after the symlink,
   1597 			 * we're done with the loop and what we found
   1598 			 * is the searchdir.
   1599 			 */
   1600 			if (cnp->cn_nameptr[0] == '\0') {
   1601 				KASSERT(searchdir != NULL);
   1602 				foundobj = searchdir;
   1603 				searchdir = NULL;
   1604 				cnp->cn_flags |= ISLASTCN;
   1605 				break;
   1606 			}
   1607 
   1608 			continue;
   1609 		}
   1610 
   1611 		/*
   1612 		 * Not a symbolic link.
   1613 		 *
   1614 		 * Check for directory, if the component was
   1615 		 * followed by a series of slashes.
   1616 		 */
   1617 		if ((foundobj->v_type != VDIR) &&
   1618 		    (cnp->cn_flags & REQUIREDIR)) {
   1619 			KASSERT(foundobj != searchdir);
   1620 			if (searchdir) {
   1621 				if (searchdir_locked) {
   1622 					searchdir_locked = false;
   1623 					vput(searchdir);
   1624 				} else {
   1625 					vrele(searchdir);
   1626 				}
   1627 			} else {
   1628 				KASSERT(!searchdir_locked);
   1629 			}
   1630 			vrele(foundobj);
   1631 			ndp->ni_dvp = NULL;
   1632 			ndp->ni_vp = NULL;
   1633 			state->attempt_retry = 1;
   1634 			return ENOTDIR;
   1635 		}
   1636 
   1637 		/*
   1638 		 * Stop if we've reached the last component.
   1639 		 */
   1640 		if (cnp->cn_flags & ISLASTCN) {
   1641 			break;
   1642 		}
   1643 
   1644 		/*
   1645 		 * Continue with the next component.
   1646 		 */
   1647 		cnp->cn_nameptr = ndp->ni_next;
   1648 		if (searchdir != NULL) {
   1649 			if (searchdir_locked) {
   1650 				searchdir_locked = false;
   1651 				vput(searchdir);
   1652 			} else {
   1653 				vrele(searchdir);
   1654 			}
   1655 		}
   1656 		searchdir = foundobj;
   1657 		foundobj = NULL;
   1658 	}
   1659 
   1660 	KASSERT((cnp->cn_flags & LOCKPARENT) == 0 || searchdir == NULL ||
   1661 	    VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
   1662 
   1663  skiploop:
   1664 
   1665 	if (foundobj != NULL) {
   1666 		if (foundobj == ndp->ni_erootdir) {
   1667 			/*
   1668 			 * We are about to return the emulation root.
   1669 			 * This isn't a good idea because code might
   1670 			 * repeatedly lookup ".." until the file
   1671 			 * matches that returned for "/" and loop
   1672 			 * forever.  So convert it to the real root.
   1673 			 */
   1674 			if (searchdir != NULL) {
   1675 				if (searchdir_locked) {
   1676 					vput(searchdir);
   1677 					searchdir_locked = false;
   1678 				} else {
   1679 					vrele(searchdir);
   1680 				}
   1681 				searchdir = NULL;
   1682 			}
   1683 			vrele(foundobj);
   1684 			foundobj = ndp->ni_rootdir;
   1685 			vref(foundobj);
   1686 		}
   1687 
   1688 		/*
   1689 		 * If the caller requested the parent node (i.e. it's
   1690 		 * a CREATE, DELETE, or RENAME), and we don't have one
   1691 		 * (because this is the root directory, or we crossed
   1692 		 * a mount point), then we must fail.
   1693 		 */
   1694 		if (cnp->cn_nameiop != LOOKUP &&
   1695 		    (searchdir == NULL ||
   1696 		     searchdir->v_mount != foundobj->v_mount)) {
   1697 			if (searchdir) {
   1698 				if (searchdir_locked) {
   1699 					vput(searchdir);
   1700 					searchdir_locked = false;
   1701 				} else {
   1702 					vrele(searchdir);
   1703 				}
   1704 				searchdir = NULL;
   1705 			}
   1706 			vrele(foundobj);
   1707 			foundobj = NULL;
   1708 			ndp->ni_dvp = NULL;
   1709 			ndp->ni_vp = NULL;
   1710 			state->attempt_retry = 1;
   1711 
   1712 			switch (cnp->cn_nameiop) {
   1713 			    case CREATE:
   1714 				return EEXIST;
   1715 			    case DELETE:
   1716 			    case RENAME:
   1717 				return EBUSY;
   1718 			    default:
   1719 				break;
   1720 			}
   1721 			panic("Invalid nameiop\n");
   1722 		}
   1723 
   1724 		/*
   1725 		 * Disallow directory write attempts on read-only lookups.
   1726 		 * Prefers EEXIST over EROFS for the CREATE case.
   1727 		 */
   1728 		if (state->rdonly &&
   1729 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
   1730 			if (searchdir) {
   1731 				if (searchdir_locked) {
   1732 					vput(searchdir);
   1733 					searchdir_locked = false;
   1734 				} else {
   1735 					vrele(searchdir);
   1736 				}
   1737 				searchdir = NULL;
   1738 			}
   1739 			vrele(foundobj);
   1740 			foundobj = NULL;
   1741 			ndp->ni_dvp = NULL;
   1742 			ndp->ni_vp = NULL;
   1743 			state->attempt_retry = 1;
   1744 			return EROFS;
   1745 		}
   1746 
   1747 		/* Lock the leaf node if requested. */
   1748 		if ((cnp->cn_flags & (LOCKLEAF | LOCKPARENT)) == LOCKPARENT &&
   1749 		    searchdir == foundobj) {
   1750 			/*
   1751 			 * Note: if LOCKPARENT but not LOCKLEAF is
   1752 			 * set, and searchdir == foundobj, this code
   1753 			 * necessarily unlocks the parent as well as
   1754 			 * the leaf. That is, just because you specify
   1755 			 * LOCKPARENT doesn't mean you necessarily get
   1756 			 * a locked parent vnode. The code in
   1757 			 * vfs_syscalls.c, and possibly elsewhere,
   1758 			 * that uses this combination "knows" this, so
   1759 			 * it can't be safely changed. Feh. XXX
   1760 			 */
   1761 			KASSERT(searchdir_locked);
   1762 		    	VOP_UNLOCK(searchdir);
   1763 		    	searchdir_locked = false;
   1764 		} else if ((cnp->cn_flags & LOCKLEAF) != 0 &&
   1765 		    (searchdir != foundobj ||
   1766 		    (cnp->cn_flags & LOCKPARENT) == 0)) {
   1767 			const int lktype = (cnp->cn_flags & LOCKSHARED) != 0 ?
   1768 			    LK_SHARED : LK_EXCLUSIVE;
   1769 			vn_lock(foundobj, lktype | LK_RETRY);
   1770 		}
   1771 	}
   1772 
   1773 	/*
   1774 	 * Done.
   1775 	 */
   1776 
   1777 	/*
   1778 	 * If LOCKPARENT is not set, the parent directory isn't returned.
   1779 	 */
   1780 	if ((cnp->cn_flags & LOCKPARENT) == 0 && searchdir != NULL) {
   1781 		vrele(searchdir);
   1782 		searchdir = NULL;
   1783 	}
   1784 
   1785 	ndp->ni_dvp = searchdir;
   1786 	ndp->ni_vp = foundobj;
   1787 	return 0;
   1788 }
   1789 
   1790 /*
   1791  * Do namei; wrapper layer that handles TRYEMULROOT.
   1792  */
   1793 static int
   1794 namei_tryemulroot(struct namei_state *state,
   1795 	 int neverfollow, int inhibitmagic, int isnfsd)
   1796 {
   1797 	int error;
   1798 
   1799 	struct nameidata *ndp = state->ndp;
   1800 	struct componentname *cnp = state->cnp;
   1801 	const char *savepath = NULL;
   1802 
   1803 	KASSERT(cnp == &ndp->ni_cnd);
   1804 
   1805 	if (cnp->cn_flags & TRYEMULROOT) {
   1806 		savepath = pathbuf_stringcopy_get(ndp->ni_pathbuf);
   1807 	}
   1808 
   1809     emul_retry:
   1810 	state->attempt_retry = 0;
   1811 
   1812 	error = namei_oneroot(state, neverfollow, inhibitmagic, isnfsd);
   1813 	if (error) {
   1814 		/*
   1815 		 * Once namei has started up, the existence of ni_erootdir
   1816 		 * tells us whether we're working from an emulation root.
   1817 		 * The TRYEMULROOT flag isn't necessarily authoritative.
   1818 		 */
   1819 		if (ndp->ni_erootdir != NULL && state->attempt_retry) {
   1820 			/* Retry the whole thing using the normal root */
   1821 			cnp->cn_flags &= ~TRYEMULROOT;
   1822 			state->attempt_retry = 0;
   1823 
   1824 			/* kinda gross */
   1825 			strcpy(ndp->ni_pathbuf->pb_path, savepath);
   1826 			pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
   1827 			savepath = NULL;
   1828 
   1829 			goto emul_retry;
   1830 		}
   1831 	}
   1832 	if (savepath != NULL) {
   1833 		pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
   1834 	}
   1835 	return error;
   1836 }
   1837 
   1838 /*
   1839  * External interface.
   1840  */
   1841 int
   1842 namei(struct nameidata *ndp)
   1843 {
   1844 	struct namei_state state;
   1845 	int error;
   1846 
   1847 	namei_init(&state, ndp);
   1848 	error = namei_tryemulroot(&state,
   1849 				  0/*!neverfollow*/, 0/*!inhibitmagic*/,
   1850 				  0/*isnfsd*/);
   1851 	namei_cleanup(&state);
   1852 
   1853 	if (error) {
   1854 		/* make sure no stray refs leak out */
   1855 		KASSERT(ndp->ni_dvp == NULL);
   1856 		KASSERT(ndp->ni_vp == NULL);
   1857 	}
   1858 
   1859 	return error;
   1860 }
   1861 
   1862 ////////////////////////////////////////////////////////////
   1863 
   1864 /*
   1865  * External interface used by nfsd. This is basically different from
   1866  * namei only in that it has the ability to pass in the "current
   1867  * directory", and uses an extra flag "neverfollow" for which there's
   1868  * no physical flag defined in namei.h. (There used to be a cut&paste
   1869  * copy of about half of namei in nfsd to allow these minor
   1870  * adjustments to exist.)
   1871  *
   1872  * XXX: the namei interface should be adjusted so nfsd can just use
   1873  * ordinary namei().
   1874  */
   1875 int
   1876 lookup_for_nfsd(struct nameidata *ndp, struct vnode *forcecwd, int neverfollow)
   1877 {
   1878 	struct namei_state state;
   1879 	int error;
   1880 
   1881 	KASSERT(ndp->ni_atdir == NULL);
   1882 	ndp->ni_atdir = forcecwd;
   1883 
   1884 	namei_init(&state, ndp);
   1885 	error = namei_tryemulroot(&state,
   1886 				  neverfollow, 1/*inhibitmagic*/, 1/*isnfsd*/);
   1887 	namei_cleanup(&state);
   1888 
   1889 	if (error) {
   1890 		/* make sure no stray refs leak out */
   1891 		KASSERT(ndp->ni_dvp == NULL);
   1892 		KASSERT(ndp->ni_vp == NULL);
   1893 	}
   1894 
   1895 	return error;
   1896 }
   1897 
   1898 /*
   1899  * A second external interface used by nfsd. This turns out to be a
   1900  * single lookup used by the WebNFS code (ha!) to get "index.html" or
   1901  * equivalent when asked for a directory. It should eventually evolve
   1902  * into some kind of namei_once() call; for the time being it's kind
   1903  * of a mess. XXX.
   1904  *
   1905  * dholland 20110109: I don't think it works, and I don't think it
   1906  * worked before I started hacking and slashing either, and I doubt
   1907  * anyone will ever notice.
   1908  */
   1909 
   1910 /*
   1911  * Internals. This calls lookup_once() after setting up the assorted
   1912  * pieces of state the way they ought to be.
   1913  */
   1914 static int
   1915 do_lookup_for_nfsd_index(struct namei_state *state)
   1916 {
   1917 	int error = 0;
   1918 
   1919 	struct componentname *cnp = state->cnp;
   1920 	struct nameidata *ndp = state->ndp;
   1921 	struct vnode *startdir;
   1922 	struct vnode *foundobj;
   1923 	bool startdir_locked;
   1924 	const char *cp;			/* pointer into pathname argument */
   1925 
   1926 	KASSERT(cnp == &ndp->ni_cnd);
   1927 
   1928 	startdir = state->ndp->ni_atdir;
   1929 
   1930 	cnp->cn_nameptr = ndp->ni_pnbuf;
   1931 	state->docache = 1;
   1932 	state->rdonly = cnp->cn_flags & RDONLY;
   1933 	ndp->ni_dvp = NULL;
   1934 
   1935 	cnp->cn_consume = 0;
   1936 	cnp->cn_namelen = namei_getcomponent(cnp->cn_nameptr);
   1937 	cp = cnp->cn_nameptr + cnp->cn_namelen;
   1938 	KASSERT(cnp->cn_namelen <= KERNEL_NAME_MAX);
   1939 	ndp->ni_pathlen -= cnp->cn_namelen;
   1940 	ndp->ni_next = cp;
   1941 	state->slashes = 0;
   1942 	cnp->cn_flags &= ~REQUIREDIR;
   1943 	cnp->cn_flags |= MAKEENTRY|ISLASTCN;
   1944 
   1945 	if (cnp->cn_namelen == 2 &&
   1946 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
   1947 		cnp->cn_flags |= ISDOTDOT;
   1948 	else
   1949 		cnp->cn_flags &= ~ISDOTDOT;
   1950 
   1951 	/*
   1952 	 * Because lookup_once can change the startdir, we need our
   1953 	 * own reference to it to avoid consuming the caller's.
   1954 	 */
   1955 	vref(startdir);
   1956 	error = lookup_once(state, startdir, &startdir, &foundobj,
   1957 	    &startdir_locked);
   1958 
   1959 	KASSERT((cnp->cn_flags & LOCKPARENT) == 0);
   1960 	if (startdir_locked) {
   1961 		VOP_UNLOCK(startdir);
   1962 		startdir_locked = false;
   1963 	}
   1964 
   1965 	/*
   1966 	 * If the vnode we found is mounted on, then cross the mount and get
   1967 	 * the root vnode in foundobj.  If this encounters an error, it will
   1968 	 * dispose of foundobj, but searchdir is untouched.
   1969 	 */
   1970 	if (error == 0 && foundobj != NULL &&
   1971 	    foundobj->v_type == VDIR &&
   1972 	    foundobj->v_mountedhere != NULL &&
   1973 	    (cnp->cn_flags & NOCROSSMOUNT) == 0) {
   1974 		error = lookup_crossmount(state, &startdir, &foundobj,
   1975 		    &startdir_locked);
   1976 	}
   1977 
   1978 	/* Now toss startdir and see if we have an error. */
   1979 	if (startdir != NULL)
   1980 		vrele(startdir);
   1981 	if (error)
   1982 		foundobj = NULL;
   1983 	else if (foundobj != NULL && (cnp->cn_flags & LOCKLEAF) != 0)
   1984 		vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
   1985 
   1986 	ndp->ni_vp = foundobj;
   1987 	return (error);
   1988 }
   1989 
   1990 /*
   1991  * External interface. The partitioning between this function and the
   1992  * above isn't very clear - the above function exists mostly so code
   1993  * that uses "state->" can be shuffled around without having to change
   1994  * it to "state.".
   1995  */
   1996 int
   1997 lookup_for_nfsd_index(struct nameidata *ndp, struct vnode *startdir)
   1998 {
   1999 	struct namei_state state;
   2000 	int error;
   2001 
   2002 	KASSERT(ndp->ni_atdir == NULL);
   2003 	ndp->ni_atdir = startdir;
   2004 
   2005 	/*
   2006 	 * Note: the name sent in here (is not|should not be) allowed
   2007 	 * to contain a slash.
   2008 	 */
   2009 	if (strlen(ndp->ni_pathbuf->pb_path) > KERNEL_NAME_MAX) {
   2010 		return ENAMETOOLONG;
   2011 	}
   2012 	if (strchr(ndp->ni_pathbuf->pb_path, '/')) {
   2013 		return EINVAL;
   2014 	}
   2015 
   2016 	ndp->ni_pathlen = strlen(ndp->ni_pathbuf->pb_path) + 1;
   2017 	ndp->ni_pnbuf = NULL;
   2018 	ndp->ni_cnd.cn_nameptr = NULL;
   2019 
   2020 	namei_init(&state, ndp);
   2021 	error = do_lookup_for_nfsd_index(&state);
   2022 	namei_cleanup(&state);
   2023 
   2024 	return error;
   2025 }
   2026 
   2027 ////////////////////////////////////////////////////////////
   2028 
   2029 /*
   2030  * Reacquire a path name component.
   2031  * dvp is locked on entry and exit.
   2032  * *vpp is locked on exit unless it's NULL.
   2033  */
   2034 int
   2035 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp, int dummy)
   2036 {
   2037 	int rdonly;			/* lookup read-only flag bit */
   2038 	int error = 0;
   2039 #ifdef DEBUG
   2040 	size_t newlen;			/* DEBUG: check name len */
   2041 	const char *cp;			/* DEBUG: check name ptr */
   2042 #endif /* DEBUG */
   2043 
   2044 	(void)dummy;
   2045 
   2046 	/*
   2047 	 * Setup: break out flag bits into variables.
   2048 	 */
   2049 	rdonly = cnp->cn_flags & RDONLY;
   2050 
   2051 	/*
   2052 	 * Search a new directory.
   2053 	 *
   2054 	 * The cn_hash value is for use by vfs_cache.
   2055 	 * The last component of the filename is left accessible via
   2056 	 * cnp->cn_nameptr for callers that need the name. Callers needing
   2057 	 * the name set the SAVENAME flag. When done, they assume
   2058 	 * responsibility for freeing the pathname buffer.
   2059 	 */
   2060 #ifdef DEBUG
   2061 #if 0
   2062 	cp = NULL;
   2063 	newhash = namei_hash(cnp->cn_nameptr, &cp);
   2064 	if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
   2065 		panic("relookup: bad hash");
   2066 #endif
   2067 	newlen = namei_getcomponent(cnp->cn_nameptr);
   2068 	if (cnp->cn_namelen != newlen)
   2069 		panic("relookup: bad len");
   2070 	cp = cnp->cn_nameptr + cnp->cn_namelen;
   2071 	while (*cp == '/')
   2072 		cp++;
   2073 	if (*cp != 0)
   2074 		panic("relookup: not last component");
   2075 #endif /* DEBUG */
   2076 
   2077 	/*
   2078 	 * Check for degenerate name (e.g. / or "")
   2079 	 * which is a way of talking about a directory,
   2080 	 * e.g. like "/." or ".".
   2081 	 */
   2082 	if (cnp->cn_nameptr[0] == '\0')
   2083 		panic("relookup: null name");
   2084 
   2085 	if (cnp->cn_flags & ISDOTDOT)
   2086 		panic("relookup: lookup on dot-dot");
   2087 
   2088 	/*
   2089 	 * We now have a segment name to search for, and a directory to search.
   2090 	 */
   2091 	*vpp = NULL;
   2092 	error = VOP_LOOKUP(dvp, vpp, cnp);
   2093 	if ((error) != 0) {
   2094 		KASSERTMSG((*vpp == NULL),
   2095 		    "leaf `%s' should be empty but is %p",
   2096 		    cnp->cn_nameptr, *vpp);
   2097 		if (error != EJUSTRETURN)
   2098 			goto bad;
   2099 	}
   2100 
   2101 	/*
   2102 	 * Check for symbolic link
   2103 	 */
   2104 	KASSERTMSG((*vpp == NULL || (*vpp)->v_type != VLNK ||
   2105 		(cnp->cn_flags & FOLLOW) == 0),
   2106 	    "relookup: symlink found");
   2107 
   2108 	/*
   2109 	 * Check for read-only lookups.
   2110 	 */
   2111 	if (rdonly && cnp->cn_nameiop != LOOKUP) {
   2112 		error = EROFS;
   2113 		if (*vpp) {
   2114 			vrele(*vpp);
   2115 		}
   2116 		goto bad;
   2117 	}
   2118 	/*
   2119 	 * Lock result.
   2120 	 */
   2121 	if (*vpp && *vpp != dvp) {
   2122 		error = vn_lock(*vpp, LK_EXCLUSIVE);
   2123 		if (error != 0) {
   2124 			vrele(*vpp);
   2125 			goto bad;
   2126 		}
   2127 	}
   2128 	return (0);
   2129 
   2130 bad:
   2131 	*vpp = NULL;
   2132 	return (error);
   2133 }
   2134 
   2135 /*
   2136  * namei_simple - simple forms of namei.
   2137  *
   2138  * These are wrappers to allow the simple case callers of namei to be
   2139  * left alone while everything else changes under them.
   2140  */
   2141 
   2142 /* Flags */
   2143 struct namei_simple_flags_type {
   2144 	int dummy;
   2145 };
   2146 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
   2147 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
   2148 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
   2149 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
   2150 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
   2151 
   2152 static
   2153 int
   2154 namei_simple_convert_flags(namei_simple_flags_t sflags)
   2155 {
   2156 	if (sflags == NSM_NOFOLLOW_NOEMULROOT)
   2157 		return NOFOLLOW | 0;
   2158 	if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
   2159 		return NOFOLLOW | TRYEMULROOT;
   2160 	if (sflags == NSM_FOLLOW_NOEMULROOT)
   2161 		return FOLLOW | 0;
   2162 	if (sflags == NSM_FOLLOW_TRYEMULROOT)
   2163 		return FOLLOW | TRYEMULROOT;
   2164 	panic("namei_simple_convert_flags: bogus sflags\n");
   2165 	return 0;
   2166 }
   2167 
   2168 int
   2169 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
   2170 	struct vnode **vp_ret)
   2171 {
   2172 	return nameiat_simple_kernel(NULL, path, sflags, vp_ret);
   2173 }
   2174 
   2175 int
   2176 nameiat_simple_kernel(struct vnode *dvp, const char *path,
   2177 	namei_simple_flags_t sflags, struct vnode **vp_ret)
   2178 {
   2179 	struct nameidata nd;
   2180 	struct pathbuf *pb;
   2181 	int err;
   2182 
   2183 	pb = pathbuf_create(path);
   2184 	if (pb == NULL) {
   2185 		return ENOMEM;
   2186 	}
   2187 
   2188 	NDINIT(&nd,
   2189 		LOOKUP,
   2190 		namei_simple_convert_flags(sflags),
   2191 		pb);
   2192 
   2193 	if (dvp != NULL)
   2194 		NDAT(&nd, dvp);
   2195 
   2196 	err = namei(&nd);
   2197 	if (err != 0) {
   2198 		pathbuf_destroy(pb);
   2199 		return err;
   2200 	}
   2201 	*vp_ret = nd.ni_vp;
   2202 	pathbuf_destroy(pb);
   2203 	return 0;
   2204 }
   2205 
   2206 int
   2207 namei_simple_user(const char *path, namei_simple_flags_t sflags,
   2208 	struct vnode **vp_ret)
   2209 {
   2210 	return nameiat_simple_user(NULL, path, sflags, vp_ret);
   2211 }
   2212 
   2213 int
   2214 nameiat_simple_user(struct vnode *dvp, const char *path,
   2215 	namei_simple_flags_t sflags, struct vnode **vp_ret)
   2216 {
   2217 	struct pathbuf *pb;
   2218 	struct nameidata nd;
   2219 	int err;
   2220 
   2221 	err = pathbuf_copyin(path, &pb);
   2222 	if (err) {
   2223 		return err;
   2224 	}
   2225 
   2226 	NDINIT(&nd,
   2227 		LOOKUP,
   2228 		namei_simple_convert_flags(sflags),
   2229 		pb);
   2230 
   2231 	if (dvp != NULL)
   2232 		NDAT(&nd, dvp);
   2233 
   2234 	err = namei(&nd);
   2235 	if (err != 0) {
   2236 		pathbuf_destroy(pb);
   2237 		return err;
   2238 	}
   2239 	*vp_ret = nd.ni_vp;
   2240 	pathbuf_destroy(pb);
   2241 	return 0;
   2242 }
   2243