xref: /netbsd-src/sys/kern/vfs_lookup.c (revision 5b84b3983f71fd20a534cfa5d1556623a8aaa717)
1 /*	$NetBSD: vfs_lookup.c,v 1.63 2005/07/06 18:53:00 thorpej 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.63 2005/07/06 18:53:00 thorpej Exp $");
41 
42 #include "opt_ktrace.h"
43 #include "opt_systrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/syslimits.h>
49 #include <sys/time.h>
50 #include <sys/namei.h>
51 #include <sys/vnode.h>
52 #include <sys/mount.h>
53 #include <sys/errno.h>
54 #include <sys/filedesc.h>
55 #include <sys/hash.h>
56 #include <sys/malloc.h>
57 #include <sys/proc.h>
58 #include <sys/syslog.h>
59 
60 #ifdef KTRACE
61 #include <sys/ktrace.h>
62 #endif
63 #ifdef SYSTRACE
64 #include <sys/systrace.h>
65 #endif
66 
67 struct pool pnbuf_pool;		/* pathname buffer pool */
68 struct pool_cache pnbuf_cache;	/* pathname buffer cache */
69 
70 /*
71  * Substitute replacement text for 'magic' strings in symlinks.
72  * Returns 0 if successful, and returns non-zero if an error
73  * occurs.  (Currently, the only possible error is running out
74  * of temporary pathname space.)
75  *
76  * Looks for "@<string>" and "@<string>/", where <string> is a
77  * recognized 'magic' string.  Replaces the "@<string>" with the
78  * appropriate replacement text.  (Note that in some cases the
79  * replacement text may have zero length.)
80  *
81  * This would have been table driven, but the variance in
82  * replacement strings (and replacement string lengths) made
83  * that impractical.
84  */
85 #define	VNL(x)							\
86 	(sizeof(x) - 1)
87 
88 #define	VO	'{'
89 #define	VC	'}'
90 
91 #define	MATCH(str)						\
92 	((termchar == '/' && i + VNL(str) == *len) ||		\
93 	 (i + VNL(str) < *len &&				\
94 	  cp[i + VNL(str)] == termchar)) &&			\
95 	!strncmp((str), &cp[i], VNL(str))
96 
97 #define	SUBSTITUTE(m, s, sl)					\
98 	if ((newlen + (sl)) > MAXPATHLEN)			\
99 		return (1);					\
100 	i += VNL(m);						\
101 	if (termchar != '/')					\
102 		i++;						\
103 	memcpy(&tmp[newlen], (s), (sl));			\
104 	newlen += (sl);						\
105 	change = 1;						\
106 	termchar = '/';
107 
108 static int
109 symlink_magic(struct proc *p, char *cp, int *len)
110 {
111 	char tmp[MAXPATHLEN];
112 	int change, i, newlen;
113 	int termchar = '/';
114 
115 	for (change = i = newlen = 0; i < *len; ) {
116 		if (cp[i] != '@') {
117 			tmp[newlen++] = cp[i++];
118 			continue;
119 		}
120 
121 		i++;
122 
123 		/* Check for @{var} syntax. */
124 		if (cp[i] == VO) {
125 			termchar = VC;
126 			i++;
127 		}
128 
129 		/*
130 		 * The following checks should be ordered according
131 		 * to frequency of use.
132 		 */
133 		if (MATCH("machine_arch")) {
134 			SUBSTITUTE("machine_arch", MACHINE_ARCH,
135 			    sizeof(MACHINE_ARCH) - 1);
136 		} else if (MATCH("machine")) {
137 			SUBSTITUTE("machine", MACHINE,
138 			    sizeof(MACHINE) - 1);
139 		} else if (MATCH("hostname")) {
140 			SUBSTITUTE("hostname", hostname,
141 			    hostnamelen);
142 		} else if (MATCH("osrelease")) {
143 			SUBSTITUTE("osrelease", osrelease,
144 			    strlen(osrelease));
145 		} else if (MATCH("emul")) {
146 			SUBSTITUTE("emul", p->p_emul->e_name,
147 			    strlen(p->p_emul->e_name));
148 		} else if (MATCH("kernel_ident")) {
149 			SUBSTITUTE("kernel_ident", kernel_ident,
150 			    strlen(kernel_ident));
151 		} else if (MATCH("domainname")) {
152 			SUBSTITUTE("domainname", domainname,
153 			    domainnamelen);
154 		} else if (MATCH("ostype")) {
155 			SUBSTITUTE("ostype", ostype,
156 			    strlen(ostype));
157 		} else {
158 			tmp[newlen++] = '@';
159 			if (termchar == VC)
160 				tmp[newlen++] = VO;
161 		}
162 	}
163 
164 	if (! change)
165 		return (0);
166 
167 	memcpy(cp, tmp, newlen);
168 	*len = newlen;
169 
170 	return (0);
171 }
172 
173 #undef VNL
174 #undef VO
175 #undef VC
176 #undef MATCH
177 #undef SUBSTITUTE
178 
179 /*
180  * Convert a pathname into a pointer to a locked inode.
181  *
182  * The FOLLOW flag is set when symbolic links are to be followed
183  * when they occur at the end of the name translation process.
184  * Symbolic links are always followed for all other pathname
185  * components other than the last.
186  *
187  * The segflg defines whether the name is to be copied from user
188  * space or kernel space.
189  *
190  * Overall outline of namei:
191  *
192  *	copy in name
193  *	get starting directory
194  *	while (!done && !error) {
195  *		call lookup to search path.
196  *		if symbolic link, massage name in buffer and continue
197  *	}
198  */
199 int
200 namei(struct nameidata *ndp)
201 {
202 	struct cwdinfo *cwdi;		/* pointer to cwd state */
203 	char *cp;			/* pointer into pathname argument */
204 	struct vnode *dp;		/* the directory we are searching */
205 	struct iovec aiov;		/* uio for reading symbolic links */
206 	struct uio auio;
207 	int error, linklen;
208 	struct componentname *cnp = &ndp->ni_cnd;
209 
210 #ifdef DIAGNOSTIC
211 	if (!cnp->cn_cred || !cnp->cn_proc)
212 		panic("namei: bad cred/proc");
213 	if (cnp->cn_nameiop & (~OPMASK))
214 		panic("namei: nameiop contaminated with flags");
215 	if (cnp->cn_flags & OPMASK)
216 		panic("namei: flags contaminated with nameiops");
217 #endif
218 	cwdi = cnp->cn_proc->p_cwdi;
219 
220 	/*
221 	 * Get a buffer for the name to be translated, and copy the
222 	 * name into the buffer.
223 	 */
224 	if ((cnp->cn_flags & HASBUF) == 0)
225 		cnp->cn_pnbuf = PNBUF_GET();
226 	if (ndp->ni_segflg == UIO_SYSSPACE)
227 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf,
228 			    MAXPATHLEN, &ndp->ni_pathlen);
229 	else
230 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
231 			    MAXPATHLEN, &ndp->ni_pathlen);
232 
233 	/*
234 	 * POSIX.1 requirement: "" is not a valid file name.
235 	 */
236 	if (!error && ndp->ni_pathlen == 1)
237 		error = ENOENT;
238 
239 	if (error) {
240 		PNBUF_PUT(cnp->cn_pnbuf);
241 		ndp->ni_vp = NULL;
242 		return (error);
243 	}
244 	ndp->ni_loopcnt = 0;
245 
246 #ifdef KTRACE
247 	if (KTRPOINT(cnp->cn_proc, KTR_NAMEI))
248 		ktrnamei(cnp->cn_proc, cnp->cn_pnbuf);
249 #endif
250 #ifdef SYSTRACE
251 	if (ISSET(cnp->cn_proc->p_flag, P_SYSTRACE))
252 		systrace_namei(ndp);
253 #endif
254 
255 	/*
256 	 * Get starting point for the translation.
257 	 */
258 	if ((ndp->ni_rootdir = cwdi->cwdi_rdir) == NULL)
259 		ndp->ni_rootdir = rootvnode;
260 	/*
261 	 * Check if starting from root directory or current directory.
262 	 */
263 	if (cnp->cn_pnbuf[0] == '/') {
264 		dp = ndp->ni_rootdir;
265 		VREF(dp);
266 	} else {
267 		dp = cwdi->cwdi_cdir;
268 		VREF(dp);
269 	}
270 	for (;;) {
271 		if (!dp->v_mount)
272 		{
273 			/* Give up if the directory is no longer mounted */
274 			PNBUF_PUT(cnp->cn_pnbuf);
275 			return (ENOENT);
276 		}
277 		cnp->cn_nameptr = cnp->cn_pnbuf;
278 		ndp->ni_startdir = dp;
279 		if ((error = lookup(ndp)) != 0) {
280 			PNBUF_PUT(cnp->cn_pnbuf);
281 			return (error);
282 		}
283 		/*
284 		 * Check for symbolic link
285 		 */
286 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
287 			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
288 				PNBUF_PUT(cnp->cn_pnbuf);
289 			else
290 				cnp->cn_flags |= HASBUF;
291 			return (0);
292 		}
293 		if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN))
294 			VOP_UNLOCK(ndp->ni_dvp, 0);
295 		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
296 			error = ELOOP;
297 			break;
298 		}
299 		if (ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
300 			error = VOP_ACCESS(ndp->ni_vp, VEXEC, cnp->cn_cred,
301 			    cnp->cn_proc);
302 			if (error != 0)
303 				break;
304 		}
305 		if (ndp->ni_pathlen > 1)
306 			cp = PNBUF_GET();
307 		else
308 			cp = cnp->cn_pnbuf;
309 		aiov.iov_base = cp;
310 		aiov.iov_len = MAXPATHLEN;
311 		auio.uio_iov = &aiov;
312 		auio.uio_iovcnt = 1;
313 		auio.uio_offset = 0;
314 		auio.uio_rw = UIO_READ;
315 		auio.uio_segflg = UIO_SYSSPACE;
316 		auio.uio_procp = NULL;
317 		auio.uio_resid = MAXPATHLEN;
318 		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
319 		if (error) {
320 		badlink:
321 			if (ndp->ni_pathlen > 1)
322 				PNBUF_PUT(cp);
323 			break;
324 		}
325 		linklen = MAXPATHLEN - auio.uio_resid;
326 		if (linklen == 0) {
327 			error = ENOENT;
328 			goto badlink;
329 		}
330 		/*
331 		 * Do symlink substitution, if appropriate, and
332 		 * check length for potential overflow.
333 		 */
334 		if (((ndp->ni_vp->v_mount->mnt_flag & MNT_MAGICLINKS) &&
335 		     symlink_magic(cnp->cn_proc, cp, &linklen)) ||
336 		    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
337 			error = ENAMETOOLONG;
338 			goto badlink;
339 		}
340 		if (ndp->ni_pathlen > 1) {
341 			memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
342 			PNBUF_PUT(cnp->cn_pnbuf);
343 			cnp->cn_pnbuf = cp;
344 		} else
345 			cnp->cn_pnbuf[linklen] = '\0';
346 		ndp->ni_pathlen += linklen;
347 		vput(ndp->ni_vp);
348 		dp = ndp->ni_dvp;
349 		/*
350 		 * Check if root directory should replace current directory.
351 		 */
352 		if (cnp->cn_pnbuf[0] == '/') {
353 			vrele(dp);
354 			dp = ndp->ni_rootdir;
355 			VREF(dp);
356 		}
357 	}
358 	PNBUF_PUT(cnp->cn_pnbuf);
359 	vrele(ndp->ni_dvp);
360 	vput(ndp->ni_vp);
361 	ndp->ni_vp = NULL;
362 	return (error);
363 }
364 
365 /*
366  * Determine the namei hash (for cn_hash) for name.
367  * If *ep != NULL, hash from name to ep-1.
368  * If *ep == NULL, hash from name until the first NUL or '/', and
369  * return the location of this termination character in *ep.
370  *
371  * This function returns an equivalent hash to the MI hash32_strn().
372  * The latter isn't used because in the *ep == NULL case, determining
373  * the length of the string to the first NUL or `/' and then calling
374  * hash32_strn() involves unnecessary double-handling of the data.
375  */
376 uint32_t
377 namei_hash(const char *name, const char **ep)
378 {
379 	uint32_t	hash;
380 
381 	hash = HASH32_STR_INIT;
382 	if (*ep != NULL) {
383 		for (; name < *ep; name++)
384 			hash = hash * 33 + *(const uint8_t *)name;
385 	} else {
386 		for (; *name != '\0' && *name != '/'; name++)
387 			hash = hash * 33 + *(const uint8_t *)name;
388 		*ep = name;
389 	}
390 	return (hash + (hash >> 5));
391 }
392 
393 /*
394  * Search a pathname.
395  * This is a very central and rather complicated routine.
396  *
397  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
398  * The starting directory is taken from ni_startdir. The pathname is
399  * descended until done, or a symbolic link is encountered. The variable
400  * ni_more is clear if the path is completed; it is set to one if a
401  * symbolic link needing interpretation is encountered.
402  *
403  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
404  * whether the name is to be looked up, created, renamed, or deleted.
405  * When CREATE, RENAME, or DELETE is specified, information usable in
406  * creating, renaming, or deleting a directory entry may be calculated.
407  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
408  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
409  * returned unlocked. Otherwise the parent directory is not returned. If
410  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
411  * the target is returned locked, otherwise it is returned unlocked.
412  * When creating or renaming and LOCKPARENT is specified, the target may not
413  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
414  *
415  * Overall outline of lookup:
416  *
417  * dirloop:
418  *	identify next component of name at ndp->ni_ptr
419  *	handle degenerate case where name is null string
420  *	if .. and crossing mount points and on mounted filesys, find parent
421  *	call VOP_LOOKUP routine for next component name
422  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
423  *	    component vnode returned in ni_vp (if it exists), locked.
424  *	if result vnode is mounted on and crossing mount points,
425  *	    find mounted on vnode
426  *	if more components of name, do next level at dirloop
427  *	return the answer in ni_vp, locked if LOCKLEAF set
428  *	    if LOCKPARENT set, return locked parent in ni_dvp
429  *	    if WANTPARENT set, return unlocked parent in ni_dvp
430  */
431 int
432 lookup(struct nameidata *ndp)
433 {
434 	const char *cp;			/* pointer into pathname argument */
435 	struct vnode *dp = 0;		/* the directory we are searching */
436 	struct vnode *tdp;		/* saved dp */
437 	struct mount *mp;		/* mount table entry */
438 	int docache;			/* == 0 do not cache last component */
439 	int wantparent;			/* 1 => wantparent or lockparent flag */
440 	int rdonly;			/* lookup read-only flag bit */
441 	int error = 0;
442 	int slashes;
443 	int dpunlocked = 0;		/* dp has already been unlocked */
444 	struct componentname *cnp = &ndp->ni_cnd;
445 
446 	/*
447 	 * Setup: break out flag bits into variables.
448 	 */
449 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
450 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
451 	if (cnp->cn_nameiop == DELETE ||
452 	    (wantparent && cnp->cn_nameiop != CREATE))
453 		docache = 0;
454 	rdonly = cnp->cn_flags & RDONLY;
455 	ndp->ni_dvp = NULL;
456 	cnp->cn_flags &= ~ISSYMLINK;
457 	dp = ndp->ni_startdir;
458 	ndp->ni_startdir = NULLVP;
459 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
460 
461 	/*
462 	 * If we have a leading string of slashes, remove them, and just make
463 	 * sure the current node is a directory.
464 	 */
465 	cp = cnp->cn_nameptr;
466 	if (*cp == '/') {
467 		do {
468 			cp++;
469 		} while (*cp == '/');
470 		ndp->ni_pathlen -= cp - cnp->cn_nameptr;
471 		cnp->cn_nameptr = cp;
472 
473 		if (dp->v_type != VDIR) {
474 			error = ENOTDIR;
475 			goto bad;
476 		}
477 
478 		/*
479 		 * If we've exhausted the path name, then just return the
480 		 * current node.  If the caller requested the parent node (i.e.
481 		 * it's a CREATE, DELETE, or RENAME), and we don't have one
482 		 * (because this is the root directory), then we must fail.
483 		 */
484 		if (cnp->cn_nameptr[0] == '\0') {
485 			if (ndp->ni_dvp == NULL && wantparent) {
486 				error = EISDIR;
487 				goto bad;
488 			}
489 			ndp->ni_vp = dp;
490 			cnp->cn_flags |= ISLASTCN;
491 			goto terminal;
492 		}
493 	}
494 
495 dirloop:
496 	/*
497 	 * Search a new directory.
498 	 *
499 	 * The cn_hash value is for use by vfs_cache.
500 	 * The last component of the filename is left accessible via
501 	 * cnp->cn_nameptr for callers that need the name. Callers needing
502 	 * the name set the SAVENAME flag. When done, they assume
503 	 * responsibility for freeing the pathname buffer.
504 	 */
505 	cnp->cn_consume = 0;
506 	cp = NULL;
507 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
508 	cnp->cn_namelen = cp - cnp->cn_nameptr;
509 	if (cnp->cn_namelen > NAME_MAX) {
510 		error = ENAMETOOLONG;
511 		goto bad;
512 	}
513 #ifdef NAMEI_DIAGNOSTIC
514 	{ char c = *cp;
515 	*(char *)cp = '\0';
516 	printf("{%s}: ", cnp->cn_nameptr);
517 	*(char *)cp = c; }
518 #endif /* NAMEI_DIAGNOSTIC */
519 	ndp->ni_pathlen -= cnp->cn_namelen;
520 	ndp->ni_next = cp;
521 	/*
522 	 * If this component is followed by a slash, then move the pointer to
523 	 * the next component forward, and remember that this component must be
524 	 * a directory.
525 	 */
526 	if (*cp == '/') {
527 		do {
528 			cp++;
529 		} while (*cp == '/');
530 		slashes = cp - ndp->ni_next;
531 		ndp->ni_pathlen -= slashes;
532 		ndp->ni_next = cp;
533 		cnp->cn_flags |= REQUIREDIR;
534 	} else {
535 		slashes = 0;
536 		cnp->cn_flags &= ~REQUIREDIR;
537 	}
538 	/*
539 	 * We do special processing on the last component, whether or not it's
540 	 * a directory.  Cache all intervening lookups, but not the final one.
541 	 */
542 	if (*cp == '\0') {
543 		if (docache)
544 			cnp->cn_flags |= MAKEENTRY;
545 		else
546 			cnp->cn_flags &= ~MAKEENTRY;
547 		cnp->cn_flags |= ISLASTCN;
548 	} else {
549 		cnp->cn_flags |= MAKEENTRY;
550 		cnp->cn_flags &= ~ISLASTCN;
551 	}
552 	if (cnp->cn_namelen == 2 &&
553 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
554 		cnp->cn_flags |= ISDOTDOT;
555 	else
556 		cnp->cn_flags &= ~ISDOTDOT;
557 
558 	/*
559 	 * Handle "..": two special cases.
560 	 * 1. If at root directory (e.g. after chroot)
561 	 *    or at absolute root directory
562 	 *    then ignore it so can't get out.
563 	 * 1a. If we have somehow gotten out of a jail, warn
564 	 *    and also ignore it so we can't get farther out.
565 	 * 2. If this vnode is the root of a mounted
566 	 *    filesystem, then replace it with the
567 	 *    vnode which was mounted on so we take the
568 	 *    .. in the other file system.
569 	 */
570 	if (cnp->cn_flags & ISDOTDOT) {
571 		for (;;) {
572 			if (dp == ndp->ni_rootdir || dp == rootvnode) {
573 				ndp->ni_dvp = dp;
574 				ndp->ni_vp = dp;
575 				VREF(dp);
576 				goto nextname;
577 			}
578 			if (ndp->ni_rootdir != rootvnode) {
579 				int retval;
580 				VOP_UNLOCK(dp, 0);
581 				retval = vn_isunder(dp, ndp->ni_rootdir,
582 				    cnp->cn_proc);
583 				vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
584 				if (!retval) {
585 				    /* Oops! We got out of jail! */
586 				    log(LOG_WARNING,
587 					"chrooted pid %d uid %d (%s) "
588 					"detected outside of its chroot\n",
589 					cnp->cn_proc->p_pid,
590 					cnp->cn_proc->p_ucred->cr_uid,
591 					cnp->cn_proc->p_comm);
592 				    /* Put us at the jail root. */
593 				    vput(dp);
594 				    dp = ndp->ni_rootdir;
595 				    ndp->ni_dvp = dp;
596 				    ndp->ni_vp = dp;
597 				    VREF(dp);
598 				    VREF(dp);
599 				    vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
600 				    goto nextname;
601 				}
602 			}
603 			if ((dp->v_flag & VROOT) == 0 ||
604 			    (cnp->cn_flags & NOCROSSMOUNT))
605 				break;
606 			tdp = dp;
607 			dp = dp->v_mount->mnt_vnodecovered;
608 			vput(tdp);
609 			VREF(dp);
610 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
611 		}
612 	}
613 
614 	/*
615 	 * We now have a segment name to search for, and a directory to search.
616 	 */
617 unionlookup:
618 	ndp->ni_dvp = dp;
619 	ndp->ni_vp = NULL;
620 	cnp->cn_flags &= ~PDIRUNLOCK;
621 	if ((error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp)) != 0) {
622 #ifdef DIAGNOSTIC
623 		if (ndp->ni_vp != NULL)
624 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
625 #endif /* DIAGNOSTIC */
626 #ifdef NAMEI_DIAGNOSTIC
627 		printf("not found\n");
628 #endif /* NAMEI_DIAGNOSTIC */
629 		if ((error == ENOENT) &&
630 		    (dp->v_flag & VROOT) &&
631 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
632 			tdp = dp;
633 			dp = dp->v_mount->mnt_vnodecovered;
634 			if (cnp->cn_flags & PDIRUNLOCK)
635 				vrele(tdp);
636 			else
637 				vput(tdp);
638 			VREF(dp);
639 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
640 			goto unionlookup;
641 		}
642 
643 		if (cnp->cn_flags & PDIRUNLOCK)
644 			dpunlocked = 1;
645 
646 		if (error != EJUSTRETURN)
647 			goto bad;
648 		/*
649 		 * If this was not the last component, or there were trailing
650 		 * slashes, and we are not going to create a directory,
651 		 * then the name must exist.
652 		 */
653 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
654 			error = ENOENT;
655 			goto bad;
656 		}
657 		/*
658 		 * If creating and at end of pathname, then can consider
659 		 * allowing file to be created.
660 		 */
661 		if (rdonly) {
662 			error = EROFS;
663 			goto bad;
664 		}
665 		/*
666 		 * We return with ni_vp NULL to indicate that the entry
667 		 * doesn't currently exist, leaving a pointer to the
668 		 * (possibly locked) directory inode in ndp->ni_dvp.
669 		 */
670 		if (cnp->cn_flags & SAVESTART) {
671 			ndp->ni_startdir = ndp->ni_dvp;
672 			VREF(ndp->ni_startdir);
673 		}
674 		return (0);
675 	}
676 #ifdef NAMEI_DIAGNOSTIC
677 	printf("found\n");
678 #endif /* NAMEI_DIAGNOSTIC */
679 
680 	/*
681 	 * Take into account any additional components consumed by the
682 	 * underlying filesystem.  This will include any trailing slashes after
683 	 * the last component consumed.
684 	 */
685 	if (cnp->cn_consume > 0) {
686 		ndp->ni_pathlen -= cnp->cn_consume - slashes;
687 		ndp->ni_next += cnp->cn_consume - slashes;
688 		cnp->cn_consume = 0;
689 		if (ndp->ni_next[0] == '\0')
690 			cnp->cn_flags |= ISLASTCN;
691 	}
692 
693 	dp = ndp->ni_vp;
694 	/*
695 	 * Check to see if the vnode has been mounted on;
696 	 * if so find the root of the mounted file system.
697 	 */
698 	while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
699 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
700 		if (vfs_busy(mp, 0, 0))
701 			continue;
702 		VOP_UNLOCK(dp, 0);
703 		error = VFS_ROOT(mp, &tdp);
704 		vfs_unbusy(mp);
705 		if (error) {
706 			dpunlocked = 1;
707 			goto bad2;
708 		}
709 		vrele(dp);
710 		ndp->ni_vp = dp = tdp;
711 	}
712 
713 	/*
714 	 * Check for symbolic link.  Back up over any slashes that we skipped,
715 	 * as we will need them again.
716 	 */
717 	if ((dp->v_type == VLNK) && (cnp->cn_flags & (FOLLOW|REQUIREDIR))) {
718 		ndp->ni_pathlen += slashes;
719 		ndp->ni_next -= slashes;
720 		cnp->cn_flags |= ISSYMLINK;
721 		return (0);
722 	}
723 
724 	/*
725 	 * Check for directory, if the component was followed by a series of
726 	 * slashes.
727 	 */
728 	if ((dp->v_type != VDIR) && (cnp->cn_flags & REQUIREDIR)) {
729 		error = ENOTDIR;
730 		goto bad2;
731 	}
732 
733 nextname:
734 	/*
735 	 * Not a symbolic link.  If this was not the last component, then
736 	 * continue at the next component, else return.
737 	 */
738 	if (!(cnp->cn_flags & ISLASTCN)) {
739 		cnp->cn_nameptr = ndp->ni_next;
740 		vrele(ndp->ni_dvp);
741 		goto dirloop;
742 	}
743 
744 terminal:
745 	/*
746 	 * Disallow directory write attempts on read-only file systems.
747 	 */
748 	if (rdonly &&
749 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
750 		/*
751 		 * Disallow directory write attempts on read-only
752 		 * file systems.
753 		 */
754 		error = EROFS;
755 		goto bad2;
756 	}
757 	if (ndp->ni_dvp != NULL) {
758 		if (cnp->cn_flags & SAVESTART) {
759 			ndp->ni_startdir = ndp->ni_dvp;
760 			VREF(ndp->ni_startdir);
761 		}
762 		if (!wantparent)
763 			vrele(ndp->ni_dvp);
764 	}
765 	if ((cnp->cn_flags & LOCKLEAF) == 0)
766 		VOP_UNLOCK(dp, 0);
767 	return (0);
768 
769 bad2:
770 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
771 			((cnp->cn_flags & PDIRUNLOCK) == 0))
772 		VOP_UNLOCK(ndp->ni_dvp, 0);
773 	vrele(ndp->ni_dvp);
774 bad:
775 	if (dpunlocked)
776 		vrele(dp);
777 	else
778 		vput(dp);
779 	ndp->ni_vp = NULL;
780 	return (error);
781 }
782 
783 /*
784  * Reacquire a path name component.
785  */
786 int
787 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
788 {
789 	struct vnode *dp = 0;		/* the directory we are searching */
790 	int wantparent;			/* 1 => wantparent or lockparent flag */
791 	int rdonly;			/* lookup read-only flag bit */
792 	int error = 0;
793 #ifdef DEBUG
794 	u_long newhash;			/* DEBUG: check name hash */
795 	const char *cp;			/* DEBUG: check name ptr/len */
796 #endif /* DEBUG */
797 
798 	/*
799 	 * Setup: break out flag bits into variables.
800 	 */
801 	wantparent = cnp->cn_flags & (LOCKPARENT|WANTPARENT);
802 	rdonly = cnp->cn_flags & RDONLY;
803 	cnp->cn_flags &= ~ISSYMLINK;
804 	dp = dvp;
805 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
806 
807 /* dirloop: */
808 	/*
809 	 * Search a new directory.
810 	 *
811 	 * The cn_hash value is for use by vfs_cache.
812 	 * The last component of the filename is left accessible via
813 	 * cnp->cn_nameptr for callers that need the name. Callers needing
814 	 * the name set the SAVENAME flag. When done, they assume
815 	 * responsibility for freeing the pathname buffer.
816 	 */
817 #ifdef DEBUG
818 	cp = NULL;
819 	newhash = namei_hash(cnp->cn_nameptr, &cp);
820 	if (newhash != cnp->cn_hash)
821 		panic("relookup: bad hash");
822 	if (cnp->cn_namelen != cp - cnp->cn_nameptr)
823 		panic("relookup: bad len");
824 	while (*cp == '/')
825 		cp++;
826 	if (*cp != 0)
827 		panic("relookup: not last component");
828 #endif /* DEBUG */
829 #ifdef NAMEI_DIAGNOSTIC
830 	printf("{%s}: ", cnp->cn_nameptr);
831 #endif /* NAMEI_DIAGNOSTIC */
832 
833 	/*
834 	 * Check for degenerate name (e.g. / or "")
835 	 * which is a way of talking about a directory,
836 	 * e.g. like "/." or ".".
837 	 */
838 	if (cnp->cn_nameptr[0] == '\0')
839 		panic("relookup: null name");
840 
841 	if (cnp->cn_flags & ISDOTDOT)
842 		panic("relookup: lookup on dot-dot");
843 
844 	/*
845 	 * We now have a segment name to search for, and a directory to search.
846 	 */
847 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
848 #ifdef DIAGNOSTIC
849 		if (*vpp != NULL)
850 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
851 #endif
852 		if (error != EJUSTRETURN)
853 			goto bad;
854 		/*
855 		 * If creating and at end of pathname, then can consider
856 		 * allowing file to be created.
857 		 */
858 		if (rdonly) {
859 			error = EROFS;
860 			goto bad;
861 		}
862 		/* ASSERT(dvp == ndp->ni_startdir) */
863 		if (cnp->cn_flags & SAVESTART)
864 			VREF(dvp);
865 		/*
866 		 * We return with ni_vp NULL to indicate that the entry
867 		 * doesn't currently exist, leaving a pointer to the
868 		 * (possibly locked) directory inode in ndp->ni_dvp.
869 		 */
870 		return (0);
871 	}
872 	dp = *vpp;
873 
874 #ifdef DIAGNOSTIC
875 	/*
876 	 * Check for symbolic link
877 	 */
878 	if (dp->v_type == VLNK && (cnp->cn_flags & FOLLOW))
879 		panic("relookup: symlink found");
880 #endif
881 
882 	/*
883 	 * Check for read-only file systems.
884 	 */
885 	if (rdonly &&
886 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
887 		error = EROFS;
888 		goto bad2;
889 	}
890 	/* ASSERT(dvp == ndp->ni_startdir) */
891 	if (cnp->cn_flags & SAVESTART)
892 		VREF(dvp);
893 	if (!wantparent)
894 		vrele(dvp);
895 	if ((cnp->cn_flags & LOCKLEAF) == 0)
896 		VOP_UNLOCK(dp, 0);
897 	return (0);
898 
899 bad2:
900 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN))
901 		VOP_UNLOCK(dvp, 0);
902 	vrele(dvp);
903 bad:
904 	vput(dp);
905 	*vpp = NULL;
906 	return (error);
907 }
908