xref: /xnu-12377.1.9/bsd/vfs/vfs_lookup.c (revision f6217f891ac0bb64f3d375211650a4c1ff8ca1ea)
1 /*
2  * Copyright (c) 2000-2015 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30  * Copyright (c) 1982, 1986, 1989, 1993
31  *	The Regents of the University of California.  All rights reserved.
32  * (c) UNIX System Laboratories, Inc.
33  * All or some portions of this file are derived from material licensed
34  * to the University of California by American Telephone and Telegraph
35  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36  * the permission of UNIX System Laboratories, Inc.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *	This product includes software developed by the University of
49  *	California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)vfs_lookup.c	8.10 (Berkeley) 5/27/95
67  */
68 /*
69  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
70  * support for mandatory and extensible security protections.  This notice
71  * is included in support of clause 2.2 (b) of the Apple Public License,
72  * Version 2.0.
73  */
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/syslimits.h>
78 #include <sys/time.h>
79 #include <sys/namei.h>
80 #include <sys/vm.h>
81 #include <sys/vnode_internal.h>
82 #include <sys/mount_internal.h>
83 #include <sys/errno.h>
84 #include <kern/kalloc.h>
85 #include <sys/filedesc.h>
86 #include <sys/proc_internal.h>
87 #include <sys/kdebug.h>
88 #include <sys/unistd.h>         /* For _PC_NAME_MAX */
89 #include <sys/uio_internal.h>
90 #include <sys/kauth.h>
91 #include <kern/zalloc.h>
92 #include <security/audit/audit.h>
93 #if CONFIG_MACF
94 #include <security/mac_framework.h>
95 #endif
96 #include <os/atomic_private.h>
97 
98 #include <sys/paths.h>
99 
100 #if NAMEDRSRCFORK
101 #include <sys/xattr.h>
102 #endif
103 /*
104  * The minimum volfs-style pathname is 9.
105  * Example:  "/.vol/1/2"
106  */
107 #define VOLFS_MIN_PATH_LEN  9
108 
109 
110 #if CONFIG_VOLFS
111 static int vfs_getrealpath(const char * path, char * realpath, size_t bufsize, vfs_context_t ctx, vnode_t rdvp);
112 #define MAX_VOLFS_RESTARTS 5
113 #endif
114 
115 static int              lookup_traverse_mountpoints(struct nameidata *ndp, struct componentname *cnp, vnode_t dp, int vbusyflags, vfs_context_t ctx);
116 static int              lookup_handle_symlink(struct nameidata *ndp, vnode_t *new_dp, bool* dp_has_iocount, vfs_context_t ctx);
117 static int              lookup_authorize_search(vnode_t dp, struct componentname *cnp, int dp_authorized_in_cache, vfs_context_t ctx);
118 static void             lookup_consider_update_cache(vnode_t dvp, vnode_t vp, struct componentname *cnp, int nc_generation);
119 static int              lookup_handle_found_vnode(struct nameidata *ndp, struct componentname *cnp, int rdonly,
120     int vbusyflags, int *keep_going, int nc_generation,
121     int wantparent, int atroot, vfs_context_t ctx);
122 static int              lookup_handle_emptyname(struct nameidata *ndp, struct componentname *cnp, int wantparent);
123 
124 #if NAMEDRSRCFORK
125 static int              lookup_handle_rsrc_fork(vnode_t dp, struct nameidata *ndp, struct componentname *cnp, int wantparent, vfs_context_t ctx);
126 #endif
127 
128 extern lck_rw_t rootvnode_rw_lock;
129 
130 #define RESOLVE_CHECKED       0x80000000
131 
132 static KALLOC_HEAP_DEFINE(KHEAP_VFS_NAMEI, "vfs_namei", KHEAP_ID_DATA_BUFFERS);
133 
134 /* namei allocation/free methods */
135 
136 __typed_allocators_ignore_push
137 
138 static void *
namei_alloc(size_t size)139 namei_alloc(size_t size)
140 {
141 	assert(size <= MAXLONGPATHLEN);
142 	return kheap_alloc(KHEAP_VFS_NAMEI, size, Z_WAITOK_ZERO_NOFAIL);
143 }
144 
145 static void
namei_free(void * addr,size_t size)146 namei_free(void *addr, size_t size)
147 {
148 	assert(size <= MAXLONGPATHLEN);
149 	kheap_free(KHEAP_VFS_NAMEI, addr, size);
150 }
151 
152 __typed_allocators_ignore_pop
153 
154 /*
155  * Convert a pathname into a pointer to a locked inode.
156  *
157  * The FOLLOW flag is set when symbolic links are to be followed
158  * when they occur at the end of the name translation process.
159  * Symbolic links are always followed for all other pathname
160  * components other than the last.
161  *
162  * The segflg defines whether the name is to be copied from user
163  * space or kernel space.
164  *
165  * Overall outline of namei:
166  *
167  *	copy in name
168  *	get starting directory
169  *	while (!done && !error) {
170  *		call lookup to search path.
171  *		if symbolic link, massage name in buffer and continue
172  *	}
173  *
174  * Returns:	0			Success
175  *		ENOENT			No such file or directory
176  *		ELOOP			Too many levels of symbolic links
177  *		ENAMETOOLONG		Filename too long
178  *		copyinstr:EFAULT	Bad address
179  *		copyinstr:ENAMETOOLONG	Filename too long
180  *		lookup:EBADF		Bad file descriptor
181  *		lookup:EROFS
182  *		lookup:EACCES
183  *		lookup:EPERM
184  *		lookup:ERECYCLE	 vnode was recycled from underneath us in lookup.
185  *						 This means we should re-drive lookup from this point.
186  *		lookup: ???
187  *		VNOP_READLINK:???
188  */
189 int
namei(struct nameidata * ndp)190 namei(struct nameidata *ndp)
191 {
192 	struct vnode *dp;       /* the directory we are searching */
193 	struct vnode *usedvp = ndp->ni_dvp;  /* store pointer to vp in case we must loop due to
194 	                                      *                                          heavy vnode pressure */
195 	uint32_t cnpflags = ndp->ni_cnd.cn_flags; /* store in case we have to restore after loop */
196 	int error;
197 	struct componentname *cnp = &ndp->ni_cnd;
198 	vfs_context_t ctx = cnp->cn_context;
199 	proc_t p = vfs_context_proc(ctx);
200 #if CONFIG_AUDIT
201 /* XXX ut should be from context */
202 	uthread_t ut = current_uthread();
203 #endif
204 
205 #if CONFIG_VOLFS
206 	int volfs_restarts = 0;
207 #endif
208 	size_t bytes_copied = 0;
209 	size_t resolve_prefix_len = 0;
210 	vnode_t rootdir_with_usecount = NULLVP;
211 	vnode_t startdir_with_usecount = NULLVP;
212 	vnode_t usedvp_dp = NULLVP;
213 	int32_t old_count = 0;
214 	uint32_t resolve_flags = 0;
215 	int resolve_error = 0;
216 	bool dp_has_iocount = false;
217 	bool clear_usedvp = false;
218 
219 #if DIAGNOSTIC
220 	if (!vfs_context_ucred(ctx) || !p) {
221 		panic("namei: bad cred/proc");
222 	}
223 	if (cnp->cn_nameiop & (~OPMASK)) {
224 		panic("namei: nameiop contaminated with flags");
225 	}
226 	if (cnp->cn_flags & OPMASK) {
227 		panic("namei: flags contaminated with nameiops");
228 	}
229 #endif
230 
231 	/*
232 	 * A compound VNOP found something that needs further processing:
233 	 * either a trigger vnode, a covered directory, or a symlink.
234 	 */
235 	if (ndp->ni_flag & NAMEI_CONTLOOKUP) {
236 		int rdonly, vbusyflags, keep_going, wantparent;
237 
238 		rdonly = cnp->cn_flags & RDONLY;
239 		vbusyflags = ((cnp->cn_flags & CN_NBMOUNTLOOK) != 0) ? LK_NOWAIT : 0;
240 		keep_going = 0;
241 		wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
242 
243 		ndp->ni_flag &= ~(NAMEI_CONTLOOKUP);
244 
245 		error = lookup_handle_found_vnode(ndp, &ndp->ni_cnd, rdonly, vbusyflags,
246 		    &keep_going, ndp->ni_ncgeneration, wantparent, 0, ctx);
247 		if (error) {
248 			goto out_drop;
249 		}
250 		if (keep_going) {
251 			if ((cnp->cn_flags & ISSYMLINK) == 0) {
252 				panic("We need to keep going on a continued lookup, but for vp type %d (tag %d)", ndp->ni_vp->v_type, ndp->ni_vp->v_tag);
253 			}
254 			goto continue_symlink;
255 		}
256 
257 		return 0;
258 	}
259 
260 vnode_recycled:
261 
262 	/*
263 	 * Get a buffer for the name to be translated, and copy the
264 	 * name into the buffer.
265 	 */
266 	if ((cnp->cn_flags & HASBUF) == 0) {
267 		cnp->cn_pnbuf = ndp->ni_pathbuf;
268 		cnp->cn_pnlen = PATHBUFLEN;
269 	}
270 
271 retry_copy:
272 	if (UIO_SEG_IS_USER_SPACE(ndp->ni_segflg)) {
273 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
274 		    cnp->cn_pnlen, &bytes_copied);
275 	} else {
276 		error = copystr(CAST_DOWN(void *, ndp->ni_dirp), cnp->cn_pnbuf,
277 		    cnp->cn_pnlen, &bytes_copied);
278 	}
279 	if (error == ENAMETOOLONG && !(cnp->cn_flags & HASBUF)) {
280 		if (bytes_copied == PATHBUFLEN) {
281 			resolve_error = lookup_check_for_resolve_prefix(cnp->cn_pnbuf, PATHBUFLEN,
282 			    PATHBUFLEN, &resolve_flags, &resolve_prefix_len);
283 			/* errors from copyinstr take precedence over resolve_error */
284 			if (!resolve_error && resolve_prefix_len) {
285 				ndp->ni_dirp += resolve_prefix_len;
286 				resolve_prefix_len = 0;
287 			}
288 		}
289 
290 		cnp->cn_pnbuf = namei_alloc(MAXPATHLEN);
291 		cnp->cn_flags |= HASBUF;
292 		cnp->cn_pnlen = MAXPATHLEN;
293 		bytes_copied = 0;
294 
295 		goto retry_copy;
296 	} else if (error == ENAMETOOLONG && (cnp->cn_flags & HASBUF) &&
297 	    (cnp->cn_pnlen * 2) <= MAXLONGPATHLEN && proc_support_long_paths(p)) {
298 		/* First time we arrive here, the buffer came from namei_alloc */
299 		namei_free(cnp->cn_pnbuf, cnp->cn_pnlen);
300 
301 		resolve_error = 0;
302 
303 		cnp->cn_pnlen *= 2;
304 		cnp->cn_pnbuf = namei_alloc(cnp->cn_pnlen);
305 		bytes_copied = 0;
306 
307 		goto retry_copy;
308 	}
309 	if (error) {
310 		goto error_out;
311 	} else if (resolve_error) {
312 		error = resolve_error;
313 		goto error_out;
314 	}
315 	assert(bytes_copied <= cnp->cn_pnlen);
316 	ndp->ni_pathlen = (u_int)bytes_copied;
317 	bytes_copied = 0;
318 
319 	if (!(resolve_flags & RESOLVE_CHECKED)) {
320 		assert(!(cnp->cn_flags & HASBUF) && (cnp->cn_pnlen == PATHBUFLEN));
321 		error = lookup_check_for_resolve_prefix(cnp->cn_pnbuf, cnp->cn_pnlen, ndp->ni_pathlen,
322 		    &resolve_flags, &resolve_prefix_len);
323 		if (error) {
324 			goto error_out;
325 		}
326 		if (resolve_prefix_len) {
327 			/*
328 			 * Since this is pointing to the static path buffer instead of a zalloc'ed memorry,
329 			 * we're not going to attempt to free this, so it is perfectly fine to change the
330 			 * value of cnp->cn_pnbuf.
331 			 */
332 			cnp->cn_pnbuf += resolve_prefix_len;
333 			cnp->cn_pnlen -= resolve_prefix_len;
334 			ndp->ni_pathlen -= resolve_prefix_len;
335 			resolve_prefix_len = 0;
336 
337 			/* Update ndp with the resolve flags */
338 			if (resolve_flags & RESOLVE_NODOTDOT) {
339 				ndp->ni_flag |= NAMEI_NODOTDOT;
340 			}
341 			if (resolve_flags & RESOLVE_LOCAL) {
342 				ndp->ni_flag |= NAMEI_LOCAL;
343 			}
344 			if (resolve_flags & RESOLVE_NODEVFS) {
345 				ndp->ni_flag |= NAMEI_NODEVFS;
346 			}
347 			if (resolve_flags & RESOLVE_IMMOVABLE) {
348 				ndp->ni_flag |= NAMEI_IMMOVABLE;
349 			}
350 			if (resolve_flags & RESOLVE_UNIQUE) {
351 				ndp->ni_flag |= NAMEI_UNIQUE;
352 			}
353 			if (resolve_flags & RESOLVE_NOXATTRS) {
354 				ndp->ni_flag |= NAMEI_NOXATTRS;
355 			}
356 		}
357 	}
358 
359 	/* At this point we should have stripped off the prefix from the path that has to be looked up */
360 	assert((resolve_flags & RESOLVE_CHECKED) && (resolve_prefix_len == 0));
361 
362 	/*
363 	 * Since the name cache may contain positive entries of
364 	 * the incorrect case, force lookup() to bypass the cache
365 	 * and call directly into the filesystem for each path
366 	 * component. Note: the FS may still consult the cache,
367 	 * but can apply rules to validate the results.
368 	 */
369 	if (proc_is_forcing_hfs_case_sensitivity(p)) {
370 		cnp->cn_flags |= CN_SKIPNAMECACHE;
371 	}
372 
373 #if CONFIG_VOLFS
374 	/*
375 	 * Check for legacy volfs style pathnames.
376 	 *
377 	 * For compatibility reasons we currently allow these paths,
378 	 * but future versions of the OS may not support them.
379 	 */
380 	if (ndp->ni_pathlen >= VOLFS_MIN_PATH_LEN &&
381 	    cnp->cn_pnbuf[0] == '/' &&
382 	    cnp->cn_pnbuf[1] == '.' &&
383 	    cnp->cn_pnbuf[2] == 'v' &&
384 	    cnp->cn_pnbuf[3] == 'o' &&
385 	    cnp->cn_pnbuf[4] == 'l' &&
386 	    cnp->cn_pnbuf[5] == '/') {
387 		char * realpath;
388 		size_t realpathlen;
389 		int realpath_err;
390 		vnode_t rdvp = NULLVP;
391 		/* Attempt to resolve a legacy volfs style pathname. */
392 
393 		realpathlen = MAXPATHLEN;
394 		do {
395 			/*
396 			 * To be consistent with the behavior of openbyid_np, which always supports
397 			 * long paths, do not gate our support on proc_support_long_paths either.
398 			 */
399 			realpath = namei_alloc(realpathlen);
400 
401 			if (fdt_flag_test(&p->p_fd, FD_CHROOT)) {
402 				proc_dirs_lock_shared(p);
403 				if (fdt_flag_test(&p->p_fd, FD_CHROOT)) {
404 					rdvp = p->p_fd.fd_rdir;
405 					if (vnode_get(rdvp)) {
406 						rdvp = NULLVP;
407 					}
408 				}
409 				proc_dirs_unlock_shared(p);
410 			}
411 			/*
412 			 * We only error out on the ENAMETOOLONG cases where we know that
413 			 * vfs_getrealpath translation succeeded but the path could not fit into
414 			 * realpathlen characters.  In other failure cases, we may be dealing with a path
415 			 * that legitimately looks like /.vol/1234/567 and is not meant to be translated
416 			 */
417 			realpath_err = vfs_getrealpath(&cnp->cn_pnbuf[6], realpath, realpathlen, ctx, rdvp);
418 
419 			if (rdvp) {
420 				vnode_put(rdvp);
421 				rdvp = NULLVP;
422 			}
423 			if (realpath_err) {
424 				namei_free(realpath, realpathlen);
425 				if (realpath_err == ENOSPC || realpath_err == ENAMETOOLONG) {
426 					error = ENAMETOOLONG;
427 				}
428 			} else {
429 				size_t tmp_len;
430 				if (cnp->cn_flags & HASBUF) {
431 					namei_free(cnp->cn_pnbuf, cnp->cn_pnlen);
432 				}
433 				cnp->cn_pnbuf = realpath;
434 				cnp->cn_pnlen = (int)realpathlen;
435 				tmp_len = strlen(realpath) + 1;
436 				assert(tmp_len <= UINT_MAX);
437 				ndp->ni_pathlen = (u_int)tmp_len;
438 				cnp->cn_flags |= HASBUF | CN_VOLFSPATH;
439 				error = 0;
440 			}
441 		} while (error == ENAMETOOLONG && (realpathlen *= 2) && realpathlen <= MAXLONGPATHLEN);
442 
443 		if (error) {
444 			goto error_out;
445 		}
446 	}
447 #endif /* CONFIG_VOLFS */
448 
449 #if CONFIG_AUDIT
450 	/* If we are auditing the kernel pathname, save the user pathname */
451 	if (cnp->cn_flags & AUDITVNPATH1) {
452 		AUDIT_ARG(upath, ut->uu_cdir, cnp->cn_pnbuf, ARG_UPATH1);
453 	}
454 	if (cnp->cn_flags & AUDITVNPATH2) {
455 		AUDIT_ARG(upath, ut->uu_cdir, cnp->cn_pnbuf, ARG_UPATH2);
456 	}
457 #endif /* CONFIG_AUDIT */
458 
459 	/*
460 	 * Do not allow empty pathnames
461 	 */
462 	if (*cnp->cn_pnbuf == '\0') {
463 		error = ENOENT;
464 		goto error_out;
465 	}
466 	if (ndp->ni_flag & NAMEI_NOFOLLOW_ANY || (resolve_flags & RESOLVE_NOFOLLOW_ANY)) {
467 		ndp->ni_loopcnt = MAXSYMLINKS;
468 	} else {
469 		ndp->ni_loopcnt = 0;
470 	}
471 
472 	/*
473 	 * determine the starting point for the translation.
474 	 */
475 	proc_dirs_lock_shared(p);
476 	lck_rw_lock_shared(&rootvnode_rw_lock);
477 
478 	if (!(ndp->ni_flag & NAMEI_ROOTDIR)) {
479 		if (fdt_flag_test(&p->p_fd, FD_CHROOT)) {
480 			ndp->ni_rootdir = p->p_fd.fd_rdir;
481 		} else {
482 			ndp->ni_rootdir = rootvnode;
483 		}
484 	}
485 
486 	if (!ndp->ni_rootdir) {
487 		if (ndp->ni_flag & NAMEI_ROOTDIR) {
488 			panic("NAMEI_ROOTDIR is set but ni_rootdir is not\n");
489 		} else if (fdt_flag_test(&p->p_fd, FD_CHROOT)) {
490 			/* This should be a panic */
491 			printf("p->p_fd.fd_rdir is not set\n");
492 		} else {
493 			printf("rootvnode is not set\n");
494 		}
495 		lck_rw_unlock_shared(&rootvnode_rw_lock);
496 		proc_dirs_unlock_shared(p);
497 		error = ENOENT;
498 		goto error_out;
499 	}
500 
501 	cnp->cn_nameptr = cnp->cn_pnbuf;
502 
503 	ndp->ni_usedvp = NULLVP;
504 
505 	if (*(cnp->cn_nameptr) == '/') {
506 		while (*(cnp->cn_nameptr) == '/') {
507 			cnp->cn_nameptr++;
508 			ndp->ni_pathlen--;
509 		}
510 		if (ndp->ni_flag & NAMEI_RESOLVE_BENEATH) {
511 			/* Absolute paths are never allowed in NAMEI_RESOLVE_BENEATH */
512 			lck_rw_unlock_shared(&rootvnode_rw_lock);
513 			proc_dirs_unlock_shared(p);
514 			error = ENOTCAPABLE;
515 			goto error_out;
516 		}
517 		dp = ndp->ni_rootdir;
518 	} else if (cnp->cn_flags & USEDVP) {
519 		dp = ndp->ni_dvp;
520 		ndp->ni_usedvp = dp;
521 		usedvp_dp = dp;
522 	} else {
523 		dp = vfs_context_cwd(ctx);
524 		if (ndp->ni_flag & NAMEI_RESOLVE_BENEATH) {
525 			/* Store the starting directory because it can change after a symlink traversal */
526 			ndp->ni_usedvp = dp;
527 			clear_usedvp = true;
528 		}
529 	}
530 
531 	if (dp == NULLVP || (dp->v_lflag & VL_DEAD)) {
532 		dp = NULLVP;
533 		lck_rw_unlock_shared(&rootvnode_rw_lock);
534 		proc_dirs_unlock_shared(p);
535 		error = ENOENT;
536 		goto error_out;
537 	}
538 
539 	/*
540 	 * We need our own usecount on the root vnode and the starting dir across
541 	 * the lookup. There's two things that be done here. We can hold the locks
542 	 * (which protect the existing usecounts on the directories) across the
543 	 * lookup or take our own usecount. Holding the locks across the lookup can
544 	 * cause deadlock issues if we re-enter namei on the same thread so the
545 	 * correct thing to do is to acquire our own usecount.
546 	 *
547 	 * Ideally, the usecount should be obtained by vnode_get->vnode_ref->vnode_put.
548 	 * However when this vnode is the rootvnode, that sequence will produce a
549 	 * lot of vnode mutex locks and  unlocks on a single vnode (the rootvnode)
550 	 * and will be highly contended and degrade performance. Since we have
551 	 * an existing usecount protected by the locks we hold, we'll just use
552 	 * an atomic op to increment the usecount on a vnode which already has one
553 	 * and can't be released because we have the locks which protect against that
554 	 * happening.
555 	 */
556 	rootdir_with_usecount = ndp->ni_rootdir;
557 	old_count = os_atomic_inc_orig(&rootdir_with_usecount->v_usecount, relaxed);
558 	if (old_count < 1) {
559 		panic("(1) invalid pre-increment usecount (%d) for rootdir vnode %p",
560 		    old_count, rootdir_with_usecount);
561 	} else if (old_count == INT32_MAX) {
562 		panic("(1) usecount overflow for vnode %p", rootdir_with_usecount);
563 	}
564 
565 	if ((dp != rootdir_with_usecount) && (dp != usedvp_dp)) {
566 		old_count = os_atomic_inc_orig(&dp->v_usecount, relaxed);
567 		if (old_count < 1) {
568 			panic("(2) invalid pre-increment usecount (%d) for vnode %p", old_count, dp);
569 		} else if (old_count == INT32_MAX) {
570 			panic("(2) usecount overflow for vnode %p", dp);
571 		}
572 		startdir_with_usecount = dp;
573 	}
574 
575 	/* Now that we have our usecount, release the locks */
576 	lck_rw_unlock_shared(&rootvnode_rw_lock);
577 	proc_dirs_unlock_shared(p);
578 
579 	ndp->ni_dvp = NULLVP;
580 	ndp->ni_vp  = NULLVP;
581 
582 	for (;;) {
583 #if CONFIG_MACF
584 		/*
585 		 * Give MACF policies a chance to reject the lookup
586 		 * before performing any filesystem operations.
587 		 * This hook is called before resolving the path and
588 		 * again each time a symlink is encountered.
589 		 * NB: policies receive path information as supplied
590 		 *     by the caller and thus cannot be trusted.
591 		 */
592 		error = mac_vnode_check_lookup_preflight(ctx, dp, cnp->cn_nameptr, cnp->cn_namelen);
593 		if (error) {
594 			goto error_out;
595 		}
596 #endif
597 		ndp->ni_startdir = dp;
598 		dp = NULLVP;
599 
600 		if ((error = lookup(ndp))) {
601 			goto error_out;
602 		}
603 
604 		/*
605 		 * Check for symbolic link
606 		 */
607 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
608 			if ((ndp->ni_flag & NAMEI_UNIQUE) && ndp->ni_vp && vnode_hasmultipath(ndp->ni_vp)) {
609 				error = ENOTCAPABLE;
610 				goto out_drop;
611 			}
612 			if (startdir_with_usecount) {
613 				vnode_rele(startdir_with_usecount);
614 				startdir_with_usecount = NULLVP;
615 			}
616 			if (rootdir_with_usecount) {
617 				lck_rw_lock_shared(&rootvnode_rw_lock);
618 				if (rootdir_with_usecount == rootvnode) {
619 					old_count = os_atomic_dec_orig(&rootdir_with_usecount->v_usecount, relaxed);
620 					if (old_count < 2) {
621 						/*
622 						 * There needs to have been at least 1 usecount left on the rootvnode
623 						 */
624 						panic("(3) Unexpected pre-decrement value (%d) of usecount for rootvnode %p",
625 						    old_count, rootdir_with_usecount);
626 					}
627 					rootdir_with_usecount = NULLVP;
628 				}
629 				lck_rw_unlock_shared(&rootvnode_rw_lock);
630 				if (rootdir_with_usecount) {
631 					vnode_rele(rootdir_with_usecount);
632 					rootdir_with_usecount = NULLVP;
633 				}
634 			}
635 
636 			return 0;
637 		}
638 
639 continue_symlink:
640 		/* Gives us a new path to process, and a starting dir */
641 		error = lookup_handle_symlink(ndp, &dp, &dp_has_iocount, ctx);
642 		if (error != 0) {
643 			break;
644 		}
645 		if (dp_has_iocount) {
646 			if ((dp != rootdir_with_usecount) && (dp != startdir_with_usecount) &&
647 			    (dp != usedvp_dp)) {
648 				if (startdir_with_usecount) {
649 					vnode_rele(startdir_with_usecount);
650 				}
651 				vnode_ref_ext(dp, 0, VNODE_REF_FORCE);
652 				startdir_with_usecount = dp;
653 			}
654 			vnode_put(dp);
655 			dp_has_iocount = false;
656 		}
657 	}
658 	/*
659 	 * only come here if we fail to handle a SYMLINK...
660 	 * if either ni_dvp or ni_vp is non-NULL, then
661 	 * we need to drop the iocount that was picked
662 	 * up in the lookup routine
663 	 */
664 out_drop:
665 	if (ndp->ni_dvp) {
666 		vnode_put(ndp->ni_dvp);
667 	}
668 	if (ndp->ni_vp) {
669 		vnode_put(ndp->ni_vp);
670 	}
671 error_out:
672 	if (clear_usedvp) {
673 		ndp->ni_usedvp = NULLVP;
674 	}
675 	if (startdir_with_usecount) {
676 		vnode_rele(startdir_with_usecount);
677 		startdir_with_usecount = NULLVP;
678 	}
679 	if (rootdir_with_usecount) {
680 		lck_rw_lock_shared(&rootvnode_rw_lock);
681 		if (rootdir_with_usecount == rootvnode) {
682 			old_count = os_atomic_dec_orig(&rootdir_with_usecount->v_usecount, relaxed);
683 			if (old_count < 2) {
684 				/*
685 				 * There needs to have been at least 1 usecount left on the rootvnode
686 				 */
687 				panic("(4) Unexpected pre-decrement value (%d) of usecount for rootvnode %p",
688 				    old_count, rootdir_with_usecount);
689 			}
690 			lck_rw_unlock_shared(&rootvnode_rw_lock);
691 		} else {
692 			lck_rw_unlock_shared(&rootvnode_rw_lock);
693 			vnode_rele(rootdir_with_usecount);
694 		}
695 		rootdir_with_usecount = NULLVP;
696 	}
697 
698 	if ((cnp->cn_flags & HASBUF)) {
699 		cnp->cn_flags &= ~HASBUF;
700 		namei_free(cnp->cn_pnbuf, cnp->cn_pnlen);
701 	}
702 	cnp->cn_pnbuf = NULL;
703 	ndp->ni_vp = NULLVP;
704 	ndp->ni_dvp = NULLVP;
705 
706 #if CONFIG_VOLFS
707 	/*
708 	 * Deal with volfs fallout.
709 	 *
710 	 * At this point, if we were originally given a volfs path that
711 	 * looks like /.vol/123/456, then we would have had to convert it into
712 	 * a full path.  Assuming that part worked properly, we will now attempt
713 	 * to conduct a lookup of the item in the namespace.  Under normal
714 	 * circumstances, if a user looked up /tmp/foo and it was not there, it
715 	 * would be permissible to return ENOENT.
716 	 *
717 	 * However, we may not want to do that here.  Specifically, the volfs path
718 	 * uniquely identifies a certain item in the namespace regardless of where it
719 	 * lives.  If the item has moved in between the time we constructed the
720 	 * path and now, when we're trying to do a lookup/authorization on the full
721 	 * path, we may have gotten an ENOENT.
722 	 *
723 	 * At this point we can no longer tell if the path no longer exists
724 	 * or if the item in question no longer exists. It could have been renamed
725 	 * away, in which case the /.vol identifier is still valid.
726 	 *
727 	 * Do this dance a maximum of MAX_VOLFS_RESTARTS times.
728 	 */
729 	if ((error == ENOENT) && (ndp->ni_cnd.cn_flags & CN_VOLFSPATH)) {
730 		if (volfs_restarts < MAX_VOLFS_RESTARTS) {
731 			volfs_restarts++;
732 			goto vnode_recycled;
733 		}
734 	}
735 #endif
736 
737 	if (error == ERECYCLE) {
738 		/* vnode was recycled underneath us. re-drive lookup to start at
739 		 *  the beginning again, since recycling invalidated last lookup*/
740 		ndp->ni_cnd.cn_flags = cnpflags;
741 		ndp->ni_dvp = usedvp;
742 		goto vnode_recycled;
743 	}
744 
745 
746 	return error;
747 }
748 
749 int
namei_compound_available(vnode_t dp,struct nameidata * ndp)750 namei_compound_available(vnode_t dp, struct nameidata *ndp)
751 {
752 	if ((ndp->ni_flag & NAMEI_COMPOUNDOPEN) != 0) {
753 		return vnode_compound_open_available(dp);
754 	}
755 
756 	return 0;
757 }
758 
759 int
lookup_check_for_resolve_prefix(char * path,size_t pathbuflen,size_t len,uint32_t * resolve_flags,size_t * prefix_len)760 lookup_check_for_resolve_prefix(char *path, size_t pathbuflen, size_t len, uint32_t *resolve_flags, size_t *prefix_len)
761 {
762 	int error = 0;
763 	*resolve_flags = (uint32_t)RESOLVE_CHECKED;
764 	*prefix_len = 0;
765 
766 	if (len < (sizeof("/.nofollow/") - 1) || path[0] != '/' || path[1] != '.') {
767 		return 0;
768 	}
769 
770 	if ((strncmp(&path[2], "nofollow/", (sizeof("nofollow/") - 1)) == 0)) {
771 		*resolve_flags |= RESOLVE_NOFOLLOW_ANY;
772 		*prefix_len = sizeof("/.nofollow") - 1;
773 	} else if ((len >= sizeof("/.resolve/1/") - 1) &&
774 	    strncmp(&path[2], "resolve/", (sizeof("resolve/") - 1)) == 0) {
775 		char * flag = path + (sizeof("/.resolve/") - 1);
776 		char *next = flag;
777 		char last_char = path[pathbuflen - 1];
778 
779 		/* no leading zeroes or non digits */
780 		if ((flag[0] == '0' && flag[1] != '/') ||
781 		    flag[0] < '0' || flag[0] > '9') {
782 			error = EINVAL;
783 			goto out;
784 		}
785 
786 		path[pathbuflen - 1] = '\0';
787 		unsigned long flag_val = strtoul(flag, &next, 10);
788 		path[pathbuflen - 1] = last_char;
789 		if (next[0] != '/' || (flag_val & ~RESOLVE_VALIDMASK)) {
790 			error = EINVAL;
791 			goto out;
792 		}
793 		assert(next >= flag);
794 		*resolve_flags |= (uint32_t)flag_val;
795 		*prefix_len = (size_t)(next - path);
796 	}
797 out:
798 	assert(*prefix_len <= sizeof("/.resolve/2147483647"));
799 	return error;
800 }
801 
802 static int
lookup_authorize_search(vnode_t dp,struct componentname * cnp,int dp_authorized_in_cache,vfs_context_t ctx)803 lookup_authorize_search(vnode_t dp, struct componentname *cnp, int dp_authorized_in_cache, vfs_context_t ctx)
804 {
805 #if !CONFIG_MACF
806 #pragma unused(cnp)
807 #endif
808 
809 	int error;
810 
811 	if (!dp_authorized_in_cache) {
812 		error = vnode_authorize(dp, NULL, KAUTH_VNODE_SEARCH, ctx);
813 		if (error) {
814 			return error;
815 		}
816 	}
817 #if CONFIG_MACF
818 	error = mac_vnode_check_lookup(ctx, dp, cnp);
819 	if (error) {
820 		return error;
821 	}
822 #endif /* CONFIG_MACF */
823 
824 	return 0;
825 }
826 
827 static void
lookup_consider_update_cache(vnode_t dvp,vnode_t vp,struct componentname * cnp,int nc_generation)828 lookup_consider_update_cache(vnode_t dvp, vnode_t vp, struct componentname *cnp, int nc_generation)
829 {
830 	int isdot_or_dotdot;
831 	isdot_or_dotdot = (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') || (cnp->cn_flags & ISDOTDOT);
832 
833 	if (vp->v_name == NULL || vp->v_parent == NULLVP) {
834 		int  update_flags = 0;
835 
836 		if (isdot_or_dotdot == 0) {
837 			if (vp->v_name == NULL) {
838 				update_flags |= VNODE_UPDATE_NAME;
839 			}
840 			if (dvp != NULLVP && vp->v_parent == NULLVP) {
841 				update_flags |= VNODE_UPDATE_PARENT;
842 			}
843 
844 			if (update_flags) {
845 				vnode_update_identity(vp, dvp, cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, update_flags);
846 			}
847 		}
848 	}
849 	if ((cnp->cn_flags & MAKEENTRY) && (vp->v_flag & VNCACHEABLE) && LIST_FIRST(&vp->v_nclinks) == NULL) {
850 		/*
851 		 * missing from name cache, but should
852 		 * be in it... this can happen if volfs
853 		 * causes the vnode to be created or the
854 		 * name cache entry got recycled but the
855 		 * vnode didn't...
856 		 * check to make sure that ni_dvp is valid
857 		 * cache_lookup_path may return a NULL
858 		 * do a quick check to see if the generation of the
859 		 * directory matches our snapshot... this will get
860 		 * rechecked behind the name cache lock, but if it
861 		 * already fails to match, no need to go any further
862 		 */
863 		if (dvp != NULLVP && (nc_generation == dvp->v_nc_generation) && (!isdot_or_dotdot)) {
864 			cache_enter_with_gen(dvp, vp, cnp, nc_generation);
865 		}
866 	}
867 }
868 
869 #if NAMEDRSRCFORK
870 /*
871  * Can change ni_dvp and ni_vp.  On success, returns with iocounts on stream vnode (always) and
872  * data fork if requested.  On failure, returns with iocount data fork (always) and its parent directory
873  * (if one was provided).
874  */
875 static int
lookup_handle_rsrc_fork(vnode_t dp,struct nameidata * ndp,struct componentname * cnp,int wantparent,vfs_context_t ctx)876 lookup_handle_rsrc_fork(vnode_t dp, struct nameidata *ndp, struct componentname *cnp, int wantparent, vfs_context_t ctx)
877 {
878 	vnode_t svp = NULLVP;
879 	enum nsoperation nsop;
880 	int nsflags;
881 	int error;
882 
883 	if (dp->v_type != VREG) {
884 		error = ENOENT;
885 		goto out;
886 	}
887 	switch (cnp->cn_nameiop) {
888 	case DELETE:
889 		if (cnp->cn_flags & CN_ALLOWRSRCFORK) {
890 			nsop = NS_DELETE;
891 		} else {
892 			error = EPERM;
893 			goto out;
894 		}
895 		break;
896 	case CREATE:
897 		if (cnp->cn_flags & CN_ALLOWRSRCFORK) {
898 			nsop = NS_CREATE;
899 		} else {
900 			error = EPERM;
901 			goto out;
902 		}
903 		break;
904 	case LOOKUP:
905 		/* Make sure our lookup of "/..namedfork/rsrc" is allowed. */
906 		if (cnp->cn_flags & CN_ALLOWRSRCFORK) {
907 			nsop = NS_OPEN;
908 		} else {
909 			error = EPERM;
910 			goto out;
911 		}
912 		break;
913 	default:
914 		error = EPERM;
915 		goto out;
916 	}
917 
918 	nsflags = 0;
919 	if (cnp->cn_flags & CN_RAW_ENCRYPTED) {
920 		nsflags |= NS_GETRAWENCRYPTED;
921 	}
922 
923 	/* Ask the file system for the resource fork. */
924 	error = vnode_getnamedstream(dp, &svp, XATTR_RESOURCEFORK_NAME, nsop, nsflags, ctx);
925 
926 	/* During a create, it OK for stream vnode to be missing. */
927 	if (error == ENOATTR || error == ENOENT) {
928 		error = (nsop == NS_CREATE) ? 0 : ENOENT;
929 	}
930 	if (error) {
931 		goto out;
932 	}
933 	/* The "parent" of the stream is the file. */
934 	if (wantparent) {
935 		if (ndp->ni_dvp) {
936 			vnode_put(ndp->ni_dvp);
937 		}
938 		ndp->ni_dvp = dp;
939 	} else {
940 		vnode_put(dp);
941 	}
942 	ndp->ni_vp = svp;  /* on create this may be null */
943 
944 	/* Restore the truncated pathname buffer (for audits). */
945 	if (ndp->ni_pathlen == 1 && ndp->ni_next[0] == '\0') {
946 		/*
947 		 * While we replaced only '/' with '\0' and would ordinarily
948 		 * need to just switch that back, the buffer in which we did
949 		 * this may not be what the pathname buffer is now when symlinks
950 		 * are involved. If we just restore the "/" we will make the
951 		 * string not terminated anymore, so be safe and restore the
952 		 * entire suffix.
953 		 */
954 		strncpy(ndp->ni_next, _PATH_RSRCFORKSPEC, sizeof(_PATH_RSRCFORKSPEC));
955 		cnp->cn_nameptr = ndp->ni_next + 1;
956 		cnp->cn_namelen = sizeof(_PATH_RSRCFORKSPEC) - 1;
957 		ndp->ni_next += cnp->cn_namelen;
958 		if (ndp->ni_next[0] != '\0') {
959 			panic("Incorrect termination of path in %s", __FUNCTION__);
960 		}
961 	}
962 	cnp->cn_flags  &= ~MAKEENTRY;
963 
964 	return 0;
965 out:
966 	return error;
967 }
968 #endif /* NAMEDRSRCFORK */
969 
970 /*
971  * iocounts in:
972  *      --One on ni_vp.  One on ni_dvp if there is more path, or we didn't come through the
973  *      cache, or we came through the cache and the caller doesn't want the parent.
974  *
975  * iocounts out:
976  *	--Leaves us in the correct state for the next step, whatever that might be.
977  *	--If we find a symlink, returns with iocounts on both ni_vp and ni_dvp.
978  *	--If we are to look up another component, then we have an iocount on ni_vp and
979  *	nothing else.
980  *	--If we are done, returns an iocount on ni_vp, and possibly on ni_dvp depending on nameidata flags.
981  *	--In the event of an error, may return with ni_dvp NULL'ed out (in which case, iocount
982  *	was dropped).
983  */
984 static int
lookup_handle_found_vnode(struct nameidata * ndp,struct componentname * cnp,int rdonly,int vbusyflags,int * keep_going,int nc_generation,int wantparent,int atroot,vfs_context_t ctx)985 lookup_handle_found_vnode(struct nameidata *ndp, struct componentname *cnp, int rdonly,
986     int vbusyflags, int *keep_going, int nc_generation,
987     int wantparent, int atroot, vfs_context_t ctx)
988 {
989 	vnode_t dp;
990 	int error;
991 	char *cp;
992 
993 	dp = ndp->ni_vp;
994 	*keep_going = 0;
995 
996 	if (ndp->ni_vp == NULLVP) {
997 		panic("NULL ni_vp in %s", __FUNCTION__);
998 	}
999 
1000 	if (atroot) {
1001 		goto nextname;
1002 	}
1003 
1004 	/*
1005 	 * Take into account any additional components consumed by
1006 	 * the underlying filesystem.
1007 	 */
1008 	if (cnp->cn_consume > 0) {
1009 		cnp->cn_nameptr += cnp->cn_consume;
1010 		ndp->ni_next += cnp->cn_consume;
1011 		ndp->ni_pathlen -= cnp->cn_consume;
1012 		cnp->cn_consume = 0;
1013 	} else {
1014 		lookup_consider_update_cache(ndp->ni_dvp, dp, cnp, nc_generation);
1015 	}
1016 
1017 	/*
1018 	 * Check to see if the vnode has been mounted on...
1019 	 * if so find the root of the mounted file system.
1020 	 * Updates ndp->ni_vp.
1021 	 */
1022 	error = lookup_traverse_mountpoints(ndp, cnp, dp, vbusyflags, ctx);
1023 	dp = ndp->ni_vp;
1024 	if (error) {
1025 		goto out;
1026 	}
1027 
1028 #if CONFIG_MACF
1029 	if (vfs_flags(vnode_mount(dp)) & MNT_MULTILABEL) {
1030 		error = vnode_label(vnode_mount(dp), NULL, dp, NULL, 0, ctx);
1031 		if (error) {
1032 			goto out;
1033 		}
1034 	}
1035 #endif
1036 
1037 	/*
1038 	 * Check for symbolic link
1039 	 */
1040 	if ((dp->v_type == VLNK) &&
1041 	    ((cnp->cn_flags & FOLLOW) || (ndp->ni_flag & NAMEI_TRAILINGSLASH) || *ndp->ni_next == '/')) {
1042 		cnp->cn_flags |= ISSYMLINK;
1043 		*keep_going = 1;
1044 		return 0;
1045 	}
1046 
1047 	/*
1048 	 * Check for bogus trailing slashes.
1049 	 */
1050 	if ((ndp->ni_flag & NAMEI_TRAILINGSLASH)) {
1051 		if (dp->v_type != VDIR) {
1052 #if CONFIG_MACF
1053 			/*
1054 			 * Prevent the information disclosure on the vnode
1055 			 */
1056 			if (mac_vnode_check_stat(ctx, NOCRED, dp) == EPERM) {
1057 				error = EPERM;
1058 				goto out;
1059 			}
1060 #endif /* CONFIG_MACF */
1061 			error = ENOTDIR;
1062 			goto out;
1063 		}
1064 		ndp->ni_flag &= ~(NAMEI_TRAILINGSLASH);
1065 	}
1066 
1067 #if NAMEDSTREAMS
1068 	/*
1069 	 * Deny namei/lookup requests to resolve paths that point to shadow files.
1070 	 * Access to shadow files must be conducted by explicit calls to VNOP_LOOKUP
1071 	 * directly, and not use lookup/namei
1072 	 */
1073 	if (vnode_isshadow(dp)) {
1074 		error = ENOENT;
1075 		goto out;
1076 	}
1077 #endif
1078 
1079 nextname:
1080 	/*
1081 	 * Not a symbolic link.  If more pathname,
1082 	 * continue at next component, else return.
1083 	 *
1084 	 * Definitely have a dvp if there's another slash
1085 	 */
1086 	if (*ndp->ni_next == '/') {
1087 		cnp->cn_nameptr = ndp->ni_next + 1;
1088 		ndp->ni_pathlen--;
1089 		while (*cnp->cn_nameptr == '/') {
1090 			cnp->cn_nameptr++;
1091 			ndp->ni_pathlen--;
1092 		}
1093 
1094 		cp = cnp->cn_nameptr;
1095 		vnode_put(ndp->ni_dvp);
1096 		ndp->ni_dvp = NULLVP;
1097 
1098 		if (*cp == '\0') {
1099 			goto emptyname;
1100 		}
1101 
1102 		*keep_going = 1;
1103 		return 0;
1104 	}
1105 
1106 	/*
1107 	 * Disallow directory write attempts on read-only file systems.
1108 	 */
1109 	if (rdonly &&
1110 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1111 		error = EROFS;
1112 		goto out;
1113 	}
1114 
1115 	/* If SAVESTART is set, we should have a dvp */
1116 	if (cnp->cn_flags & SAVESTART) {
1117 		/*
1118 		 * note that we already hold a reference
1119 		 * on both dp and ni_dvp, but for some reason
1120 		 * can't get another one... in this case we
1121 		 * need to do vnode_put on dp in 'bad2'
1122 		 */
1123 		if ((vnode_get(ndp->ni_dvp))) {
1124 			error = ENOENT;
1125 			goto out;
1126 		}
1127 		ndp->ni_startdir = ndp->ni_dvp;
1128 	}
1129 	if (!wantparent && ndp->ni_dvp) {
1130 		vnode_put(ndp->ni_dvp);
1131 		ndp->ni_dvp = NULLVP;
1132 	}
1133 
1134 	if (cnp->cn_flags & AUDITVNPATH1) {
1135 		AUDIT_ARG(vnpath, dp, ARG_VNODE1);
1136 	} else if (cnp->cn_flags & AUDITVNPATH2) {
1137 		AUDIT_ARG(vnpath, dp, ARG_VNODE2);
1138 	}
1139 
1140 #if NAMEDRSRCFORK
1141 	/*
1142 	 * Caller wants the resource fork.
1143 	 */
1144 	if ((cnp->cn_flags & CN_WANTSRSRCFORK) && (dp != NULLVP)) {
1145 		error = lookup_handle_rsrc_fork(dp, ndp, cnp, wantparent, ctx);
1146 		if (error != 0) {
1147 			goto out;
1148 		}
1149 
1150 		dp = ndp->ni_vp;
1151 	}
1152 #endif
1153 	if (kdebug_enable) {
1154 		kdebug_lookup(ndp->ni_vp, cnp);
1155 	}
1156 
1157 	return 0;
1158 
1159 emptyname:
1160 	error = lookup_handle_emptyname(ndp, cnp, wantparent);
1161 	if (error != 0) {
1162 		goto out;
1163 	}
1164 
1165 	return 0;
1166 out:
1167 	return error;
1168 }
1169 
1170 /*
1171  * Comes in iocount on ni_vp.  May overwrite ni_dvp, but doesn't interpret incoming value.
1172  */
1173 static int
lookup_handle_emptyname(struct nameidata * ndp,struct componentname * cnp,int wantparent)1174 lookup_handle_emptyname(struct nameidata *ndp, struct componentname *cnp, int wantparent)
1175 {
1176 	vnode_t dp;
1177 	int error = 0;
1178 
1179 	dp = ndp->ni_vp;
1180 	cnp->cn_namelen = 0;
1181 	/*
1182 	 * A degenerate name (e.g. / or "") which is a way of
1183 	 * talking about a directory, e.g. like "/." or ".".
1184 	 */
1185 	if (dp->v_type != VDIR) {
1186 		error = ENOTDIR;
1187 		goto out;
1188 	}
1189 	if (cnp->cn_nameiop == CREATE && dp == rootvnode) {
1190 		error = EEXIST;
1191 		goto out;
1192 	}
1193 	if (cnp->cn_nameiop != LOOKUP) {
1194 		error = EISDIR;
1195 		goto out;
1196 	}
1197 	if (wantparent) {
1198 		/*
1199 		 * note that we already hold a reference
1200 		 * on dp, but for some reason can't
1201 		 * get another one... in this case we
1202 		 * need to do vnode_put on dp in 'bad'
1203 		 */
1204 		if ((vnode_get(dp))) {
1205 			error = ENOENT;
1206 			goto out;
1207 		}
1208 		ndp->ni_dvp = dp;
1209 	}
1210 	cnp->cn_flags &= ~ISDOTDOT;
1211 	cnp->cn_flags |= ISLASTCN;
1212 	ndp->ni_next = cnp->cn_nameptr;
1213 	ndp->ni_vp = dp;
1214 
1215 	if (cnp->cn_flags & AUDITVNPATH1) {
1216 		AUDIT_ARG(vnpath, dp, ARG_VNODE1);
1217 	} else if (cnp->cn_flags & AUDITVNPATH2) {
1218 		AUDIT_ARG(vnpath, dp, ARG_VNODE2);
1219 	}
1220 	if (cnp->cn_flags & SAVESTART) {
1221 		panic("lookup: SAVESTART");
1222 	}
1223 
1224 	return 0;
1225 out:
1226 	return error;
1227 }
1228 /*
1229  * Search a pathname.
1230  * This is a very central and rather complicated routine.
1231  *
1232  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
1233  * The starting directory is taken from ni_startdir. The pathname is
1234  * descended until done, or a symbolic link is encountered. The variable
1235  * ni_more is clear if the path is completed; it is set to one if a
1236  * symbolic link needing interpretation is encountered.
1237  *
1238  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
1239  * whether the name is to be looked up, created, renamed, or deleted.
1240  * When CREATE, RENAME, or DELETE is specified, information usable in
1241  * creating, renaming, or deleting a directory entry may be calculated.
1242  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
1243  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
1244  * returned unlocked. Otherwise the parent directory is not returned. If
1245  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
1246  * the target is returned locked, otherwise it is returned unlocked.
1247  * When creating or renaming and LOCKPARENT is specified, the target may not
1248  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
1249  *
1250  * Overall outline of lookup:
1251  *
1252  * dirloop:
1253  *	identify next component of name at ndp->ni_ptr
1254  *	handle degenerate case where name is null string
1255  *	if .. and crossing mount points and on mounted filesys, find parent
1256  *	call VNOP_LOOKUP routine for next component name
1257  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
1258  *	    component vnode returned in ni_vp (if it exists), locked.
1259  *	if result vnode is mounted on and crossing mount points,
1260  *	    find mounted on vnode
1261  *	if more components of name, do next level at dirloop
1262  *	return the answer in ni_vp, locked if LOCKLEAF set
1263  *	    if LOCKPARENT set, return locked parent in ni_dvp
1264  *	    if WANTPARENT set, return unlocked parent in ni_dvp
1265  *
1266  * Returns:	0			Success
1267  *		ENOENT			No such file or directory
1268  *		EBADF			Bad file descriptor
1269  *		ENOTDIR			Not a directory
1270  *		EROFS			Read-only file system [CREATE]
1271  *		EISDIR			Is a directory [CREATE]
1272  *		cache_lookup_path:ERECYCLE  (vnode was recycled from underneath us, redrive lookup again)
1273  *		vnode_authorize:EROFS
1274  *		vnode_authorize:EACCES
1275  *		vnode_authorize:EPERM
1276  *		vnode_authorize:???
1277  *		VNOP_LOOKUP:ENOENT	No such file or directory
1278  *		VNOP_LOOKUP:EJUSTRETURN	Restart system call (INTERNAL)
1279  *		VNOP_LOOKUP:???
1280  *		VFS_ROOT:ENOTSUP
1281  *		VFS_ROOT:ENOENT
1282  *		VFS_ROOT:???
1283  */
1284 int
lookup(struct nameidata * ndp)1285 lookup(struct nameidata *ndp)
1286 {
1287 	char    *cp;            /* pointer into pathname argument */
1288 	vnode_t         tdp;            /* saved dp */
1289 	vnode_t         dp;             /* the directory we are searching */
1290 	int docache = 1;                /* == 0 do not cache last component */
1291 	int wantparent;                 /* 1 => wantparent or lockparent flag */
1292 	int rdonly;                     /* lookup read-only flag bit */
1293 	int dp_authorized = 0;
1294 	int error = 0;
1295 	struct componentname *cnp = &ndp->ni_cnd;
1296 	vfs_context_t ctx = cnp->cn_context;
1297 	int vbusyflags = 0;
1298 	int nc_generation = 0;
1299 	vnode_t last_dp = NULLVP;
1300 	int keep_going;
1301 	int atroot;
1302 
1303 	/*
1304 	 * Setup: break out flag bits into variables.
1305 	 */
1306 	if (cnp->cn_flags & NOCACHE) {
1307 		docache = 0;
1308 	}
1309 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
1310 	rdonly = cnp->cn_flags & RDONLY;
1311 	cnp->cn_flags &= ~ISSYMLINK;
1312 	cnp->cn_consume = 0;
1313 
1314 	dp = ndp->ni_startdir;
1315 	ndp->ni_startdir = NULLVP;
1316 
1317 	if ((cnp->cn_flags & CN_NBMOUNTLOOK) != 0) {
1318 		vbusyflags = LK_NOWAIT;
1319 	}
1320 	cp = cnp->cn_nameptr;
1321 
1322 	if (*cp == '\0') {
1323 		if ((vnode_getwithref(dp))) {
1324 			dp = NULLVP;
1325 			error = ENOENT;
1326 			goto bad;
1327 		}
1328 		ndp->ni_vp = dp;
1329 		error = lookup_handle_emptyname(ndp, cnp, wantparent);
1330 		if (error) {
1331 			goto bad;
1332 		}
1333 
1334 		return 0;
1335 	}
1336 dirloop:
1337 	atroot = 0;
1338 	ndp->ni_vp = NULLVP;
1339 
1340 	if ((error = cache_lookup_path(ndp, cnp, dp, ctx, &dp_authorized, last_dp))) {
1341 		dp = NULLVP;
1342 		goto bad;
1343 	}
1344 	if ((cnp->cn_flags & ISLASTCN)) {
1345 		if (docache) {
1346 			cnp->cn_flags |= MAKEENTRY;
1347 		}
1348 	} else {
1349 		cnp->cn_flags |= MAKEENTRY;
1350 	}
1351 
1352 	dp = ndp->ni_dvp;
1353 
1354 	if (ndp->ni_vp != NULLVP) {
1355 		/*
1356 		 * cache_lookup_path returned a non-NULL ni_vp then,
1357 		 * we're guaranteed that the dp is a VDIR, it's
1358 		 * been authorized, and vp is not ".."
1359 		 *
1360 		 * make sure we don't try to enter the name back into
1361 		 * the cache if this vp is purged before we get to that
1362 		 * check since we won't have serialized behind whatever
1363 		 * activity is occurring in the FS that caused the purge
1364 		 */
1365 		if (dp != NULLVP) {
1366 			nc_generation = dp->v_nc_generation - 1;
1367 		}
1368 
1369 		goto returned_from_lookup_path;
1370 	}
1371 
1372 #if NAMEDRSRCFORK
1373 	/* return ENOTCAPABLE if path lookup on named streams is prohibited. */
1374 	if ((ndp->ni_flag & NAMEI_NOXATTRS) &&
1375 	    (ndp->ni_pathlen == sizeof(_PATH_RSRCFORKSPEC)) &&
1376 	    (ndp->ni_next[1] == '.' && ndp->ni_next[2] == '.') &&
1377 	    bcmp(ndp->ni_next, _PATH_RSRCFORKSPEC, sizeof(_PATH_RSRCFORKSPEC)) == 0) {
1378 		error = ENOTCAPABLE;
1379 		goto bad;
1380 	}
1381 #endif /* NAMEDRSRCFORK */
1382 
1383 	/*
1384 	 * Handle "..": three special cases.
1385 	 * 1. if at starting directory (e.g. the cwd/usedvp)
1386 	 *    and RESOLVE_BENEATH, then return ENOTCAPABLE.
1387 	 * 2. If at root directory (e.g. after chroot)
1388 	 *    or at absolute root directory
1389 	 *    then ignore it so can't get out.
1390 	 * 3. If this vnode is the root of a mounted
1391 	 *    filesystem, then replace it with the
1392 	 *    vnode which was mounted on so we take the
1393 	 *    .. in the other file system.
1394 	 */
1395 	if ((cnp->cn_flags & ISDOTDOT)) {
1396 		/* if dp is the starting directory and RESOLVE_BENEATH, we should return ENOTCAPABLE */
1397 		if ((ndp->ni_flag & NAMEI_RESOLVE_BENEATH) && (dp == ndp->ni_usedvp)) {
1398 			error = ENOTCAPABLE;
1399 			goto bad;
1400 		}
1401 		/* return ENOTCAPABLE if '..' path traversal is prohibited */
1402 		if ((ndp->ni_flag & NAMEI_NODOTDOT)) {
1403 			error = ENOTCAPABLE;
1404 			goto bad;
1405 		}
1406 		/*
1407 		 * if this is a chroot'ed process, check if the current
1408 		 * directory is still a subdirectory of the process's
1409 		 * root directory.
1410 		 */
1411 		if (ndp->ni_rootdir && (ndp->ni_rootdir != rootvnode) &&
1412 		    dp != ndp->ni_rootdir) {
1413 			int sdir_error;
1414 			int is_subdir = FALSE;
1415 
1416 			sdir_error = vnode_issubdir(dp, ndp->ni_rootdir,
1417 			    &is_subdir, vfs_context_kernel());
1418 
1419 			/*
1420 			 * If we couldn't determine if dp is a subdirectory of
1421 			 * ndp->ni_rootdir (sdir_error != 0), we let the request
1422 			 * proceed.
1423 			 */
1424 			if (!sdir_error && !is_subdir) {
1425 				vnode_put(dp);
1426 				dp = ndp->ni_rootdir;
1427 				/*
1428 				 * There's a ref on the process's root directory
1429 				 * but we can't use vnode_getwithref here as
1430 				 * there is nothing preventing that ref being
1431 				 * released by another thread.
1432 				 */
1433 				if (vnode_get(dp)) {
1434 					dp = NULLVP;
1435 					error = ENOENT;
1436 					goto bad;
1437 				}
1438 			}
1439 		}
1440 
1441 		for (;;) {
1442 			if (dp == ndp->ni_rootdir || dp == rootvnode) {
1443 				ndp->ni_dvp = dp;
1444 				ndp->ni_vp = dp;
1445 				/*
1446 				 * we're pinned at the root
1447 				 * we've already got one reference on 'dp'
1448 				 * courtesy of cache_lookup_path... take
1449 				 * another one for the ".."
1450 				 * if we fail to get the new reference, we'll
1451 				 * drop our original down in 'bad'
1452 				 */
1453 				if (vnode_get(dp)) {
1454 					error = ENOENT;
1455 					goto bad;
1456 				}
1457 				atroot = 1;
1458 				goto returned_from_lookup_path;
1459 			}
1460 			if ((dp->v_flag & VROOT) == 0 ||
1461 			    (cnp->cn_flags & NOCROSSMOUNT)) {
1462 				break;
1463 			}
1464 			if (dp->v_mount == NULL) {      /* forced umount */
1465 				error = EBADF;
1466 				goto bad;
1467 			}
1468 			tdp = dp;
1469 			dp = tdp->v_mount->mnt_vnodecovered;
1470 
1471 			if ((vnode_getwithref(dp))) {
1472 				vnode_put(tdp);
1473 				dp = NULLVP;
1474 				error = ENOENT;
1475 				goto bad;
1476 			}
1477 
1478 			vnode_put(tdp);
1479 
1480 			ndp->ni_dvp = dp;
1481 			dp_authorized = 0;
1482 		}
1483 	}
1484 
1485 	/*
1486 	 * We now have a segment name to search for, and a directory to search.
1487 	 */
1488 #if CONFIG_UNION_MOUNTS
1489 unionlookup:
1490 #endif /* CONFIG_UNION_MOUNTS */
1491 	ndp->ni_vp = NULLVP;
1492 
1493 	if (dp->v_type != VDIR) {
1494 #if CONFIG_MACF
1495 		/*
1496 		 * Prevent the information disclosure on the vnode
1497 		 */
1498 		if (mac_vnode_check_stat(ctx, NOCRED, dp) == EPERM) {
1499 			error = EPERM;
1500 			goto lookup_error;
1501 		}
1502 #endif /* CONFIG_MACF */
1503 		error = ENOTDIR;
1504 		goto lookup_error;
1505 	}
1506 	if ((cnp->cn_flags & DONOTAUTH) != DONOTAUTH) {
1507 		error = lookup_authorize_search(dp, cnp, dp_authorized, ctx);
1508 		if (error) {
1509 			goto lookup_error;
1510 		}
1511 	}
1512 
1513 	/*
1514 	 * Now that we've authorized a lookup, can bail out if the filesystem
1515 	 * will be doing a batched operation.  Return an iocount on dvp.
1516 	 */
1517 #if NAMEDRSRCFORK
1518 	if ((cnp->cn_flags & ISLASTCN) && namei_compound_available(dp, ndp) && !(cnp->cn_flags & CN_WANTSRSRCFORK)) {
1519 #else
1520 	if ((cnp->cn_flags & ISLASTCN) && namei_compound_available(dp, ndp)) {
1521 #endif /* NAMEDRSRCFORK */
1522 		ndp->ni_flag |= NAMEI_UNFINISHED;
1523 		ndp->ni_ncgeneration = dp->v_nc_generation;
1524 		return 0;
1525 	}
1526 
1527 	nc_generation = dp->v_nc_generation;
1528 
1529 	/*
1530 	 * Note:
1531 	 * Filesystems that support hardlinks may want to call vnode_update_identity
1532 	 * if the lookup operation below will modify the in-core vnode to belong to a new point
1533 	 * in the namespace.  VFS cannot infer whether or not the look up operation makes the vnode
1534 	 * name change or change parents.  Without this, the lookup may make update
1535 	 * filesystem-specific in-core metadata but fail to update the v_parent or v_name
1536 	 * fields in the vnode.  If VFS were to do this, it would be necessary to call
1537 	 * vnode_update_identity on every lookup operation -- expensive!
1538 	 *
1539 	 * However, even with this in place, multiple lookups may occur in between this lookup
1540 	 * and the subsequent vnop, so, at best, we could only guarantee that you would get a
1541 	 * valid path back, and not necessarily the one that you wanted.
1542 	 *
1543 	 * Example:
1544 	 * /tmp/a == /foo/b
1545 	 *
1546 	 * If you are now looking up /foo/b and the vnode for this link represents /tmp/a,
1547 	 * vnode_update_identity will fix the parentage so that you can get /foo/b back
1548 	 * through the v_parent chain (preventing you from getting /tmp/b back). It would
1549 	 * not fix whether or not you should or should not get /tmp/a vs. /foo/b.
1550 	 */
1551 
1552 	error = VNOP_LOOKUP(dp, &ndp->ni_vp, cnp, ctx);
1553 
1554 	if (error) {
1555 lookup_error:
1556 #if CONFIG_UNION_MOUNTS
1557 		if ((error == ENOENT) &&
1558 		    (dp->v_mount != NULL) &&
1559 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
1560 			tdp = dp;
1561 			error = lookup_traverse_union(tdp, &dp, ctx);
1562 			vnode_put(tdp);
1563 			if (error) {
1564 				dp = NULLVP;
1565 				goto bad;
1566 			}
1567 
1568 			ndp->ni_dvp = dp;
1569 			dp_authorized = 0;
1570 			goto unionlookup;
1571 		}
1572 #endif /* CONFIG_UNION_MOUNTS */
1573 
1574 		if (error != EJUSTRETURN) {
1575 			goto bad;
1576 		}
1577 
1578 		if (ndp->ni_vp != NULLVP) {
1579 			panic("leaf should be empty");
1580 		}
1581 
1582 #if NAMEDRSRCFORK
1583 		/*
1584 		 * At this point, error should be EJUSTRETURN.
1585 		 *
1586 		 * If CN_WANTSRSRCFORK is set, that implies that the
1587 		 * underlying filesystem could not find the "parent" of the
1588 		 * resource fork (the data fork), and we are doing a lookup
1589 		 * for a CREATE event.
1590 		 *
1591 		 * However, this should be converted to an error, as the
1592 		 * failure to find this parent should disallow further
1593 		 * progress to try and acquire a resource fork vnode.
1594 		 */
1595 		if (cnp->cn_flags & CN_WANTSRSRCFORK) {
1596 			error = ENOENT;
1597 			goto bad;
1598 		}
1599 #endif
1600 
1601 		error = lookup_validate_creation_path(ndp);
1602 		if (error) {
1603 			goto bad;
1604 		}
1605 		/*
1606 		 * We return with ni_vp NULL to indicate that the entry
1607 		 * doesn't currently exist, leaving a pointer to the
1608 		 * referenced directory vnode in ndp->ni_dvp.
1609 		 */
1610 		if (cnp->cn_flags & SAVESTART) {
1611 			if ((vnode_get(ndp->ni_dvp))) {
1612 				error = ENOENT;
1613 				goto bad;
1614 			}
1615 			ndp->ni_startdir = ndp->ni_dvp;
1616 		}
1617 		if (!wantparent) {
1618 			vnode_put(ndp->ni_dvp);
1619 		}
1620 
1621 		if (kdebug_enable) {
1622 			kdebug_lookup(ndp->ni_dvp, cnp);
1623 		}
1624 		return 0;
1625 	}
1626 returned_from_lookup_path:
1627 	/* We'll always have an iocount on ni_vp when this finishes. */
1628 	error = lookup_handle_found_vnode(ndp, cnp, rdonly, vbusyflags, &keep_going, nc_generation, wantparent, atroot, ctx);
1629 	if (error != 0) {
1630 		goto bad2;
1631 	}
1632 
1633 	if (keep_going) {
1634 		dp = ndp->ni_vp;
1635 
1636 		/* namei() will handle symlinks */
1637 		if ((dp->v_type == VLNK) &&
1638 		    ((cnp->cn_flags & FOLLOW) || (ndp->ni_flag & NAMEI_TRAILINGSLASH) || *ndp->ni_next == '/')) {
1639 			return 0;
1640 		}
1641 
1642 		/*
1643 		 * Otherwise, there's more path to process.
1644 		 * cache_lookup_path is now responsible for dropping io ref on dp
1645 		 * when it is called again in the dirloop.  This ensures we hold
1646 		 * a ref on dp until we complete the next round of lookup.
1647 		 */
1648 		last_dp = dp;
1649 
1650 		goto dirloop;
1651 	}
1652 
1653 	return 0;
1654 bad2:
1655 	if (ndp->ni_dvp) {
1656 		vnode_put(ndp->ni_dvp);
1657 	}
1658 
1659 	vnode_put(ndp->ni_vp);
1660 	ndp->ni_vp = NULLVP;
1661 
1662 	if (kdebug_enable) {
1663 		kdebug_lookup(dp, cnp);
1664 	}
1665 	return error;
1666 
1667 bad:
1668 	if (dp) {
1669 		vnode_put(dp);
1670 	}
1671 	ndp->ni_vp = NULLVP;
1672 
1673 	if (kdebug_enable) {
1674 		kdebug_lookup(dp, cnp);
1675 	}
1676 	return error;
1677 }
1678 
1679 #if CONFIG_UNION_MOUNTS
1680 /*
1681  * Given a vnode in a union mount, traverse to the equivalent
1682  * vnode in the underlying mount.
1683  */
1684 int
1685 lookup_traverse_union(vnode_t dvp, vnode_t *new_dvp, vfs_context_t ctx)
1686 {
1687 	char *path = NULL, *pp;
1688 	const char *name, *np;
1689 	size_t len;
1690 	int error = 0;
1691 	struct nameidata nd;
1692 	vnode_t vp = dvp;
1693 
1694 	*new_dvp = NULL;
1695 
1696 	if (vp && vp->v_flag & VROOT) {
1697 		*new_dvp = vp->v_mount->mnt_vnodecovered;
1698 		if (vnode_getwithref(*new_dvp)) {
1699 			return ENOENT;
1700 		}
1701 		return 0;
1702 	}
1703 
1704 	path = namei_alloc(MAXPATHLEN);
1705 
1706 	/*
1707 	 * Walk back up to the mountpoint following the
1708 	 * v_parent chain and build a slash-separated path.
1709 	 * Then lookup that path starting with the covered vnode.
1710 	 */
1711 	pp = path + (MAXPATHLEN - 1);
1712 	*pp = '\0';
1713 
1714 	while (1) {
1715 		name = vnode_getname(vp);
1716 		if (name == NULL) {
1717 			printf("lookup_traverse_union: null parent name: .%s\n", pp);
1718 			error = ENOENT;
1719 			goto done;
1720 		}
1721 		len = strlen(name);
1722 		if ((len + 1) > (size_t)(pp - path)) {          // Enough space for this name ?
1723 			error = ENAMETOOLONG;
1724 			vnode_putname(name);
1725 			goto done;
1726 		}
1727 		for (np = name + len; len > 0; len--) { // Copy name backwards
1728 			*--pp = *--np;
1729 		}
1730 		vnode_putname(name);
1731 		vp = vp->v_parent;
1732 		if (vp == NULLVP || vp->v_flag & VROOT) {
1733 			break;
1734 		}
1735 		*--pp = '/';
1736 	}
1737 
1738 	/* Evaluate the path in the underlying mount */
1739 	NDINIT(&nd, LOOKUP, OP_LOOKUP, USEDVP, UIO_SYSSPACE, CAST_USER_ADDR_T(pp), ctx);
1740 	nd.ni_dvp = dvp->v_mount->mnt_vnodecovered;
1741 	error = namei(&nd);
1742 	if (error == 0) {
1743 		*new_dvp = nd.ni_vp;
1744 	}
1745 	nameidone(&nd);
1746 done:
1747 	if (path) {
1748 		namei_free(path, MAXPATHLEN);
1749 	}
1750 	return error;
1751 }
1752 #endif /* CONFIG_UNION_MOUNTS */
1753 
1754 int
1755 lookup_validate_creation_path(struct nameidata *ndp)
1756 {
1757 	struct componentname *cnp = &ndp->ni_cnd;
1758 
1759 	/*
1760 	 * If creating and at end of pathname, then can consider
1761 	 * allowing file to be created.
1762 	 */
1763 	if (cnp->cn_flags & RDONLY) {
1764 		return EROFS;
1765 	}
1766 	if ((cnp->cn_flags & ISLASTCN) && (ndp->ni_flag & NAMEI_TRAILINGSLASH) && !(cnp->cn_flags & WILLBEDIR)) {
1767 		return ENOENT;
1768 	}
1769 
1770 	return 0;
1771 }
1772 
1773 /*
1774  * Modifies only ni_vp.  Always returns with ni_vp still valid (iocount held).
1775  */
1776 static int
1777 lookup_traverse_mountpoints(struct nameidata *ndp, struct componentname *cnp, vnode_t dp,
1778     int vbusyflags, vfs_context_t ctx)
1779 {
1780 	mount_t mp;
1781 	vnode_t tdp;
1782 	int error = 0;
1783 	uint32_t depth = 0;
1784 	vnode_t mounted_on_dp;
1785 	int current_mount_generation = 0;
1786 #if CONFIG_TRIGGERS
1787 	vnode_t triggered_dp = NULLVP;
1788 	int retry_cnt = 0;
1789 #define MAX_TRIGGER_RETRIES 1
1790 #endif
1791 
1792 	if (dp->v_type != VDIR || cnp->cn_flags & NOCROSSMOUNT) {
1793 		return 0;
1794 	}
1795 
1796 	mounted_on_dp = dp;
1797 #if CONFIG_TRIGGERS
1798 restart:
1799 #endif
1800 	current_mount_generation = mount_generation;
1801 
1802 	while (dp->v_mountedhere) {
1803 		vnode_lock_spin(dp);
1804 		if ((mp = dp->v_mountedhere)) {
1805 			mp->mnt_crossref++;
1806 			vnode_unlock(dp);
1807 		} else {
1808 			vnode_unlock(dp);
1809 			break;
1810 		}
1811 
1812 		if (ISSET(mp->mnt_lflag, MNT_LFORCE)) {
1813 			mount_dropcrossref(mp, dp, 0);
1814 			break;  // don't traverse into a forced unmount
1815 		}
1816 
1817 		if ((ndp->ni_flag & NAMEI_LOCAL) && !(mp->mnt_flag & MNT_LOCAL)) {
1818 			/* Prevent a path lookup from ever crossing into a network filesystem */
1819 			error = ENOTCAPABLE;
1820 			goto out;
1821 		}
1822 		if ((ndp->ni_flag & NAMEI_NODEVFS) && (strcmp(mp->mnt_vfsstat.f_fstypename, "devfs") == 0)) {
1823 			/* Prevent a path lookup into `devfs` filesystem */
1824 			error = ENOTCAPABLE;
1825 			goto out;
1826 		}
1827 		if ((ndp->ni_flag & NAMEI_IMMOVABLE) && (mp->mnt_flag & MNT_REMOVABLE) && !(mp->mnt_kern_flag & MNTK_VIRTUALDEV)) {
1828 			/* Prevent a path lookup into a removable filesystem */
1829 			error = ENOTCAPABLE;
1830 			goto out;
1831 		}
1832 
1833 		if (vfs_busy(mp, vbusyflags)) {
1834 			mount_dropcrossref(mp, dp, 0);
1835 			if (vbusyflags == LK_NOWAIT) {
1836 				error = ENOENT;
1837 				goto out;
1838 			}
1839 
1840 			continue;
1841 		}
1842 
1843 		error = VFS_ROOT(mp, &tdp, ctx);
1844 
1845 		mount_dropcrossref(mp, dp, 0);
1846 		vfs_unbusy(mp);
1847 
1848 		if (error) {
1849 			goto out;
1850 		}
1851 
1852 		vnode_put(dp);
1853 		ndp->ni_vp = dp = tdp;
1854 		if (dp->v_type != VDIR) {
1855 #if DEVELOPMENT || DEBUG
1856 			panic("%s : Root of filesystem not a directory",
1857 			    __FUNCTION__);
1858 #else
1859 			break;
1860 #endif
1861 		}
1862 		depth++;
1863 	}
1864 
1865 #if CONFIG_TRIGGERS
1866 	/*
1867 	 * The triggered_dp check here is required but is susceptible to a
1868 	 * (unlikely) race in which trigger mount is done from here and is
1869 	 * unmounted before we get past vfs_busy above. We retry to deal with
1870 	 * that case but it has the side effect of unwanted retries for
1871 	 * "special" processes which don't want to trigger mounts.
1872 	 */
1873 	if (dp->v_resolve && retry_cnt < MAX_TRIGGER_RETRIES) {
1874 		error = vnode_trigger_resolve(dp, ndp, ctx);
1875 		if (error) {
1876 			goto out;
1877 		}
1878 		if (dp == triggered_dp) {
1879 			retry_cnt += 1;
1880 		} else {
1881 			retry_cnt = 0;
1882 		}
1883 		triggered_dp = dp;
1884 		goto restart;
1885 	}
1886 #endif /* CONFIG_TRIGGERS */
1887 
1888 	if (depth) {
1889 		mp = mounted_on_dp->v_mountedhere;
1890 
1891 		if (mp) {
1892 			mount_lock_spin(mp);
1893 			mp->mnt_realrootvp_vid = dp->v_id;
1894 			mp->mnt_realrootvp = dp;
1895 			mp->mnt_generation = current_mount_generation;
1896 			mount_unlock(mp);
1897 		}
1898 	}
1899 
1900 	return 0;
1901 
1902 out:
1903 	return error;
1904 }
1905 
1906 /*
1907  * Takes ni_vp and ni_dvp non-NULL.  Returns with *new_dp set to the location
1908  * at which to start a lookup with a resolved path, and all other iocounts dropped.
1909  */
1910 static int
1911 lookup_handle_symlink(struct nameidata *ndp, vnode_t *new_dp, bool *new_dp_has_iocount, vfs_context_t ctx)
1912 {
1913 	int error;
1914 	char *cp = NULL;               /* pointer into pathname argument */
1915 	u_int cplen = 0;
1916 	uio_t auio;
1917 	UIO_STACKBUF(uio_buf, 1);
1918 	int need_newpathbuf;
1919 	u_int linklen = 0;
1920 	struct componentname *cnp = &ndp->ni_cnd;
1921 	vnode_t dp;
1922 	char *tmppn;
1923 	u_int rsrclen = (cnp->cn_flags & CN_WANTSRSRCFORK) ? sizeof(_PATH_RSRCFORKSPEC) : 0;
1924 	bool dp_has_iocount = false;
1925 
1926 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
1927 #if CONFIG_MACF
1928 		if (mac_vnode_check_stat(ctx, NOCRED, ndp->ni_vp) == EPERM) {
1929 			return EPERM;
1930 		}
1931 #endif /* CONFIG_MACF */
1932 		return ELOOP;
1933 	}
1934 #if CONFIG_MACF
1935 	if ((error = mac_vnode_check_readlink(ctx, ndp->ni_vp)) != 0) {
1936 		return error;
1937 	}
1938 #endif /* MAC */
1939 	if (ndp->ni_pathlen > 1 || !(cnp->cn_flags & HASBUF)) {
1940 		need_newpathbuf = 1;
1941 	} else {
1942 		need_newpathbuf = 0;
1943 	}
1944 
1945 	if (need_newpathbuf) {
1946 		if (!(cnp->cn_flags & HASBUF) || cnp->cn_pnlen == MAXPATHLEN) {
1947 			cplen = MAXPATHLEN;
1948 		} else {
1949 			assert(proc_support_long_paths(vfs_context_proc(ctx)));
1950 			cplen = cnp->cn_pnlen;
1951 		}
1952 		cp = namei_alloc(cplen);
1953 	} else {
1954 		cp = cnp->cn_pnbuf;
1955 	}
1956 	auio = uio_createwithbuffer(1, 0, UIO_SYSSPACE, UIO_READ, &uio_buf[0], sizeof(uio_buf));
1957 
1958 	uio_addiov(auio, CAST_USER_ADDR_T(cp), MAXPATHLEN);
1959 
1960 	error = VNOP_READLINK(ndp->ni_vp, auio, ctx);
1961 
1962 	if (!error) {
1963 		user_ssize_t resid = uio_resid(auio);
1964 
1965 		assert(resid <= MAXPATHLEN);
1966 
1967 		if (resid == MAXPATHLEN) {
1968 			linklen = 0;
1969 		} else {
1970 			/*
1971 			 * Safe to set unsigned with a [larger] signed type here
1972 			 * because 0 <= uio_resid <= MAXPATHLEN and MAXPATHLEN
1973 			 * is only 1024.
1974 			 */
1975 			linklen = (u_int)strnlen(cp, MAXPATHLEN - (u_int)resid);
1976 		}
1977 
1978 		size_t maxlen = proc_support_long_paths(vfs_context_proc(ctx)) ? MAXLONGPATHLEN : MAXPATHLEN;
1979 
1980 		if (linklen == 0) {
1981 			error = ENOENT;
1982 		} else if (linklen + ndp->ni_pathlen + rsrclen > maxlen) {
1983 			error = ENAMETOOLONG;
1984 		}
1985 	}
1986 
1987 	if (error) {
1988 		if (need_newpathbuf) {
1989 			namei_free(cp, cplen);
1990 		}
1991 		return error;
1992 	}
1993 
1994 	if (need_newpathbuf) {
1995 		tmppn = cnp->cn_pnbuf;
1996 		u_int tmplen = cnp->cn_pnlen;
1997 		bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
1998 		cnp->cn_pnbuf = cp;
1999 		cnp->cn_pnlen = cplen;
2000 
2001 		if ((cnp->cn_flags & HASBUF)) {
2002 			namei_free(tmppn, tmplen);
2003 		} else {
2004 			cnp->cn_flags |= HASBUF;
2005 		}
2006 	} else {
2007 		cnp->cn_pnbuf[linklen] = '\0';
2008 	}
2009 
2010 	ndp->ni_pathlen += linklen;
2011 	cnp->cn_nameptr = cnp->cn_pnbuf;
2012 
2013 	/*
2014 	 * starting point for 'relative'
2015 	 * symbolic link path
2016 	 */
2017 	dp = ndp->ni_dvp;
2018 
2019 	/*
2020 	 * get rid of reference returned via 'lookup'
2021 	 * ni_dvp is released only if we restart at /.
2022 	 */
2023 	vnode_put(ndp->ni_vp);
2024 	ndp->ni_vp = NULLVP;
2025 	ndp->ni_dvp = NULLVP;
2026 
2027 	dp_has_iocount = true;
2028 
2029 	/*
2030 	 * Check if symbolic link restarts us at the root
2031 	 */
2032 	if (*(cnp->cn_nameptr) == '/') {
2033 		/* return ENOTCAPABLE if resolve beneath and the symlink restarts at root */
2034 		if (ndp->ni_flag & NAMEI_RESOLVE_BENEATH) {
2035 			vnode_put(dp); /* ALWAYS have a dvp for a symlink */
2036 			return ENOTCAPABLE;
2037 		}
2038 		while (*(cnp->cn_nameptr) == '/') {
2039 			cnp->cn_nameptr++;
2040 			ndp->ni_pathlen--;
2041 		}
2042 		if (linklen != 0) {
2043 			vnode_put(dp); /* ALWAYS have a dvp for a symlink */
2044 			dp_has_iocount = false;
2045 			if ((dp = ndp->ni_rootdir) == NULLVP) {
2046 				return ENOENT;
2047 			}
2048 		}
2049 	}
2050 
2051 	*new_dp = dp;
2052 	*new_dp_has_iocount = dp_has_iocount;
2053 
2054 	return 0;
2055 }
2056 
2057 /*
2058  * relookup - lookup a path name component
2059  *    Used by lookup to re-aquire things.
2060  */
2061 int
2062 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
2063 {
2064 	struct vnode *dp = NULL;                /* the directory we are searching */
2065 	int wantparent;                 /* 1 => wantparent or lockparent flag */
2066 	int rdonly;                     /* lookup read-only flag bit */
2067 	int error = 0;
2068 #ifdef NAMEI_DIAGNOSTIC
2069 	int i, newhash;                 /* DEBUG: check name hash */
2070 	char *cp;                       /* DEBUG: check name ptr/len */
2071 #endif
2072 	vfs_context_t ctx = cnp->cn_context;
2073 
2074 	/*
2075 	 * Setup: break out flag bits into variables.
2076 	 */
2077 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
2078 	rdonly = cnp->cn_flags & RDONLY;
2079 	cnp->cn_flags &= ~ISSYMLINK;
2080 
2081 	if (cnp->cn_flags & NOCACHE) {
2082 		cnp->cn_flags &= ~MAKEENTRY;
2083 	} else {
2084 		cnp->cn_flags |= MAKEENTRY;
2085 	}
2086 
2087 	dp = dvp;
2088 
2089 	/*
2090 	 * Check for degenerate name (e.g. / or "")
2091 	 * which is a way of talking about a directory,
2092 	 * e.g. like "/." or ".".
2093 	 */
2094 	if (cnp->cn_nameptr[0] == '\0') {
2095 		if (cnp->cn_nameiop != LOOKUP || wantparent) {
2096 			error = EISDIR;
2097 			goto bad;
2098 		}
2099 		if (dp->v_type != VDIR) {
2100 			error = ENOTDIR;
2101 			goto bad;
2102 		}
2103 		if ((vnode_get(dp))) {
2104 			error = ENOENT;
2105 			goto bad;
2106 		}
2107 		*vpp = dp;
2108 
2109 		if (cnp->cn_flags & SAVESTART) {
2110 			panic("lookup: SAVESTART");
2111 		}
2112 		return 0;
2113 	}
2114 	/*
2115 	 * We now have a segment name to search for, and a directory to search.
2116 	 */
2117 	if ((error = VNOP_LOOKUP(dp, vpp, cnp, ctx))) {
2118 		if (error != EJUSTRETURN) {
2119 			goto bad;
2120 		}
2121 #if DIAGNOSTIC
2122 		if (*vpp != NULL) {
2123 			panic("leaf should be empty");
2124 		}
2125 #endif
2126 		/*
2127 		 * If creating and at end of pathname, then can consider
2128 		 * allowing file to be created.
2129 		 */
2130 		if (rdonly) {
2131 			error = EROFS;
2132 			goto bad;
2133 		}
2134 		/*
2135 		 * We return with ni_vp NULL to indicate that the entry
2136 		 * doesn't currently exist, leaving a pointer to the
2137 		 * (possibly locked) directory inode in ndp->ni_dvp.
2138 		 */
2139 		return 0;
2140 	}
2141 	dp = *vpp;
2142 
2143 #if DIAGNOSTIC
2144 	/*
2145 	 * Check for symbolic link
2146 	 */
2147 	if (dp->v_type == VLNK && (cnp->cn_flags & FOLLOW)) {
2148 		panic("relookup: symlink found.");
2149 	}
2150 #endif
2151 
2152 	/*
2153 	 * Disallow directory write attempts on read-only file systems.
2154 	 */
2155 	if (rdonly &&
2156 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
2157 		error = EROFS;
2158 		goto bad2;
2159 	}
2160 	/* ASSERT(dvp == ndp->ni_startdir) */
2161 
2162 	return 0;
2163 
2164 bad2:
2165 	vnode_put(dp);
2166 bad:
2167 	*vpp = NULL;
2168 
2169 	return error;
2170 }
2171 
2172 /*
2173  * Free pathname buffer
2174  */
2175 void
2176 nameidone(struct nameidata *ndp)
2177 {
2178 	if (ndp->ni_cnd.cn_flags & HASBUF) {
2179 		char *tmp = ndp->ni_cnd.cn_pnbuf;
2180 
2181 		ndp->ni_cnd.cn_pnbuf = NULL;
2182 		ndp->ni_cnd.cn_flags &= ~HASBUF;
2183 		namei_free(tmp, ndp->ni_cnd.cn_pnlen);
2184 	}
2185 }
2186 
2187 
2188 /*
2189  * Log (part of) a pathname using kdebug, as used by fs_usage.  The path up to
2190  * and including the current component name are logged.  Up to NUMPARMS * 4
2191  * bytes of pathname will be logged.  If the path to be logged is longer than
2192  * that, then the last NUMPARMS * 4 bytes are logged. That is, the truncation
2193  * removes the leading portion of the path.
2194  *
2195  * The logging is done via multiple KDBG_RELEASE calls.  The first one is marked
2196  * with DBG_FUNC_START.  The last one is marked with DBG_FUNC_END (in addition
2197  * to DBG_FUNC_START if it is also the first).  There may be intermediate ones
2198  * with neither DBG_FUNC_START nor DBG_FUNC_END.
2199  *
2200  * The first event passes the vnode pointer and 24 or 32 (on K32, 12 or 24)
2201  * bytes of pathname.  The remaining events add 32 (on K32, 16) bytes of
2202  * pathname each.  The minimum number of events required to pass the path are
2203  * used.  Any excess padding in the final event (because not all of the 24 or 32
2204  * (on K32, 12 or 16) bytes are needed for the remainder of the path) is set to
2205  * zero bytes, or '>' if there is more path beyond the current component name
2206  * (usually because an intermediate component was not found).
2207  *
2208  * NOTE: If the path length is greater than NUMPARMS * 4, or is not of the form
2209  * 24 + N * 32 (or on K32, 12 + N * 16), there will be no padding.
2210  */
2211 #if (KDEBUG_LEVEL >= KDEBUG_LEVEL_IST)
2212 
2213 void
2214 kdebug_vfs_lookup(const char *path, size_t path_len, void *vnp,
2215     uint32_t flags)
2216 {
2217 	unsigned long path_words[4] = {};
2218 	size_t trace_len = MIN(sizeof(path_words) - sizeof(path_words[0]), path_len);
2219 	size_t path_next = 0;
2220 	bool noprocfilt = flags & KDBG_VFS_LOOKUP_FLAG_NOPROCFILT;
2221 
2222 	assert(path_len >= 0);
2223 
2224 	int code = ((flags & KDBG_VFS_LOOKUP_FLAG_LOOKUP) ? VFS_LOOKUP :
2225 	    VFS_LOOKUP_DONE) | DBG_FUNC_START;
2226 
2227 	if (path_len <= (3 * (int)sizeof(long))) {
2228 		code |= DBG_FUNC_END;
2229 	}
2230 	memcpy(path_words, path, trace_len);
2231 	path_next += trace_len;
2232 
2233 	if (noprocfilt) {
2234 		KDBG_RELEASE_NOPROCFILT(code, kdebug_vnode(vnp), path_words[0],
2235 		    path_words[1], path_words[2]);
2236 	} else {
2237 		KDBG_RELEASE(code, kdebug_vnode(vnp), path_words[0], path_words[1],
2238 		    path_words[2]);
2239 	}
2240 
2241 	code &= ~DBG_FUNC_START;
2242 
2243 	for (int i = 3; i * (int)sizeof(long) < path_len; i += 4) {
2244 		trace_len = sizeof(path_words);
2245 		if ((i + 4) * (int)sizeof(long) >= path_len) {
2246 			code |= DBG_FUNC_END;
2247 			trace_len = path_len - path_next;
2248 			memset(path_words, 0, sizeof(path_words));
2249 		}
2250 		memcpy(path_words, &path[path_next], trace_len);
2251 		path_next += trace_len;
2252 
2253 		if (noprocfilt) {
2254 			KDBG_RELEASE_NOPROCFILT(code, path_words[0], path_words[1],
2255 			    path_words[2], path_words[3]);
2256 		} else {
2257 			KDBG_RELEASE(code, path_words[0], path_words[1],
2258 			    path_words[2], path_words[3]);
2259 		}
2260 	}
2261 }
2262 
2263 void
2264 kdebug_lookup_gen_events(long *path_words, int path_len, void *vnp, bool lookup)
2265 {
2266 	assert(path_len >= 0);
2267 	kdebug_vfs_lookup((const char *)path_words, path_len, vnp,
2268 	    lookup ? KDBG_VFS_LOOKUP_FLAG_LOOKUP : 0);
2269 }
2270 
2271 void
2272 kdebug_lookup(vnode_t vnp, struct componentname *cnp)
2273 {
2274 	kdebug_vfs_lookup(cnp->cn_pnbuf, strnlen(cnp->cn_pnbuf, cnp->cn_pnlen), vnp, KDBG_VFS_LOOKUP_FLAG_LOOKUP);
2275 }
2276 
2277 #else /* (KDEBUG_LEVEL >= KDEBUG_LEVEL_IST) */
2278 
2279 void
2280 kdebug_vfs_lookup(const char *dbg_parms __unused, size_t dbg_namelen __unused,
2281     void *dp __unused, __unused kdebug_vfs_lookup_flags_t flags)
2282 {
2283 }
2284 
2285 static void
2286 kdebug_lookup(struct vnode *dp __unused, struct componentname *cnp __unused)
2287 {
2288 }
2289 #endif /* (KDEBUG_LEVEL >= KDEBUG_LEVEL_IST) */
2290 
2291 int
2292 vfs_getbyid(fsid_t *fsid, ino64_t ino, vnode_t *vpp, vfs_context_t ctx)
2293 {
2294 	mount_t mp;
2295 	int error;
2296 
2297 	mp = mount_lookupby_volfsid(fsid->val[0], 1);
2298 	if (mp == NULL) {
2299 		return EINVAL;
2300 	}
2301 
2302 	/* Get the target vnode. */
2303 	if (ino == 2) {
2304 		error = VFS_ROOT(mp, vpp, ctx);
2305 	} else {
2306 		error = VFS_VGET(mp, ino, vpp, ctx);
2307 	}
2308 
2309 	vfs_unbusy(mp);
2310 	return error;
2311 }
2312 /*
2313  * Obtain the real path from a legacy volfs style path.
2314  *
2315  * Valid formats of input path:
2316  *
2317  *	"555/@"
2318  *	"555/2"
2319  *	"555/123456"
2320  *	"555/123456/foobar"
2321  *
2322  * Where:
2323  *	555 represents the volfs file system id
2324  *	'@' and '2' are aliases to the root of a file system
2325  *	123456 represents a file id
2326  *	"foobar" represents a file name
2327  */
2328 #if CONFIG_VOLFS
2329 static int
2330 vfs_getrealpath(const char * path, char * realpath, size_t bufsize, vfs_context_t ctx, vnode_t rdvp)
2331 {
2332 	vnode_t vp;
2333 	struct mount *mp = NULL;
2334 	char  *str;
2335 	char ch;
2336 	unsigned long id;
2337 	ino64_t ino;
2338 	int error;
2339 	int length;
2340 
2341 	/* Get file system id and move str to next component. */
2342 	id = strtoul(path, &str, 10);
2343 	if (id == 0 || str[0] != '/') {
2344 		return EINVAL;
2345 	}
2346 	while (*str == '/') {
2347 		str++;
2348 	}
2349 	ch = *str;
2350 
2351 	if (id > INT_MAX) {
2352 		return ENOENT;
2353 	}
2354 	mp = mount_lookupby_volfsid((int)id, 1);
2355 	if (mp == NULL) {
2356 		return EINVAL;  /* unexpected failure */
2357 	}
2358 	/* Check for an alias to a file system root. */
2359 	if (ch == '@' && str[1] == '\0') {
2360 		ino = 2;
2361 		str++;
2362 	} else {
2363 		/* Get file id and move str to next component. */
2364 		ino = strtouq(str, &str, 10);
2365 	}
2366 
2367 	/* Get the target vnode. */
2368 	if (ino == 2) {
2369 		struct vfs_attr vfsattr;
2370 		int use_vfs_root = TRUE;
2371 
2372 		VFSATTR_INIT(&vfsattr);
2373 		VFSATTR_WANTED(&vfsattr, f_capabilities);
2374 		if (vfs_getattr(mp, &vfsattr, vfs_context_kernel()) == 0 &&
2375 		    VFSATTR_IS_SUPPORTED(&vfsattr, f_capabilities)) {
2376 			if ((vfsattr.f_capabilities.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_VOL_GROUPS) &&
2377 			    (vfsattr.f_capabilities.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_VOL_GROUPS)) {
2378 				use_vfs_root = FALSE;
2379 			}
2380 		}
2381 
2382 		if (use_vfs_root) {
2383 			error = VFS_ROOT(mp, &vp, ctx);
2384 		} else {
2385 			error = VFS_VGET(mp, ino, &vp, ctx);
2386 		}
2387 	} else {
2388 		error = VFS_VGET(mp, ino, &vp, ctx);
2389 	}
2390 	vfs_unbusy(mp);
2391 	if (error) {
2392 		goto out;
2393 	}
2394 	realpath[0] = '\0';
2395 
2396 	/* Check for and fail if the path is not under the chroot */
2397 	if (rdvp != NULLVP) {
2398 		int is_subdir = 0;
2399 		vnode_t pvp = NULLVP;
2400 
2401 		/* Get the parent if vp is not a directory */
2402 		if (!vnode_isdir(vp) && !(pvp = vnode_getparent(vp))) {
2403 			error = EINVAL;
2404 			vnode_put(vp);
2405 			goto out;
2406 		}
2407 
2408 		/* Check if a given directory vp/pvp is a subdirectory of rdvp */
2409 		error = vnode_issubdir(pvp ? pvp : vp, rdvp, &is_subdir, ctx);
2410 		if (pvp) {
2411 			vnode_put(pvp);
2412 		}
2413 		if (error || !is_subdir) {
2414 			if (!error) {
2415 				/* Path is not under the chroot */
2416 				error = EINVAL;
2417 			}
2418 			vnode_put(vp);
2419 			goto out;
2420 		}
2421 	}
2422 
2423 	/* Get the absolute path to this vnode. */
2424 	error = build_path(vp, realpath, (int)bufsize, &length, 0, ctx);
2425 	vnode_put(vp);
2426 
2427 	if (error == 0 && *str != '\0') {
2428 		size_t attempt = strlcat(realpath, str, MAXPATHLEN);
2429 		if (attempt > MAXPATHLEN) {
2430 			error = ENAMETOOLONG;
2431 		}
2432 	}
2433 out:
2434 	return error;
2435 }
2436 #endif
2437 
2438 void
2439 lookup_compound_vnop_post_hook(int error, vnode_t dvp, vnode_t vp, struct nameidata *ndp, int did_create)
2440 {
2441 	if (error == 0 && vp == NULLVP) {
2442 		panic("NULL vp with error == 0.");
2443 	}
2444 
2445 	/*
2446 	 * We don't want to do any of this if we didn't use the compound vnop
2447 	 * to perform the lookup... i.e. if we're allowing and using the legacy pattern,
2448 	 * where we did a full lookup.
2449 	 */
2450 	if ((ndp->ni_flag & NAMEI_COMPOUND_OP_MASK) == 0) {
2451 		return;
2452 	}
2453 
2454 	/*
2455 	 * If we're going to continue the lookup, we'll handle
2456 	 * all lookup-related updates at that time.
2457 	 */
2458 	if (error == EKEEPLOOKING) {
2459 		return;
2460 	}
2461 
2462 	/*
2463 	 * Only audit or update cache for *found* vnodes.  For creation
2464 	 * neither would happen in the non-compound-vnop case.
2465 	 */
2466 	if ((vp != NULLVP) && !did_create) {
2467 		/*
2468 		 * If MAKEENTRY isn't set, and we've done a successful compound VNOP,
2469 		 * then we certainly don't want to update cache or identity.
2470 		 */
2471 		if ((error != 0) || (ndp->ni_cnd.cn_flags & MAKEENTRY)) {
2472 			lookup_consider_update_cache(dvp, vp, &ndp->ni_cnd, ndp->ni_ncgeneration);
2473 		}
2474 		if (ndp->ni_cnd.cn_flags & AUDITVNPATH1) {
2475 			AUDIT_ARG(vnpath, vp, ARG_VNODE1);
2476 		} else if (ndp->ni_cnd.cn_flags & AUDITVNPATH2) {
2477 			AUDIT_ARG(vnpath, vp, ARG_VNODE2);
2478 		}
2479 	}
2480 
2481 	/*
2482 	 * If you created (whether you opened or not), cut a lookup tracepoint
2483 	 * for the parent dir (as would happen without a compound vnop).  Note: we may need
2484 	 * a vnode despite failure in this case!
2485 	 *
2486 	 * If you did not create:
2487 	 *      Found child (succeeded or not): cut a tracepoint for the child.
2488 	 *      Did not find child: cut a tracepoint with the parent.
2489 	 */
2490 	if (kdebug_enable) {
2491 		kdebug_lookup(vp ? vp : dvp, &ndp->ni_cnd);
2492 	}
2493 }
2494