xref: /xnu-8020.101.4/bsd/vfs/vfs_cache.c (revision e7776783b89a353188416a9a346c6cdb4928faad)
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) 1989, 1993, 1995
31  *	The Regents of the University of California.  All rights reserved.
32  *
33  * This code is derived from software contributed to Berkeley by
34  * Poul-Henning Kamp of the FreeBSD Project.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. All advertising materials mentioning features or use of this software
45  *    must display the following acknowledgement:
46  *	This product includes software developed by the University of
47  *	California, Berkeley and its contributors.
48  * 4. Neither the name of the University nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  *
64  *
65  *	@(#)vfs_cache.c	8.5 (Berkeley) 3/22/95
66  */
67 /*
68  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
69  * support for mandatory and extensible security protections.  This notice
70  * is included in support of clause 2.2 (b) of the Apple Public License,
71  * Version 2.0.
72  */
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/time.h>
76 #include <sys/mount_internal.h>
77 #include <sys/vnode_internal.h>
78 #include <miscfs/specfs/specdev.h>
79 #include <sys/namei.h>
80 #include <sys/errno.h>
81 #include <kern/kalloc.h>
82 #include <sys/kauth.h>
83 #include <sys/user.h>
84 #include <sys/paths.h>
85 #include <os/overflow.h>
86 
87 #if CONFIG_MACF
88 #include <security/mac_framework.h>
89 #endif
90 
91 /*
92  * Name caching works as follows:
93  *
94  * Names found by directory scans are retained in a cache
95  * for future reference.  It is managed LRU, so frequently
96  * used names will hang around.  Cache is indexed by hash value
97  * obtained from (vp, name) where vp refers to the directory
98  * containing name.
99  *
100  * If it is a "negative" entry, (i.e. for a name that is known NOT to
101  * exist) the vnode pointer will be NULL.
102  *
103  * Upon reaching the last segment of a path, if the reference
104  * is for DELETE, or NOCACHE is set (rewrite), and the
105  * name is located in the cache, it will be dropped.
106  */
107 
108 /*
109  * Structures associated with name cacheing.
110  */
111 
112 ZONE_DEFINE_TYPE(namecache_zone, "namecache", struct namecache, ZC_NONE);
113 
114 LIST_HEAD(nchashhead, namecache) * nchashtbl;    /* Hash Table */
115 u_long  nchashmask;
116 u_long  nchash;                         /* size of hash table - 1 */
117 long    numcache;                       /* number of cache entries allocated */
118 int     desiredNodes;
119 int     desiredNegNodes;
120 int     ncs_negtotal;
121 TUNABLE_WRITEABLE(int, nc_disabled, "-novfscache", 0);
122 TAILQ_HEAD(, namecache) nchead;         /* chain of all name cache entries */
123 TAILQ_HEAD(, namecache) neghead;        /* chain of only negative cache entries */
124 
125 
126 #if COLLECT_STATS
127 
128 struct  nchstats nchstats;              /* cache effectiveness statistics */
129 
130 #define NCHSTAT(v) {            \
131 	nchstats.v++;           \
132 }
133 #define NAME_CACHE_LOCK()               name_cache_lock()
134 #define NAME_CACHE_UNLOCK()             name_cache_unlock()
135 #define NAME_CACHE_LOCK_SHARED()        name_cache_lock()
136 
137 #else
138 
139 #define NCHSTAT(v)
140 #define NAME_CACHE_LOCK()               name_cache_lock()
141 #define NAME_CACHE_UNLOCK()             name_cache_unlock()
142 #define NAME_CACHE_LOCK_SHARED()        name_cache_lock_shared()
143 
144 #endif
145 
146 
147 /* vars for name cache list lock */
148 static LCK_GRP_DECLARE(namecache_lck_grp, "Name Cache");
149 static LCK_RW_DECLARE(namecache_rw_lock, &namecache_lck_grp);
150 
151 static LCK_GRP_DECLARE(strcache_lck_grp, "String Cache");
152 static LCK_ATTR_DECLARE(strcache_lck_attr, 0, 0);
153 LCK_RW_DECLARE_ATTR(strtable_rw_lock, &strcache_lck_grp, &strcache_lck_attr);
154 
155 static LCK_GRP_DECLARE(rootvnode_lck_grp, "rootvnode");
156 LCK_RW_DECLARE(rootvnode_rw_lock, &rootvnode_lck_grp);
157 
158 #define NUM_STRCACHE_LOCKS 1024
159 
160 lck_mtx_t strcache_mtx_locks[NUM_STRCACHE_LOCKS];
161 
162 
163 static vnode_t cache_lookup_locked(vnode_t dvp, struct componentname *cnp);
164 static const char *add_name_internal(const char *, uint32_t, u_int, boolean_t, u_int);
165 static void init_string_table(void);
166 static void cache_delete(struct namecache *, int);
167 static void cache_enter_locked(vnode_t dvp, vnode_t vp, struct componentname *cnp, const char *strname);
168 static void cache_purge_locked(vnode_t vp, kauth_cred_t *credp);
169 
170 #ifdef DUMP_STRING_TABLE
171 /*
172  * Internal dump function used for debugging
173  */
174 void dump_string_table(void);
175 #endif  /* DUMP_STRING_TABLE */
176 
177 static void init_crc32(void);
178 static unsigned int crc32tab[256];
179 
180 
181 #define NCHHASH(dvp, hash_val) \
182 	(&nchashtbl[(dvp->v_id ^ (hash_val)) & nchashmask])
183 
184 /*
185  * This function tries to check if a directory vp is a subdirectory of dvp
186  * only from valid v_parent pointers. It is called with the name cache lock
187  * held and does not drop the lock anytime inside the function.
188  *
189  * It returns a boolean that indicates whether or not it was able to
190  * successfully infer the parent/descendent relationship via the v_parent
191  * pointers, or if it could not infer such relationship and that the decision
192  * must be delegated to the owning filesystem.
193  *
194  * If it does not defer the decision, i.e. it was successfuly able to determine
195  * the parent/descendent relationship,  *is_subdir tells the caller if vp is a
196  * subdirectory of dvp.
197  *
198  * If the decision is deferred, *next_vp is where it stopped i.e. *next_vp
199  * is the vnode whose parent is to be determined from the filesystem.
200  * *is_subdir, in this case, is not indicative of anything and should be
201  * ignored.
202  *
203  * The return value and output args should be used as follows :
204  *
205  * defer = cache_check_vnode_issubdir(vp, dvp, is_subdir, next_vp);
206  * if (!defer) {
207  *      if (*is_subdir)
208  *              vp is subdirectory;
209  *      else
210  *              vp is not a subdirectory;
211  * } else {
212  *      if (*next_vp)
213  *              check this vnode's parent from the filesystem
214  *      else
215  *              error (likely because of forced unmount).
216  * }
217  *
218  */
219 static boolean_t
cache_check_vnode_issubdir(vnode_t vp,vnode_t dvp,boolean_t * is_subdir,vnode_t * next_vp)220 cache_check_vnode_issubdir(vnode_t vp, vnode_t dvp, boolean_t *is_subdir,
221     vnode_t *next_vp)
222 {
223 	vnode_t tvp = vp;
224 	int defer = FALSE;
225 
226 	*is_subdir = FALSE;
227 	*next_vp = NULLVP;
228 	while (1) {
229 		mount_t tmp;
230 
231 		if (tvp == dvp) {
232 			*is_subdir = TRUE;
233 			break;
234 		} else if (tvp == rootvnode) {
235 			/* *is_subdir = FALSE */
236 			break;
237 		}
238 
239 		tmp = tvp->v_mount;
240 		while ((tvp->v_flag & VROOT) && tmp && tmp->mnt_vnodecovered &&
241 		    tvp != dvp && tvp != rootvnode) {
242 			tvp = tmp->mnt_vnodecovered;
243 			tmp = tvp->v_mount;
244 		}
245 
246 		/*
247 		 * If dvp is not at the top of a mount "stack" then
248 		 * vp is not a subdirectory of dvp either.
249 		 */
250 		if (tvp == dvp || tvp == rootvnode) {
251 			/* *is_subdir = FALSE */
252 			break;
253 		}
254 
255 		if (!tmp) {
256 			defer = TRUE;
257 			*next_vp = NULLVP;
258 			break;
259 		}
260 
261 		if ((tvp->v_flag & VISHARDLINK) || !(tvp->v_parent)) {
262 			defer = TRUE;
263 			*next_vp = tvp;
264 			break;
265 		}
266 
267 		tvp = tvp->v_parent;
268 	}
269 
270 	return defer;
271 }
272 
273 /* maximum times retry from potentially transient errors in vnode_issubdir */
274 #define MAX_ERROR_RETRY 3
275 
276 /*
277  * This function checks if a given directory (vp) is a subdirectory of dvp.
278  * It walks backwards from vp and if it hits dvp in its parent chain,
279  * it is a subdirectory. If it encounters the root directory, it is not
280  * a subdirectory.
281  *
282  * This function returns an error if it is unsuccessful and 0 on success.
283  *
284  * On entry (and exit) vp has an iocount and if this function has to take
285  * any iocounts on other vnodes in the parent chain traversal, it releases them.
286  */
287 int
vnode_issubdir(vnode_t vp,vnode_t dvp,int * is_subdir,vfs_context_t ctx)288 vnode_issubdir(vnode_t vp, vnode_t dvp, int *is_subdir, vfs_context_t ctx)
289 {
290 	vnode_t start_vp, tvp;
291 	vnode_t vp_with_iocount;
292 	int error = 0;
293 	char dotdotbuf[] = "..";
294 	int error_retry_count = 0; /* retry count for potentially transient
295 	                            *  errors */
296 
297 	*is_subdir = FALSE;
298 	tvp = start_vp = vp;
299 	/*
300 	 * Anytime we acquire an iocount in this function, we save the vnode
301 	 * in this variable and release it before exiting.
302 	 */
303 	vp_with_iocount = NULLVP;
304 
305 	while (1) {
306 		boolean_t defer;
307 		vnode_t pvp;
308 		uint32_t vid;
309 		struct componentname cn;
310 		boolean_t is_subdir_locked = FALSE;
311 
312 		if (tvp == dvp) {
313 			*is_subdir = TRUE;
314 			break;
315 		} else if (tvp == rootvnode) {
316 			/* *is_subdir = FALSE */
317 			break;
318 		}
319 
320 		NAME_CACHE_LOCK_SHARED();
321 
322 		defer = cache_check_vnode_issubdir(tvp, dvp, &is_subdir_locked,
323 		    &tvp);
324 
325 		if (defer && tvp) {
326 			vid = vnode_vid(tvp);
327 		}
328 
329 		NAME_CACHE_UNLOCK();
330 
331 		if (!defer) {
332 			*is_subdir = is_subdir_locked;
333 			break;
334 		}
335 
336 		if (!tvp) {
337 			if (error_retry_count++ < MAX_ERROR_RETRY) {
338 				tvp = vp;
339 				continue;
340 			}
341 			error = ENOENT;
342 			break;
343 		}
344 
345 		if (tvp != start_vp) {
346 			if (vp_with_iocount) {
347 				vnode_put(vp_with_iocount);
348 				vp_with_iocount = NULLVP;
349 			}
350 
351 			error = vnode_getwithvid(tvp, vid);
352 			if (error) {
353 				if (error_retry_count++ < MAX_ERROR_RETRY) {
354 					tvp = vp;
355 					error = 0;
356 					continue;
357 				}
358 				break;
359 			}
360 
361 			vp_with_iocount = tvp;
362 		}
363 
364 		bzero(&cn, sizeof(cn));
365 		cn.cn_nameiop = LOOKUP;
366 		cn.cn_flags = ISLASTCN | ISDOTDOT;
367 		cn.cn_context = ctx;
368 		cn.cn_pnbuf = &dotdotbuf[0];
369 		cn.cn_pnlen = sizeof(dotdotbuf);
370 		cn.cn_nameptr = cn.cn_pnbuf;
371 		cn.cn_namelen = 2;
372 
373 		pvp = NULLVP;
374 		if ((error = VNOP_LOOKUP(tvp, &pvp, &cn, ctx))) {
375 			break;
376 		}
377 
378 		if (!(tvp->v_flag & VISHARDLINK) && tvp->v_parent != pvp) {
379 			(void)vnode_update_identity(tvp, pvp, NULL, 0, 0,
380 			    VNODE_UPDATE_PARENT);
381 		}
382 
383 		if (vp_with_iocount) {
384 			vnode_put(vp_with_iocount);
385 		}
386 
387 		vp_with_iocount = tvp = pvp;
388 	}
389 
390 	if (vp_with_iocount) {
391 		vnode_put(vp_with_iocount);
392 	}
393 
394 	return error;
395 }
396 
397 /*
398  * This function builds the path in "buff" from the supplied vnode.
399  * The length of the buffer *INCLUDING* the trailing zero byte is
400  * returned in outlen.  NOTE: the length includes the trailing zero
401  * byte and thus the length is one greater than what strlen would
402  * return.  This is important and lots of code elsewhere in the kernel
403  * assumes this behavior.
404  *
405  * This function can call vnop in file system if the parent vnode
406  * does not exist or when called for hardlinks via volfs path.
407  * If BUILDPATH_NO_FS_ENTER is set in flags, it only uses values present
408  * in the name cache and does not enter the file system.
409  *
410  * If BUILDPATH_CHECK_MOVED is set in flags, we return EAGAIN when
411  * we encounter ENOENT during path reconstruction.  ENOENT means that
412  * one of the parents moved while we were building the path.  The
413  * caller can special handle this case by calling build_path again.
414  *
415  * If BUILDPATH_VOLUME_RELATIVE is set in flags, we return path
416  * that is relative to the nearest mount point, i.e. do not
417  * cross over mount points during building the path.
418  *
419  * passed in vp must have a valid io_count reference
420  *
421  * If parent vnode is non-NULL it also must have an io count.  This
422  * allows build_path_with_parent to be safely called for operations
423  * unlink, rmdir and rename that already have io counts on the target
424  * and the directory. In this way build_path_with_parent does not have
425  * to try and obtain an additional io count on the parent.  Taking an
426  * io count ont the parent can lead to dead lock if a forced unmount
427  * occures at the right moment. For a fuller explaination on how this
428  * can occur see the comment for vn_getpath_with_parent.
429  *
430  */
431 int
build_path_with_parent(vnode_t first_vp,vnode_t parent_vp,char * buff,int buflen,int * outlen,size_t * mntpt_outlen,int flags,vfs_context_t ctx)432 build_path_with_parent(vnode_t first_vp, vnode_t parent_vp, char *buff, int buflen,
433     int *outlen, size_t *mntpt_outlen, int flags, vfs_context_t ctx)
434 {
435 	vnode_t vp, tvp;
436 	vnode_t vp_with_iocount;
437 	vnode_t proc_root_dir_vp;
438 	char *end;
439 	char *mntpt_end;
440 	const char *str;
441 	unsigned int  len;
442 	int  ret = 0;
443 	int  fixhardlink;
444 
445 	if (first_vp == NULLVP) {
446 		return EINVAL;
447 	}
448 
449 	if (buflen <= 1) {
450 		return ENOSPC;
451 	}
452 
453 	/*
454 	 * Grab the process fd so we can evaluate fd_rdir.
455 	 */
456 	if (!(flags & BUILDPATH_NO_PROCROOT)) {
457 		proc_root_dir_vp = vfs_context_proc(ctx)->p_fd.fd_rdir;
458 	} else {
459 		proc_root_dir_vp = NULL;
460 	}
461 
462 	vp_with_iocount = NULLVP;
463 again:
464 	vp = first_vp;
465 
466 	end = &buff[buflen - 1];
467 	*end = '\0';
468 	mntpt_end = NULL;
469 
470 	/*
471 	 * Catch a special corner case here: chroot to /full/path/to/dir, chdir to
472 	 * it, then open it. Without this check, the path to it will be
473 	 * /full/path/to/dir instead of "/".
474 	 */
475 	if (proc_root_dir_vp == first_vp) {
476 		*--end = '/';
477 		goto out;
478 	}
479 
480 	/*
481 	 * holding the NAME_CACHE_LOCK in shared mode is
482 	 * sufficient to stabilize both the vp->v_parent chain
483 	 * and the 'vp->v_mount->mnt_vnodecovered' chain
484 	 *
485 	 * if we need to drop this lock, we must first grab the v_id
486 	 * from the vnode we're currently working with... if that
487 	 * vnode doesn't already have an io_count reference (the vp
488 	 * passed in comes with one), we must grab a reference
489 	 * after we drop the NAME_CACHE_LOCK via vnode_getwithvid...
490 	 * deadlocks may result if you call vnode_get while holding
491 	 * the NAME_CACHE_LOCK... we lazily release the reference
492 	 * we pick up the next time we encounter a need to drop
493 	 * the NAME_CACHE_LOCK or before we return from this routine
494 	 */
495 	NAME_CACHE_LOCK_SHARED();
496 
497 #if CONFIG_FIRMLINKS
498 	if (!(flags & BUILDPATH_NO_FIRMLINK) &&
499 	    (vp->v_flag & VFMLINKTARGET) && vp->v_fmlink && (vp->v_fmlink->v_type == VDIR)) {
500 		vp = vp->v_fmlink;
501 	}
502 #endif
503 
504 	/*
505 	 * Check if this is the root of a file system.
506 	 */
507 	while (vp && vp->v_flag & VROOT) {
508 		if (vp->v_mount == NULL) {
509 			ret = EINVAL;
510 			goto out_unlock;
511 		}
512 		if ((vp->v_mount->mnt_flag & MNT_ROOTFS) || (vp == proc_root_dir_vp)) {
513 			/*
514 			 * It's the root of the root file system, so it's
515 			 * just "/".
516 			 */
517 			*--end = '/';
518 
519 			goto out_unlock;
520 		} else {
521 			/*
522 			 * This the root of the volume and the caller does not
523 			 * want to cross mount points.  Therefore just return
524 			 * '/' as the relative path.
525 			 */
526 #if CONFIG_FIRMLINKS
527 			if (!(flags & BUILDPATH_NO_FIRMLINK) &&
528 			    (vp->v_flag & VFMLINKTARGET) && vp->v_fmlink && (vp->v_fmlink->v_type == VDIR)) {
529 				vp = vp->v_fmlink;
530 			} else
531 #endif
532 			if (flags & BUILDPATH_VOLUME_RELATIVE) {
533 				*--end = '/';
534 				goto out_unlock;
535 			} else {
536 				vp = vp->v_mount->mnt_vnodecovered;
537 				if (!mntpt_end && vp) {
538 					mntpt_end = end;
539 				}
540 			}
541 		}
542 	}
543 
544 	while ((vp != NULLVP) && (vp->v_parent != vp)) {
545 		int  vid;
546 
547 		/*
548 		 * For hardlinks the v_name may be stale, so if its OK
549 		 * to enter a file system, ask the file system for the
550 		 * name and parent (below).
551 		 */
552 		fixhardlink = (vp->v_flag & VISHARDLINK) &&
553 		    (vp->v_mount->mnt_kern_flag & MNTK_PATH_FROM_ID) &&
554 		    !(flags & BUILDPATH_NO_FS_ENTER);
555 
556 		if (!fixhardlink) {
557 			str = vp->v_name;
558 
559 			if (str == NULL || *str == '\0') {
560 				if (vp->v_parent != NULL) {
561 					ret = EINVAL;
562 				} else {
563 					ret = ENOENT;
564 				}
565 				goto out_unlock;
566 			}
567 			len = (unsigned int)strlen(str);
568 			/*
569 			 * Check that there's enough space (including space for the '/')
570 			 */
571 			if ((unsigned int)(end - buff) < (len + 1)) {
572 				ret = ENOSPC;
573 				goto out_unlock;
574 			}
575 			/*
576 			 * Copy the name backwards.
577 			 */
578 			str += len;
579 
580 			for (; len > 0; len--) {
581 				*--end = *--str;
582 			}
583 			/*
584 			 * Add a path separator.
585 			 */
586 			*--end = '/';
587 		}
588 
589 		/*
590 		 * Walk up the parent chain.
591 		 */
592 		if (((vp->v_parent != NULLVP) && !fixhardlink) ||
593 		    (flags & BUILDPATH_NO_FS_ENTER)) {
594 			/*
595 			 * In this if () block we are not allowed to enter the filesystem
596 			 * to conclusively get the most accurate parent identifier.
597 			 * As a result, if 'vp' does not identify '/' and it
598 			 * does not have a valid v_parent, then error out
599 			 * and disallow further path construction
600 			 */
601 			if ((vp->v_parent == NULLVP) && (rootvnode != vp)) {
602 				/*
603 				 * Only '/' is allowed to have a NULL parent
604 				 * pointer. Upper level callers should ideally
605 				 * re-drive name lookup on receiving a ENOENT.
606 				 */
607 				ret = ENOENT;
608 
609 				/* The code below will exit early if 'tvp = vp' == NULL */
610 			}
611 			vp = vp->v_parent;
612 
613 			/*
614 			 * if the vnode we have in hand isn't a directory and it
615 			 * has a v_parent, then we started with the resource fork
616 			 * so skip up to avoid getting a duplicate copy of the
617 			 * file name in the path.
618 			 */
619 			if (vp && !vnode_isdir(vp) && vp->v_parent) {
620 				vp = vp->v_parent;
621 			}
622 		} else {
623 			/*
624 			 * No parent, go get it if supported.
625 			 */
626 			struct vnode_attr  va;
627 			vnode_t  dvp;
628 
629 			/*
630 			 * Make sure file system supports obtaining a path from id.
631 			 */
632 			if (!(vp->v_mount->mnt_kern_flag & MNTK_PATH_FROM_ID)) {
633 				ret = ENOENT;
634 				goto out_unlock;
635 			}
636 			vid = vp->v_id;
637 
638 			NAME_CACHE_UNLOCK();
639 
640 			if (vp != first_vp && vp != parent_vp && vp != vp_with_iocount) {
641 				if (vp_with_iocount) {
642 					vnode_put(vp_with_iocount);
643 					vp_with_iocount = NULLVP;
644 				}
645 				if (vnode_getwithvid(vp, vid)) {
646 					goto again;
647 				}
648 				vp_with_iocount = vp;
649 			}
650 			VATTR_INIT(&va);
651 			VATTR_WANTED(&va, va_parentid);
652 
653 			if (fixhardlink) {
654 				VATTR_WANTED(&va, va_name);
655 				va.va_name = zalloc(ZV_NAMEI);
656 			} else {
657 				va.va_name = NULL;
658 			}
659 			/*
660 			 * Ask the file system for its parent id and for its name (optional).
661 			 */
662 			ret = vnode_getattr(vp, &va, ctx);
663 
664 			if (fixhardlink) {
665 				if ((ret == 0) && (VATTR_IS_SUPPORTED(&va, va_name))) {
666 					str = va.va_name;
667 					vnode_update_identity(vp, NULL, str, (unsigned int)strlen(str), 0, VNODE_UPDATE_NAME);
668 				} else if (vp->v_name) {
669 					str = vp->v_name;
670 					ret = 0;
671 				} else {
672 					ret = ENOENT;
673 					goto bad_news;
674 				}
675 				len = (unsigned int)strlen(str);
676 
677 				/*
678 				 * Check that there's enough space.
679 				 */
680 				if ((unsigned int)(end - buff) < (len + 1)) {
681 					ret = ENOSPC;
682 				} else {
683 					/* Copy the name backwards. */
684 					str += len;
685 
686 					for (; len > 0; len--) {
687 						*--end = *--str;
688 					}
689 					/*
690 					 * Add a path separator.
691 					 */
692 					*--end = '/';
693 				}
694 bad_news:
695 				zfree(ZV_NAMEI, va.va_name);
696 			}
697 			if (ret || !VATTR_IS_SUPPORTED(&va, va_parentid)) {
698 				ret = ENOENT;
699 				goto out;
700 			}
701 			/*
702 			 * Ask the file system for the parent vnode.
703 			 */
704 			if ((ret = VFS_VGET(vp->v_mount, (ino64_t)va.va_parentid, &dvp, ctx))) {
705 				goto out;
706 			}
707 
708 			if (!fixhardlink && (vp->v_parent != dvp)) {
709 				vnode_update_identity(vp, dvp, NULL, 0, 0, VNODE_UPDATE_PARENT);
710 			}
711 
712 			if (vp_with_iocount) {
713 				vnode_put(vp_with_iocount);
714 			}
715 			vp = dvp;
716 			vp_with_iocount = vp;
717 
718 			NAME_CACHE_LOCK_SHARED();
719 
720 			/*
721 			 * if the vnode we have in hand isn't a directory and it
722 			 * has a v_parent, then we started with the resource fork
723 			 * so skip up to avoid getting a duplicate copy of the
724 			 * file name in the path.
725 			 */
726 			if (vp && !vnode_isdir(vp) && vp->v_parent) {
727 				vp = vp->v_parent;
728 			}
729 		}
730 
731 		if (vp && (flags & BUILDPATH_CHECKACCESS)) {
732 			vid = vp->v_id;
733 
734 			NAME_CACHE_UNLOCK();
735 
736 			if (vp != first_vp && vp != parent_vp && vp != vp_with_iocount) {
737 				if (vp_with_iocount) {
738 					vnode_put(vp_with_iocount);
739 					vp_with_iocount = NULLVP;
740 				}
741 				if (vnode_getwithvid(vp, vid)) {
742 					goto again;
743 				}
744 				vp_with_iocount = vp;
745 			}
746 			if ((ret = vnode_authorize(vp, NULL, KAUTH_VNODE_SEARCH, ctx))) {
747 				goto out;       /* no peeking */
748 			}
749 			NAME_CACHE_LOCK_SHARED();
750 		}
751 
752 		/*
753 		 * When a mount point is crossed switch the vp.
754 		 * Continue until we find the root or we find
755 		 * a vnode that's not the root of a mounted
756 		 * file system.
757 		 */
758 		tvp = vp;
759 
760 		while (tvp) {
761 			if (tvp == proc_root_dir_vp) {
762 				goto out_unlock;        /* encountered the root */
763 			}
764 
765 #if CONFIG_FIRMLINKS
766 			if (!(flags & BUILDPATH_NO_FIRMLINK) &&
767 			    (tvp->v_flag & VFMLINKTARGET) && tvp->v_fmlink && (vp->v_fmlink->v_type == VDIR)) {
768 				tvp = tvp->v_fmlink;
769 				break;
770 			}
771 #endif
772 
773 			if (!(tvp->v_flag & VROOT) || !tvp->v_mount) {
774 				break;                  /* not the root of a mounted FS */
775 			}
776 			if (flags & BUILDPATH_VOLUME_RELATIVE) {
777 				/* Do not cross over mount points */
778 				tvp = NULL;
779 			} else {
780 				tvp = tvp->v_mount->mnt_vnodecovered;
781 				if (!mntpt_end && tvp) {
782 					mntpt_end = end;
783 				}
784 			}
785 		}
786 		if (tvp == NULLVP) {
787 			goto out_unlock;
788 		}
789 		vp = tvp;
790 	}
791 out_unlock:
792 	NAME_CACHE_UNLOCK();
793 out:
794 	if (vp_with_iocount) {
795 		vnode_put(vp_with_iocount);
796 	}
797 	/*
798 	 * Slide the name down to the beginning of the buffer.
799 	 */
800 	memmove(buff, end, &buff[buflen] - end);
801 
802 	/*
803 	 * length includes the trailing zero byte
804 	 */
805 	*outlen = (int)(&buff[buflen] - end);
806 	if (mntpt_outlen && mntpt_end) {
807 		*mntpt_outlen = (size_t)*outlen - (size_t)(&buff[buflen] - mntpt_end);
808 	}
809 
810 	/* One of the parents was moved during path reconstruction.
811 	 * The caller is interested in knowing whether any of the
812 	 * parents moved via BUILDPATH_CHECK_MOVED, so return EAGAIN.
813 	 */
814 	if ((ret == ENOENT) && (flags & BUILDPATH_CHECK_MOVED)) {
815 		ret = EAGAIN;
816 	}
817 
818 	return ret;
819 }
820 
821 int
build_path(vnode_t first_vp,char * buff,int buflen,int * outlen,int flags,vfs_context_t ctx)822 build_path(vnode_t first_vp, char *buff, int buflen, int *outlen, int flags, vfs_context_t ctx)
823 {
824 	return build_path_with_parent(first_vp, NULL, buff, buflen, outlen, NULL, flags, ctx);
825 }
826 
827 /*
828  * return NULLVP if vp's parent doesn't
829  * exist, or we can't get a valid iocount
830  * else return the parent of vp
831  */
832 vnode_t
vnode_getparent(vnode_t vp)833 vnode_getparent(vnode_t vp)
834 {
835 	vnode_t pvp = NULLVP;
836 	int     pvid;
837 
838 	NAME_CACHE_LOCK_SHARED();
839 
840 	pvp = vp->v_parent;
841 
842 	/*
843 	 * v_parent is stable behind the name_cache lock
844 	 * however, the only thing we can really guarantee
845 	 * is that we've grabbed a valid iocount on the
846 	 * parent of 'vp' at the time we took the name_cache lock...
847 	 * once we drop the lock, vp could get re-parented
848 	 */
849 	if (pvp != NULLVP) {
850 		pvid = pvp->v_id;
851 
852 		NAME_CACHE_UNLOCK();
853 
854 		if (vnode_getwithvid(pvp, pvid) != 0) {
855 			pvp = NULL;
856 		}
857 	} else {
858 		NAME_CACHE_UNLOCK();
859 	}
860 	return pvp;
861 }
862 
863 const char *
vnode_getname(vnode_t vp)864 vnode_getname(vnode_t vp)
865 {
866 	const char *name = NULL;
867 
868 	NAME_CACHE_LOCK_SHARED();
869 
870 	if (vp->v_name) {
871 		name = vfs_addname(vp->v_name, (unsigned int)strlen(vp->v_name), 0, 0);
872 	}
873 	NAME_CACHE_UNLOCK();
874 
875 	return name;
876 }
877 
878 void
vnode_putname(const char * name)879 vnode_putname(const char *name)
880 {
881 	vfs_removename(name);
882 }
883 
884 static const char unknown_vnodename[] = "(unknown vnode name)";
885 
886 const char *
vnode_getname_printable(vnode_t vp)887 vnode_getname_printable(vnode_t vp)
888 {
889 	const char *name = vnode_getname(vp);
890 	if (name != NULL) {
891 		return name;
892 	}
893 
894 	switch (vp->v_type) {
895 	case VCHR:
896 	case VBLK:
897 	{
898 		/*
899 		 * Create an artificial dev name from
900 		 * major and minor device number
901 		 */
902 		char dev_name[64];
903 		(void) snprintf(dev_name, sizeof(dev_name),
904 		    "%c(%u, %u)", VCHR == vp->v_type ? 'c':'b',
905 		    major(vp->v_rdev), minor(vp->v_rdev));
906 		/*
907 		 * Add the newly created dev name to the name
908 		 * cache to allow easier cleanup. Also,
909 		 * vfs_addname allocates memory for the new name
910 		 * and returns it.
911 		 */
912 		NAME_CACHE_LOCK_SHARED();
913 		name = vfs_addname(dev_name, (unsigned int)strlen(dev_name), 0, 0);
914 		NAME_CACHE_UNLOCK();
915 		return name;
916 	}
917 	default:
918 		return unknown_vnodename;
919 	}
920 }
921 
922 void
vnode_putname_printable(const char * name)923 vnode_putname_printable(const char *name)
924 {
925 	if (name == unknown_vnodename) {
926 		return;
927 	}
928 	vnode_putname(name);
929 }
930 
931 
932 /*
933  * if VNODE_UPDATE_PARENT, and we can take
934  * a reference on dvp, then update vp with
935  * it's new parent... if vp already has a parent,
936  * then drop the reference vp held on it
937  *
938  * if VNODE_UPDATE_NAME,
939  * then drop string ref on v_name if it exists, and if name is non-NULL
940  * then pick up a string reference on name and record it in v_name...
941  * optionally pass in the length and hashval of name if known
942  *
943  * if VNODE_UPDATE_CACHE, flush the name cache entries associated with vp
944  */
945 void
vnode_update_identity(vnode_t vp,vnode_t dvp,const char * name,int name_len,uint32_t name_hashval,int flags)946 vnode_update_identity(vnode_t vp, vnode_t dvp, const char *name, int name_len, uint32_t name_hashval, int flags)
947 {
948 	struct  namecache *ncp;
949 	vnode_t old_parentvp = NULLVP;
950 	int isstream = (vp->v_flag & VISNAMEDSTREAM);
951 	int kusecountbumped = 0;
952 	kauth_cred_t tcred = NULL;
953 	const char *vname = NULL;
954 	const char *tname = NULL;
955 
956 	if (name_len < 0) {
957 		return;
958 	}
959 
960 	if (flags & VNODE_UPDATE_PARENT) {
961 		if (dvp && vnode_ref(dvp) != 0) {
962 			dvp = NULLVP;
963 		}
964 		/* Don't count a stream's parent ref during unmounts */
965 		if (isstream && dvp && (dvp != vp) && (dvp != vp->v_parent) && (dvp->v_type == VREG)) {
966 			vnode_lock_spin(dvp);
967 			++dvp->v_kusecount;
968 			kusecountbumped = 1;
969 			vnode_unlock(dvp);
970 		}
971 	} else {
972 		dvp = NULLVP;
973 	}
974 	if ((flags & VNODE_UPDATE_NAME)) {
975 		if (name != vp->v_name) {
976 			if (name && *name) {
977 				if (name_len == 0) {
978 					name_len = (int)strlen(name);
979 				}
980 				tname = vfs_addname(name, name_len, name_hashval, 0);
981 			}
982 		} else {
983 			flags &= ~VNODE_UPDATE_NAME;
984 		}
985 	}
986 	if ((flags & (VNODE_UPDATE_PURGE | VNODE_UPDATE_PARENT | VNODE_UPDATE_CACHE | VNODE_UPDATE_NAME | VNODE_UPDATE_PURGEFIRMLINK))) {
987 		NAME_CACHE_LOCK();
988 
989 #if CONFIG_FIRMLINKS
990 		if (flags & VNODE_UPDATE_PURGEFIRMLINK) {
991 			vnode_t old_fvp = vp->v_fmlink;
992 			if (old_fvp) {
993 				vnode_lock_spin(vp);
994 				vp->v_flag &= ~VFMLINKTARGET;
995 				vp->v_fmlink = NULLVP;
996 				vnode_unlock(vp);
997 				NAME_CACHE_UNLOCK();
998 
999 				/*
1000 				 * vnode_rele can result in cascading series of
1001 				 * usecount releases. The combination of calling
1002 				 * vnode_recycle and dont_reenter (3rd arg to
1003 				 * vnode_rele_internal) ensures we don't have
1004 				 * that issue.
1005 				 */
1006 				vnode_recycle(old_fvp);
1007 				vnode_rele_internal(old_fvp, O_EVTONLY, 1, 0);
1008 
1009 				NAME_CACHE_LOCK();
1010 			}
1011 		}
1012 #endif
1013 
1014 		if ((flags & VNODE_UPDATE_PURGE)) {
1015 			if (vp->v_parent) {
1016 				vp->v_parent->v_nc_generation++;
1017 			}
1018 
1019 			while ((ncp = LIST_FIRST(&vp->v_nclinks))) {
1020 				cache_delete(ncp, 1);
1021 			}
1022 
1023 			while ((ncp = TAILQ_FIRST(&vp->v_ncchildren))) {
1024 				cache_delete(ncp, 1);
1025 			}
1026 
1027 			/*
1028 			 * Use a temp variable to avoid kauth_cred_drop() while NAME_CACHE_LOCK is held
1029 			 */
1030 			tcred = vnode_cred(vp);
1031 			vp->v_cred = NOCRED;
1032 			vp->v_authorized_actions = 0;
1033 			vp->v_cred_timestamp = 0;
1034 		}
1035 		if ((flags & VNODE_UPDATE_NAME)) {
1036 			vname = vp->v_name;
1037 			vp->v_name = tname;
1038 		}
1039 		if (flags & VNODE_UPDATE_PARENT) {
1040 			if (dvp != vp && dvp != vp->v_parent) {
1041 				old_parentvp = vp->v_parent;
1042 				vp->v_parent = dvp;
1043 				dvp = NULLVP;
1044 
1045 				if (old_parentvp) {
1046 					flags |= VNODE_UPDATE_CACHE;
1047 				}
1048 			}
1049 		}
1050 		if (flags & VNODE_UPDATE_CACHE) {
1051 			while ((ncp = LIST_FIRST(&vp->v_nclinks))) {
1052 				cache_delete(ncp, 1);
1053 			}
1054 		}
1055 		NAME_CACHE_UNLOCK();
1056 
1057 		if (vname != NULL) {
1058 			vfs_removename(vname);
1059 		}
1060 
1061 		kauth_cred_set(&tcred, NOCRED);
1062 	}
1063 	if (dvp != NULLVP) {
1064 		/* Back-out the ref we took if we lost a race for vp->v_parent. */
1065 		if (kusecountbumped) {
1066 			vnode_lock_spin(dvp);
1067 			if (dvp->v_kusecount > 0) {
1068 				--dvp->v_kusecount;
1069 			}
1070 			vnode_unlock(dvp);
1071 		}
1072 		vnode_rele(dvp);
1073 	}
1074 	if (old_parentvp) {
1075 		struct  uthread *ut;
1076 
1077 		if (isstream) {
1078 			vnode_lock_spin(old_parentvp);
1079 			if ((old_parentvp->v_type != VDIR) && (old_parentvp->v_kusecount > 0)) {
1080 				--old_parentvp->v_kusecount;
1081 			}
1082 			vnode_unlock(old_parentvp);
1083 		}
1084 		ut = current_uthread();
1085 
1086 		/*
1087 		 * indicated to vnode_rele that it shouldn't do a
1088 		 * vnode_reclaim at this time... instead it will
1089 		 * chain the vnode to the uu_vreclaims list...
1090 		 * we'll be responsible for calling vnode_reclaim
1091 		 * on each of the vnodes in this list...
1092 		 */
1093 		ut->uu_defer_reclaims = 1;
1094 		ut->uu_vreclaims = NULLVP;
1095 
1096 		while ((vp = old_parentvp) != NULLVP) {
1097 			vnode_lock_spin(vp);
1098 			vnode_rele_internal(vp, 0, 0, 1);
1099 
1100 			/*
1101 			 * check to see if the vnode is now in the state
1102 			 * that would have triggered a vnode_reclaim in vnode_rele
1103 			 * if it is, we save it's parent pointer and then NULL
1104 			 * out the v_parent field... we'll drop the reference
1105 			 * that was held on the next iteration of this loop...
1106 			 * this short circuits a potential deep recursion if we
1107 			 * have a long chain of parents in this state...
1108 			 * we'll sit in this loop until we run into
1109 			 * a parent in this chain that is not in this state
1110 			 *
1111 			 * make our check and the vnode_rele atomic
1112 			 * with respect to the current vnode we're working on
1113 			 * by holding the vnode lock
1114 			 * if vnode_rele deferred the vnode_reclaim and has put
1115 			 * this vnode on the list to be reaped by us, than
1116 			 * it has left this vnode with an iocount == 1
1117 			 */
1118 			if ((vp->v_iocount == 1) && (vp->v_usecount == 0) &&
1119 			    ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD)) == VL_MARKTERM)) {
1120 				/*
1121 				 * vnode_rele wanted to do a vnode_reclaim on this vnode
1122 				 * it should be sitting on the head of the uu_vreclaims chain
1123 				 * pull the parent pointer now so that when we do the
1124 				 * vnode_reclaim for each of the vnodes in the uu_vreclaims
1125 				 * list, we won't recurse back through here
1126 				 *
1127 				 * need to do a convert here in case vnode_rele_internal
1128 				 * returns with the lock held in the spin mode... it
1129 				 * can drop and retake the lock under certain circumstances
1130 				 */
1131 				vnode_lock_convert(vp);
1132 
1133 				NAME_CACHE_LOCK();
1134 				old_parentvp = vp->v_parent;
1135 				vp->v_parent = NULLVP;
1136 				NAME_CACHE_UNLOCK();
1137 			} else {
1138 				/*
1139 				 * we're done... we ran into a vnode that isn't
1140 				 * being terminated
1141 				 */
1142 				old_parentvp = NULLVP;
1143 			}
1144 			vnode_unlock(vp);
1145 		}
1146 		ut->uu_defer_reclaims = 0;
1147 
1148 		while ((vp = ut->uu_vreclaims) != NULLVP) {
1149 			ut->uu_vreclaims = vp->v_defer_reclaimlist;
1150 
1151 			/*
1152 			 * vnode_put will drive the vnode_reclaim if
1153 			 * we are still the only reference on this vnode
1154 			 */
1155 			vnode_put(vp);
1156 		}
1157 	}
1158 }
1159 
1160 #if CONFIG_FIRMLINKS
1161 errno_t
vnode_setasfirmlink(vnode_t vp,vnode_t target_vp)1162 vnode_setasfirmlink(vnode_t vp, vnode_t target_vp)
1163 {
1164 	int error = 0;
1165 	vnode_t old_target_vp = NULLVP;
1166 	vnode_t old_target_vp_v_fmlink = NULLVP;
1167 	kauth_cred_t target_vp_cred = NULL;
1168 	kauth_cred_t old_target_vp_cred = NULL;
1169 
1170 	if (!vp) {
1171 		return EINVAL;
1172 	}
1173 
1174 	if (target_vp) {
1175 		if (vp->v_fmlink == target_vp) { /* Will be checked again under the name cache lock */
1176 			return 0;
1177 		}
1178 
1179 		/*
1180 		 * Firmlink source and target will take both a usecount
1181 		 * and kusecount on each other.
1182 		 */
1183 		if ((error = vnode_ref_ext(target_vp, O_EVTONLY, VNODE_REF_FORCE))) {
1184 			return error;
1185 		}
1186 
1187 		if ((error = vnode_ref_ext(vp, O_EVTONLY, VNODE_REF_FORCE))) {
1188 			vnode_rele_ext(target_vp, O_EVTONLY, 1);
1189 			return error;
1190 		}
1191 	}
1192 
1193 	NAME_CACHE_LOCK();
1194 
1195 	old_target_vp = vp->v_fmlink;
1196 	if (target_vp && (target_vp == old_target_vp)) {
1197 		NAME_CACHE_UNLOCK();
1198 		return 0;
1199 	}
1200 	vp->v_fmlink = target_vp;
1201 
1202 	vnode_lock_spin(vp);
1203 	vp->v_flag &= ~VFMLINKTARGET;
1204 	vnode_unlock(vp);
1205 
1206 	if (target_vp) {
1207 		target_vp->v_fmlink = vp;
1208 		vnode_lock_spin(target_vp);
1209 		target_vp->v_flag |= VFMLINKTARGET;
1210 		vnode_unlock(target_vp);
1211 		cache_purge_locked(vp, &target_vp_cred);
1212 	}
1213 
1214 	if (old_target_vp) {
1215 		old_target_vp_v_fmlink = old_target_vp->v_fmlink;
1216 		old_target_vp->v_fmlink = NULLVP;
1217 		vnode_lock_spin(old_target_vp);
1218 		old_target_vp->v_flag &= ~VFMLINKTARGET;
1219 		vnode_unlock(old_target_vp);
1220 		cache_purge_locked(vp, &old_target_vp_cred);
1221 	}
1222 
1223 	NAME_CACHE_UNLOCK();
1224 
1225 	kauth_cred_set(&target_vp_cred, NOCRED);
1226 
1227 	if (old_target_vp) {
1228 		kauth_cred_set(&old_target_vp_cred, NOCRED);
1229 
1230 		vnode_rele_ext(old_target_vp, O_EVTONLY, 1);
1231 		if (old_target_vp_v_fmlink) {
1232 			vnode_rele_ext(old_target_vp_v_fmlink, O_EVTONLY, 1);
1233 		}
1234 	}
1235 
1236 	return 0;
1237 }
1238 
1239 errno_t
vnode_getfirmlink(vnode_t vp,vnode_t * target_vp)1240 vnode_getfirmlink(vnode_t vp, vnode_t *target_vp)
1241 {
1242 	int error;
1243 
1244 	if (!vp->v_fmlink) {
1245 		return ENODEV;
1246 	}
1247 
1248 	NAME_CACHE_LOCK_SHARED();
1249 	if (vp->v_fmlink && !(vp->v_flag & VFMLINKTARGET) &&
1250 	    (vnode_get(vp->v_fmlink) == 0)) {
1251 		vnode_t tvp = vp->v_fmlink;
1252 
1253 		vnode_lock_spin(tvp);
1254 		if (tvp->v_lflag & (VL_TERMINATE | VL_DEAD)) {
1255 			vnode_unlock(tvp);
1256 			NAME_CACHE_UNLOCK();
1257 			vnode_put(tvp);
1258 			return ENOENT;
1259 		}
1260 		if (!(tvp->v_flag & VFMLINKTARGET)) {
1261 			panic("firmlink target for vnode %p does not have flag set", vp);
1262 		}
1263 		vnode_unlock(tvp);
1264 		*target_vp = tvp;
1265 		error = 0;
1266 	} else {
1267 		*target_vp = NULLVP;
1268 		error = ENODEV;
1269 	}
1270 	NAME_CACHE_UNLOCK();
1271 	return error;
1272 }
1273 
1274 #else /* CONFIG_FIRMLINKS */
1275 
1276 errno_t
vnode_setasfirmlink(__unused vnode_t vp,__unused vnode_t src_vp)1277 vnode_setasfirmlink(__unused vnode_t vp, __unused vnode_t src_vp)
1278 {
1279 	return ENOTSUP;
1280 }
1281 
1282 errno_t
vnode_getfirmlink(__unused vnode_t vp,__unused vnode_t * target_vp)1283 vnode_getfirmlink(__unused vnode_t vp, __unused vnode_t *target_vp)
1284 {
1285 	return ENOTSUP;
1286 }
1287 
1288 #endif
1289 
1290 /*
1291  * Mark a vnode as having multiple hard links.  HFS makes use of this
1292  * because it keeps track of each link separately, and wants to know
1293  * which link was actually used.
1294  *
1295  * This will cause the name cache to force a VNOP_LOOKUP on the vnode
1296  * so that HFS can post-process the lookup.  Also, volfs will call
1297  * VNOP_GETATTR2 to determine the parent, instead of using v_parent.
1298  */
1299 void
vnode_setmultipath(vnode_t vp)1300 vnode_setmultipath(vnode_t vp)
1301 {
1302 	vnode_lock_spin(vp);
1303 
1304 	/*
1305 	 * In theory, we're changing the vnode's identity as far as the
1306 	 * name cache is concerned, so we ought to grab the name cache lock
1307 	 * here.  However, there is already a race, and grabbing the name
1308 	 * cache lock only makes the race window slightly smaller.
1309 	 *
1310 	 * The race happens because the vnode already exists in the name
1311 	 * cache, and could be found by one thread before another thread
1312 	 * can set the hard link flag.
1313 	 */
1314 
1315 	vp->v_flag |= VISHARDLINK;
1316 
1317 	vnode_unlock(vp);
1318 }
1319 
1320 
1321 
1322 /*
1323  * backwards compatibility
1324  */
1325 void
vnode_uncache_credentials(vnode_t vp)1326 vnode_uncache_credentials(vnode_t vp)
1327 {
1328 	vnode_uncache_authorized_action(vp, KAUTH_INVALIDATE_CACHED_RIGHTS);
1329 }
1330 
1331 
1332 /*
1333  * use the exclusive form of NAME_CACHE_LOCK to protect the update of the
1334  * following fields in the vnode: v_cred_timestamp, v_cred, v_authorized_actions
1335  * we use this lock so that we can look at the v_cred and v_authorized_actions
1336  * atomically while behind the NAME_CACHE_LOCK in shared mode in 'cache_lookup_path',
1337  * which is the super-hot path... if we are updating the authorized actions for this
1338  * vnode, we are already in the super-slow and far less frequented path so its not
1339  * that bad that we take the lock exclusive for this case... of course we strive
1340  * to hold it for the minimum amount of time possible
1341  */
1342 
1343 void
vnode_uncache_authorized_action(vnode_t vp,kauth_action_t action)1344 vnode_uncache_authorized_action(vnode_t vp, kauth_action_t action)
1345 {
1346 	kauth_cred_t tcred = NOCRED;
1347 
1348 	NAME_CACHE_LOCK();
1349 
1350 	vp->v_authorized_actions &= ~action;
1351 
1352 	if (action == KAUTH_INVALIDATE_CACHED_RIGHTS &&
1353 	    IS_VALID_CRED(vp->v_cred)) {
1354 		/*
1355 		 * Use a temp variable to avoid kauth_cred_unref() while NAME_CACHE_LOCK is held
1356 		 */
1357 		tcred = vnode_cred(vp);
1358 		vp->v_cred = NOCRED;
1359 	}
1360 	NAME_CACHE_UNLOCK();
1361 
1362 	kauth_cred_set(&tcred, NOCRED);
1363 }
1364 
1365 
1366 /* disable vnode_cache_is_authorized() by setting vnode_cache_defeat */
1367 static TUNABLE(int, bootarg_vnode_cache_defeat, "-vnode_cache_defeat", 0);
1368 
1369 boolean_t
vnode_cache_is_authorized(vnode_t vp,vfs_context_t ctx,kauth_action_t action)1370 vnode_cache_is_authorized(vnode_t vp, vfs_context_t ctx, kauth_action_t action)
1371 {
1372 	kauth_cred_t    ucred;
1373 	boolean_t       retval = FALSE;
1374 
1375 	/* Boot argument to defeat rights caching */
1376 	if (bootarg_vnode_cache_defeat) {
1377 		return FALSE;
1378 	}
1379 
1380 	if ((vp->v_mount->mnt_kern_flag & (MNTK_AUTH_OPAQUE | MNTK_AUTH_CACHE_TTL))) {
1381 		/*
1382 		 * a TTL is enabled on the rights cache... handle it here
1383 		 * a TTL of 0 indicates that no rights should be cached
1384 		 */
1385 		if (vp->v_mount->mnt_authcache_ttl) {
1386 			if (!(vp->v_mount->mnt_kern_flag & MNTK_AUTH_CACHE_TTL)) {
1387 				/*
1388 				 * For filesystems marked only MNTK_AUTH_OPAQUE (generally network ones),
1389 				 * we will only allow a SEARCH right on a directory to be cached...
1390 				 * that cached right always has a default TTL associated with it
1391 				 */
1392 				if (action != KAUTH_VNODE_SEARCH || vp->v_type != VDIR) {
1393 					vp = NULLVP;
1394 				}
1395 			}
1396 			if (vp != NULLVP && vnode_cache_is_stale(vp) == TRUE) {
1397 				vnode_uncache_authorized_action(vp, vp->v_authorized_actions);
1398 				vp = NULLVP;
1399 			}
1400 		} else {
1401 			vp = NULLVP;
1402 		}
1403 	}
1404 	if (vp != NULLVP) {
1405 		ucred = vfs_context_ucred(ctx);
1406 
1407 		NAME_CACHE_LOCK_SHARED();
1408 
1409 		if (vnode_cred(vp) == ucred && (vp->v_authorized_actions & action) == action) {
1410 			retval = TRUE;
1411 		}
1412 
1413 		NAME_CACHE_UNLOCK();
1414 	}
1415 	return retval;
1416 }
1417 
1418 
1419 void
vnode_cache_authorized_action(vnode_t vp,vfs_context_t ctx,kauth_action_t action)1420 vnode_cache_authorized_action(vnode_t vp, vfs_context_t ctx, kauth_action_t action)
1421 {
1422 	kauth_cred_t tcred = NOCRED;
1423 	kauth_cred_t ucred;
1424 	struct timeval tv;
1425 	boolean_t ttl_active = FALSE;
1426 
1427 	ucred = vfs_context_ucred(ctx);
1428 
1429 	if (!IS_VALID_CRED(ucred) || action == 0) {
1430 		return;
1431 	}
1432 
1433 	if ((vp->v_mount->mnt_kern_flag & (MNTK_AUTH_OPAQUE | MNTK_AUTH_CACHE_TTL))) {
1434 		/*
1435 		 * a TTL is enabled on the rights cache... handle it here
1436 		 * a TTL of 0 indicates that no rights should be cached
1437 		 */
1438 		if (vp->v_mount->mnt_authcache_ttl == 0) {
1439 			return;
1440 		}
1441 
1442 		if (!(vp->v_mount->mnt_kern_flag & MNTK_AUTH_CACHE_TTL)) {
1443 			/*
1444 			 * only cache SEARCH action for filesystems marked
1445 			 * MNTK_AUTH_OPAQUE on VDIRs...
1446 			 * the lookup_path code will time these out
1447 			 */
1448 			if ((action & ~KAUTH_VNODE_SEARCH) || vp->v_type != VDIR) {
1449 				return;
1450 			}
1451 		}
1452 		ttl_active = TRUE;
1453 
1454 		microuptime(&tv);
1455 	}
1456 	NAME_CACHE_LOCK();
1457 
1458 	if (vnode_cred(vp) != ucred) {
1459 		/*
1460 		 * Use a temp variable to avoid kauth_cred_drop() while NAME_CACHE_LOCK is held
1461 		 */
1462 		tcred = vnode_cred(vp);
1463 		vp->v_cred = NOCRED;
1464 		kauth_cred_set(&vp->v_cred, ucred);
1465 		vp->v_authorized_actions = 0;
1466 	}
1467 	if (ttl_active == TRUE && vp->v_authorized_actions == 0) {
1468 		/*
1469 		 * only reset the timestamnp on the
1470 		 * first authorization cached after the previous
1471 		 * timer has expired or we're switching creds...
1472 		 * 'vnode_cache_is_authorized' will clear the
1473 		 * authorized actions if the TTL is active and
1474 		 * it has expired
1475 		 */
1476 		vp->v_cred_timestamp = (int)tv.tv_sec;
1477 	}
1478 	vp->v_authorized_actions |= action;
1479 
1480 	NAME_CACHE_UNLOCK();
1481 
1482 	kauth_cred_set(&tcred, NOCRED);
1483 }
1484 
1485 
1486 boolean_t
vnode_cache_is_stale(vnode_t vp)1487 vnode_cache_is_stale(vnode_t vp)
1488 {
1489 	struct timeval  tv;
1490 	boolean_t       retval;
1491 
1492 	microuptime(&tv);
1493 
1494 	if ((tv.tv_sec - vp->v_cred_timestamp) > vp->v_mount->mnt_authcache_ttl) {
1495 		retval = TRUE;
1496 	} else {
1497 		retval = FALSE;
1498 	}
1499 
1500 	return retval;
1501 }
1502 
1503 
1504 
1505 /*
1506  * Returns:	0			Success
1507  *		ERECYCLE		vnode was recycled from underneath us.  Force lookup to be re-driven from namei.
1508  *                                              This errno value should not be seen by anyone outside of the kernel.
1509  */
1510 int
cache_lookup_path(struct nameidata * ndp,struct componentname * cnp,vnode_t dp,vfs_context_t ctx,int * dp_authorized,vnode_t last_dp)1511 cache_lookup_path(struct nameidata *ndp, struct componentname *cnp, vnode_t dp,
1512     vfs_context_t ctx, int *dp_authorized, vnode_t last_dp)
1513 {
1514 	char            *cp;            /* pointer into pathname argument */
1515 	int             vid;
1516 	int             vvid = 0;       /* protected by vp != NULLVP */
1517 	vnode_t         vp = NULLVP;
1518 	vnode_t         tdp = NULLVP;
1519 	kauth_cred_t    ucred;
1520 	boolean_t       ttl_enabled = FALSE;
1521 	struct timeval  tv;
1522 	mount_t         mp;
1523 	unsigned int    hash;
1524 	int             error = 0;
1525 	boolean_t       dotdotchecked = FALSE;
1526 
1527 #if CONFIG_TRIGGERS
1528 	vnode_t         trigger_vp;
1529 #endif /* CONFIG_TRIGGERS */
1530 
1531 	ucred = vfs_context_ucred(ctx);
1532 	ndp->ni_flag &= ~(NAMEI_TRAILINGSLASH);
1533 
1534 	NAME_CACHE_LOCK_SHARED();
1535 
1536 	if (dp->v_mount && (dp->v_mount->mnt_kern_flag & (MNTK_AUTH_OPAQUE | MNTK_AUTH_CACHE_TTL))) {
1537 		ttl_enabled = TRUE;
1538 		microuptime(&tv);
1539 	}
1540 	for (;;) {
1541 		/*
1542 		 * Search a directory.
1543 		 *
1544 		 * The cn_hash value is for use by cache_lookup
1545 		 * The last component of the filename is left accessible via
1546 		 * cnp->cn_nameptr for callers that need the name.
1547 		 */
1548 		hash = 0;
1549 		cp = cnp->cn_nameptr;
1550 
1551 		while (*cp && (*cp != '/')) {
1552 			hash = crc32tab[((hash >> 24) ^ (unsigned char)*cp++)] ^ hash << 8;
1553 		}
1554 		/*
1555 		 * the crc generator can legitimately generate
1556 		 * a 0... however, 0 for us means that we
1557 		 * haven't computed a hash, so use 1 instead
1558 		 */
1559 		if (hash == 0) {
1560 			hash = 1;
1561 		}
1562 		cnp->cn_hash = hash;
1563 		cnp->cn_namelen = (int)(cp - cnp->cn_nameptr);
1564 
1565 		ndp->ni_pathlen -= cnp->cn_namelen;
1566 		ndp->ni_next = cp;
1567 
1568 		/*
1569 		 * Replace multiple slashes by a single slash and trailing slashes
1570 		 * by a null.  This must be done before VNOP_LOOKUP() because some
1571 		 * fs's don't know about trailing slashes.  Remember if there were
1572 		 * trailing slashes to handle symlinks, existing non-directories
1573 		 * and non-existing files that won't be directories specially later.
1574 		 */
1575 		while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
1576 			cp++;
1577 			ndp->ni_pathlen--;
1578 
1579 			if (*cp == '\0') {
1580 				ndp->ni_flag |= NAMEI_TRAILINGSLASH;
1581 				*ndp->ni_next = '\0';
1582 			}
1583 		}
1584 		ndp->ni_next = cp;
1585 
1586 		cnp->cn_flags &= ~(MAKEENTRY | ISLASTCN | ISDOTDOT);
1587 
1588 		if (*cp == '\0') {
1589 			cnp->cn_flags |= ISLASTCN;
1590 		}
1591 
1592 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.') {
1593 			cnp->cn_flags |= ISDOTDOT;
1594 #if CONFIG_FIRMLINKS
1595 			/*
1596 			 * If this is a firmlink target then dp has to be switched to the
1597 			 * firmlink "source" before exiting this loop.
1598 			 *
1599 			 * For a firmlink "target", the policy is to pick the parent of the
1600 			 * firmlink "source" as the parent. This means that you can never
1601 			 * get to the "real" parent of firmlink target via a dotdot lookup.
1602 			 */
1603 			if (dp->v_fmlink && (dp->v_flag & VFMLINKTARGET) && (dp->v_fmlink->v_type == VDIR)) {
1604 				dp = dp->v_fmlink;
1605 			}
1606 #endif
1607 		}
1608 
1609 		*dp_authorized = 0;
1610 #if NAMEDRSRCFORK
1611 		/*
1612 		 * Process a request for a file's resource fork.
1613 		 *
1614 		 * Consume the _PATH_RSRCFORKSPEC suffix and tag the path.
1615 		 */
1616 		if ((ndp->ni_pathlen == sizeof(_PATH_RSRCFORKSPEC)) &&
1617 		    (cp[1] == '.' && cp[2] == '.') &&
1618 		    bcmp(cp, _PATH_RSRCFORKSPEC, sizeof(_PATH_RSRCFORKSPEC)) == 0) {
1619 			/* Skip volfs file systems that don't support native streams. */
1620 			if ((dp->v_mount != NULL) &&
1621 			    (dp->v_mount->mnt_flag & MNT_DOVOLFS) &&
1622 			    (dp->v_mount->mnt_kern_flag & MNTK_NAMED_STREAMS) == 0) {
1623 				goto skiprsrcfork;
1624 			}
1625 			cnp->cn_flags |= CN_WANTSRSRCFORK;
1626 			cnp->cn_flags |= ISLASTCN;
1627 			ndp->ni_next[0] = '\0';
1628 			ndp->ni_pathlen = 1;
1629 		}
1630 skiprsrcfork:
1631 #endif
1632 
1633 #if CONFIG_MACF
1634 
1635 		/*
1636 		 * Name cache provides authorization caching (see below)
1637 		 * that will short circuit MAC checks in lookup().
1638 		 * We must perform MAC check here.  On denial
1639 		 * dp_authorized will remain 0 and second check will
1640 		 * be perfomed in lookup().
1641 		 */
1642 		if (!(cnp->cn_flags & DONOTAUTH)) {
1643 			error = mac_vnode_check_lookup(ctx, dp, cnp);
1644 			if (error) {
1645 				NAME_CACHE_UNLOCK();
1646 				goto errorout;
1647 			}
1648 		}
1649 #endif /* MAC */
1650 		if (ttl_enabled &&
1651 		    (dp->v_mount->mnt_authcache_ttl == 0 ||
1652 		    ((tv.tv_sec - dp->v_cred_timestamp) > dp->v_mount->mnt_authcache_ttl))) {
1653 			break;
1654 		}
1655 
1656 		/*
1657 		 * NAME_CACHE_LOCK holds these fields stable
1658 		 *
1659 		 * We can't cache KAUTH_VNODE_SEARCHBYANYONE for root correctly
1660 		 * so we make an ugly check for root here. root is always
1661 		 * allowed and breaking out of here only to find out that is
1662 		 * authorized by virtue of being root is very very expensive.
1663 		 * However, the check for not root is valid only for filesystems
1664 		 * which use local authorization.
1665 		 *
1666 		 * XXX: Remove the check for root when we can reliably set
1667 		 * KAUTH_VNODE_SEARCHBYANYONE as root.
1668 		 */
1669 		if ((vnode_cred(dp) != ucred || !(dp->v_authorized_actions & KAUTH_VNODE_SEARCH)) &&
1670 		    !(dp->v_authorized_actions & KAUTH_VNODE_SEARCHBYANYONE) &&
1671 		    (ttl_enabled || !vfs_context_issuser(ctx))) {
1672 			break;
1673 		}
1674 
1675 		/*
1676 		 * indicate that we're allowed to traverse this directory...
1677 		 * even if we fail the cache lookup or decide to bail for
1678 		 * some other reason, this information is valid and is used
1679 		 * to avoid doing a vnode_authorize before the call to VNOP_LOOKUP
1680 		 */
1681 		*dp_authorized = 1;
1682 
1683 		if ((cnp->cn_flags & (ISLASTCN | ISDOTDOT))) {
1684 			if (cnp->cn_nameiop != LOOKUP) {
1685 				break;
1686 			}
1687 			if (cnp->cn_flags & LOCKPARENT) {
1688 				break;
1689 			}
1690 			if (cnp->cn_flags & NOCACHE) {
1691 				break;
1692 			}
1693 
1694 			if (cnp->cn_flags & ISDOTDOT) {
1695 				/*
1696 				 * Force directory hardlinks to go to
1697 				 * file system for ".." requests.
1698 				 */
1699 				if ((dp->v_flag & VISHARDLINK)) {
1700 					break;
1701 				}
1702 				/*
1703 				 * Quit here only if we can't use
1704 				 * the parent directory pointer or
1705 				 * don't have one.  Otherwise, we'll
1706 				 * use it below.
1707 				 */
1708 				if ((dp->v_flag & VROOT) ||
1709 				    dp == ndp->ni_rootdir ||
1710 				    dp->v_parent == NULLVP) {
1711 					break;
1712 				}
1713 			}
1714 		}
1715 
1716 		if ((cnp->cn_flags & CN_SKIPNAMECACHE)) {
1717 			/*
1718 			 * Force lookup to go to the filesystem with
1719 			 * all cnp fields set up.
1720 			 */
1721 			break;
1722 		}
1723 
1724 		/*
1725 		 * "." and ".." aren't supposed to be cached, so check
1726 		 * for them before checking the cache.
1727 		 */
1728 		if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
1729 			vp = dp;
1730 		} else if ((cnp->cn_flags & ISDOTDOT)) {
1731 			/*
1732 			 * If this is a chrooted process, we need to check if
1733 			 * the process is trying to break out of its chrooted
1734 			 * jail. We do that by trying to determine if dp is
1735 			 * a subdirectory of ndp->ni_rootdir. If we aren't
1736 			 * able to determine that by the v_parent pointers, we
1737 			 * will leave the fast path.
1738 			 *
1739 			 * Since this function may see dotdot components
1740 			 * many times and it has the name cache lock held for
1741 			 * the entire duration, we optimise this by doing this
1742 			 * check only once per cache_lookup_path call.
1743 			 * If dotdotchecked is set, it means we've done this
1744 			 * check once already and don't need to do it again.
1745 			 */
1746 			if (!dotdotchecked && (ndp->ni_rootdir != rootvnode)) {
1747 				vnode_t tvp = dp;
1748 				boolean_t defer = FALSE;
1749 				boolean_t is_subdir = FALSE;
1750 
1751 				defer = cache_check_vnode_issubdir(tvp,
1752 				    ndp->ni_rootdir, &is_subdir, &tvp);
1753 
1754 				if (defer) {
1755 					/* defer to Filesystem */
1756 					break;
1757 				} else if (!is_subdir) {
1758 					/*
1759 					 * This process is trying to break  out
1760 					 * of its chrooted jail, so all its
1761 					 * dotdot accesses will be translated to
1762 					 * its root directory.
1763 					 */
1764 					vp = ndp->ni_rootdir;
1765 				} else {
1766 					/*
1767 					 * All good, let this dotdot access
1768 					 * proceed normally
1769 					 */
1770 					vp = dp->v_parent;
1771 				}
1772 				dotdotchecked = TRUE;
1773 			} else {
1774 				vp = dp->v_parent;
1775 			}
1776 		} else {
1777 			if ((vp = cache_lookup_locked(dp, cnp)) == NULLVP) {
1778 				break;
1779 			}
1780 
1781 			if ((vp->v_flag & VISHARDLINK)) {
1782 				/*
1783 				 * The file system wants a VNOP_LOOKUP on this vnode
1784 				 */
1785 				vp = NULL;
1786 				break;
1787 			}
1788 
1789 #if CONFIG_FIRMLINKS
1790 			if (vp->v_fmlink && !(vp->v_flag & VFMLINKTARGET)) {
1791 				if (cnp->cn_flags & CN_FIRMLINK_NOFOLLOW ||
1792 				    ((vp->v_type != VDIR) && (vp->v_type != VLNK))) {
1793 					/* Leave it to the filesystem */
1794 					vp = NULLVP;
1795 					break;
1796 				}
1797 
1798 				/*
1799 				 * Always switch to the target unless it is a VLNK
1800 				 * and it is the last component and we have NOFOLLOW
1801 				 * semantics
1802 				 */
1803 				if (vp->v_type == VDIR) {
1804 					vp = vp->v_fmlink;
1805 				} else if ((cnp->cn_flags & FOLLOW) ||
1806 				    (ndp->ni_flag & NAMEI_TRAILINGSLASH) || *ndp->ni_next == '/') {
1807 					if (ndp->ni_loopcnt >= MAXSYMLINKS - 1) {
1808 						vp = NULLVP;
1809 						break;
1810 					}
1811 					ndp->ni_loopcnt++;
1812 					vp = vp->v_fmlink;
1813 				}
1814 			}
1815 #endif
1816 		}
1817 		if ((cnp->cn_flags & ISLASTCN)) {
1818 			break;
1819 		}
1820 
1821 		if (vp->v_type != VDIR) {
1822 			if (vp->v_type != VLNK) {
1823 				vp = NULL;
1824 			}
1825 			break;
1826 		}
1827 
1828 		if ((mp = vp->v_mountedhere) && ((cnp->cn_flags & NOCROSSMOUNT) == 0)) {
1829 			vnode_t tmp_vp = mp->mnt_realrootvp;
1830 			if (tmp_vp == NULLVP || mp->mnt_generation != mount_generation ||
1831 			    mp->mnt_realrootvp_vid != tmp_vp->v_id) {
1832 				break;
1833 			}
1834 			vp = tmp_vp;
1835 		}
1836 
1837 #if CONFIG_TRIGGERS
1838 		/*
1839 		 * After traversing all mountpoints stacked here, if we have a
1840 		 * trigger in hand, resolve it.  Note that we don't need to
1841 		 * leave the fast path if the mount has already happened.
1842 		 */
1843 		if (vp->v_resolve) {
1844 			break;
1845 		}
1846 #endif /* CONFIG_TRIGGERS */
1847 
1848 
1849 		dp = vp;
1850 		vp = NULLVP;
1851 
1852 		cnp->cn_nameptr = ndp->ni_next + 1;
1853 		ndp->ni_pathlen--;
1854 		while (*cnp->cn_nameptr == '/') {
1855 			cnp->cn_nameptr++;
1856 			ndp->ni_pathlen--;
1857 		}
1858 	}
1859 	if (vp != NULLVP) {
1860 		vvid = vp->v_id;
1861 	}
1862 	vid = dp->v_id;
1863 
1864 	NAME_CACHE_UNLOCK();
1865 
1866 	if ((vp != NULLVP) && (vp->v_type != VLNK) &&
1867 	    ((cnp->cn_flags & (ISLASTCN | LOCKPARENT | WANTPARENT | SAVESTART)) == ISLASTCN)) {
1868 		/*
1869 		 * if we've got a child and it's the last component, and
1870 		 * the lookup doesn't need to return the parent then we
1871 		 * can skip grabbing an iocount on the parent, since all
1872 		 * we're going to do with it is a vnode_put just before
1873 		 * we return from 'lookup'.  If it's a symbolic link,
1874 		 * we need the parent in case the link happens to be
1875 		 * a relative pathname.
1876 		 */
1877 		tdp = dp;
1878 		dp = NULLVP;
1879 	} else {
1880 need_dp:
1881 		/*
1882 		 * return the last directory we looked at
1883 		 * with an io reference held. If it was the one passed
1884 		 * in as a result of the last iteration of VNOP_LOOKUP,
1885 		 * it should already hold an io ref. No need to increase ref.
1886 		 */
1887 		if (last_dp != dp) {
1888 			if (dp == ndp->ni_usedvp) {
1889 				/*
1890 				 * if this vnode matches the one passed in via USEDVP
1891 				 * than this context already holds an io_count... just
1892 				 * use vnode_get to get an extra ref for lookup to play
1893 				 * with... can't use the getwithvid variant here because
1894 				 * it will block behind a vnode_drain which would result
1895 				 * in a deadlock (since we already own an io_count that the
1896 				 * vnode_drain is waiting on)... vnode_get grabs the io_count
1897 				 * immediately w/o waiting... it always succeeds
1898 				 */
1899 				vnode_get(dp);
1900 			} else if ((error = vnode_getwithvid_drainok(dp, vid))) {
1901 				/*
1902 				 * failure indicates the vnode
1903 				 * changed identity or is being
1904 				 * TERMINATED... in either case
1905 				 * punt this lookup.
1906 				 *
1907 				 * don't necessarily return ENOENT, though, because
1908 				 * we really want to go back to disk and make sure it's
1909 				 * there or not if someone else is changing this
1910 				 * vnode. That being said, the one case where we do want
1911 				 * to return ENOENT is when the vnode's mount point is
1912 				 * in the process of unmounting and we might cause a deadlock
1913 				 * in our attempt to take an iocount. An ENODEV error return
1914 				 * is from vnode_get* is an indication this but we change that
1915 				 * ENOENT for upper layers.
1916 				 */
1917 				if (error == ENODEV) {
1918 					error = ENOENT;
1919 				} else {
1920 					error = ERECYCLE;
1921 				}
1922 				goto errorout;
1923 			}
1924 		}
1925 	}
1926 	if (vp != NULLVP) {
1927 		if ((vnode_getwithvid_drainok(vp, vvid))) {
1928 			vp = NULLVP;
1929 
1930 			/*
1931 			 * can't get reference on the vp we'd like
1932 			 * to return... if we didn't grab a reference
1933 			 * on the directory (due to fast path bypass),
1934 			 * then we need to do it now... we can't return
1935 			 * with both ni_dvp and ni_vp NULL, and no
1936 			 * error condition
1937 			 */
1938 			if (dp == NULLVP) {
1939 				dp = tdp;
1940 				goto need_dp;
1941 			}
1942 		}
1943 	}
1944 
1945 	ndp->ni_dvp = dp;
1946 	ndp->ni_vp  = vp;
1947 
1948 #if CONFIG_TRIGGERS
1949 	trigger_vp = vp ? vp : dp;
1950 	if ((error == 0) && (trigger_vp != NULLVP) && vnode_isdir(trigger_vp)) {
1951 		error = vnode_trigger_resolve(trigger_vp, ndp, ctx);
1952 		if (error) {
1953 			if (vp) {
1954 				vnode_put(vp);
1955 			}
1956 			if (dp) {
1957 				vnode_put(dp);
1958 			}
1959 			goto errorout;
1960 		}
1961 	}
1962 #endif /* CONFIG_TRIGGERS */
1963 
1964 errorout:
1965 	/*
1966 	 * If we came into cache_lookup_path after an iteration of the lookup loop that
1967 	 * resulted in a call to VNOP_LOOKUP, then VNOP_LOOKUP returned a vnode with a io ref
1968 	 * on it.  It is now the job of cache_lookup_path to drop the ref on this vnode
1969 	 * when it is no longer needed.  If we get to this point, and last_dp is not NULL
1970 	 * and it is ALSO not the dvp we want to return to caller of this function, it MUST be
1971 	 * the case that we got to a subsequent path component and this previous vnode is
1972 	 * no longer needed.  We can then drop the io ref on it.
1973 	 */
1974 	if ((last_dp != NULLVP) && (last_dp != ndp->ni_dvp)) {
1975 		vnode_put(last_dp);
1976 	}
1977 
1978 	//initialized to 0, should be the same if no error cases occurred.
1979 	return error;
1980 }
1981 
1982 
1983 static vnode_t
cache_lookup_locked(vnode_t dvp,struct componentname * cnp)1984 cache_lookup_locked(vnode_t dvp, struct componentname *cnp)
1985 {
1986 	struct namecache *ncp;
1987 	struct nchashhead *ncpp;
1988 	long namelen = cnp->cn_namelen;
1989 	unsigned int hashval = cnp->cn_hash;
1990 
1991 	if (nc_disabled) {
1992 		return NULL;
1993 	}
1994 
1995 	ncpp = NCHHASH(dvp, cnp->cn_hash);
1996 	LIST_FOREACH(ncp, ncpp, nc_hash) {
1997 		if ((ncp->nc_dvp == dvp) && (ncp->nc_hashval == hashval)) {
1998 			if (strncmp(ncp->nc_name, cnp->cn_nameptr, namelen) == 0 && ncp->nc_name[namelen] == 0) {
1999 				break;
2000 			}
2001 		}
2002 	}
2003 	if (ncp == 0) {
2004 		/*
2005 		 * We failed to find an entry
2006 		 */
2007 		NCHSTAT(ncs_miss);
2008 		return NULL;
2009 	}
2010 	NCHSTAT(ncs_goodhits);
2011 
2012 	return ncp->nc_vp;
2013 }
2014 
2015 
2016 unsigned int hash_string(const char *cp, int len);
2017 //
2018 // Have to take a len argument because we may only need to
2019 // hash part of a componentname.
2020 //
2021 unsigned int
hash_string(const char * cp,int len)2022 hash_string(const char *cp, int len)
2023 {
2024 	unsigned hash = 0;
2025 
2026 	if (len) {
2027 		while (len--) {
2028 			hash = crc32tab[((hash >> 24) ^ (unsigned char)*cp++)] ^ hash << 8;
2029 		}
2030 	} else {
2031 		while (*cp != '\0') {
2032 			hash = crc32tab[((hash >> 24) ^ (unsigned char)*cp++)] ^ hash << 8;
2033 		}
2034 	}
2035 	/*
2036 	 * the crc generator can legitimately generate
2037 	 * a 0... however, 0 for us means that we
2038 	 * haven't computed a hash, so use 1 instead
2039 	 */
2040 	if (hash == 0) {
2041 		hash = 1;
2042 	}
2043 	return hash;
2044 }
2045 
2046 
2047 /*
2048  * Lookup an entry in the cache
2049  *
2050  * We don't do this if the segment name is long, simply so the cache
2051  * can avoid holding long names (which would either waste space, or
2052  * add greatly to the complexity).
2053  *
2054  * Lookup is called with dvp pointing to the directory to search,
2055  * cnp pointing to the name of the entry being sought. If the lookup
2056  * succeeds, the vnode is returned in *vpp, and a status of -1 is
2057  * returned. If the lookup determines that the name does not exist
2058  * (negative cacheing), a status of ENOENT is returned. If the lookup
2059  * fails, a status of zero is returned.
2060  */
2061 
2062 int
cache_lookup(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp)2063 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
2064 {
2065 	struct namecache *ncp;
2066 	struct nchashhead *ncpp;
2067 	long namelen = cnp->cn_namelen;
2068 	unsigned int hashval;
2069 	boolean_t       have_exclusive = FALSE;
2070 	uint32_t vid;
2071 	vnode_t  vp;
2072 
2073 	if (cnp->cn_hash == 0) {
2074 		cnp->cn_hash = hash_string(cnp->cn_nameptr, cnp->cn_namelen);
2075 	}
2076 	hashval = cnp->cn_hash;
2077 
2078 	if (nc_disabled) {
2079 		return 0;
2080 	}
2081 
2082 	NAME_CACHE_LOCK_SHARED();
2083 
2084 relook:
2085 	ncpp = NCHHASH(dvp, cnp->cn_hash);
2086 	LIST_FOREACH(ncp, ncpp, nc_hash) {
2087 		if ((ncp->nc_dvp == dvp) && (ncp->nc_hashval == hashval)) {
2088 			if (strncmp(ncp->nc_name, cnp->cn_nameptr, namelen) == 0 && ncp->nc_name[namelen] == 0) {
2089 				break;
2090 			}
2091 		}
2092 	}
2093 	/* We failed to find an entry */
2094 	if (ncp == 0) {
2095 		NCHSTAT(ncs_miss);
2096 		NAME_CACHE_UNLOCK();
2097 		return 0;
2098 	}
2099 
2100 	/* We don't want to have an entry, so dump it */
2101 	if ((cnp->cn_flags & MAKEENTRY) == 0) {
2102 		if (have_exclusive == TRUE) {
2103 			NCHSTAT(ncs_badhits);
2104 			cache_delete(ncp, 1);
2105 			NAME_CACHE_UNLOCK();
2106 			return 0;
2107 		}
2108 		NAME_CACHE_UNLOCK();
2109 		NAME_CACHE_LOCK();
2110 		have_exclusive = TRUE;
2111 		goto relook;
2112 	}
2113 	vp = ncp->nc_vp;
2114 
2115 	/* We found a "positive" match, return the vnode */
2116 	if (vp) {
2117 		NCHSTAT(ncs_goodhits);
2118 
2119 		vid = vp->v_id;
2120 		NAME_CACHE_UNLOCK();
2121 
2122 		if (vnode_getwithvid(vp, vid)) {
2123 #if COLLECT_STATS
2124 			NAME_CACHE_LOCK();
2125 			NCHSTAT(ncs_badvid);
2126 			NAME_CACHE_UNLOCK();
2127 #endif
2128 			return 0;
2129 		}
2130 		*vpp = vp;
2131 		return -1;
2132 	}
2133 
2134 	/* We found a negative match, and want to create it, so purge */
2135 	if (cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME) {
2136 		if (have_exclusive == TRUE) {
2137 			NCHSTAT(ncs_badhits);
2138 			cache_delete(ncp, 1);
2139 			NAME_CACHE_UNLOCK();
2140 			return 0;
2141 		}
2142 		NAME_CACHE_UNLOCK();
2143 		NAME_CACHE_LOCK();
2144 		have_exclusive = TRUE;
2145 		goto relook;
2146 	}
2147 
2148 	/*
2149 	 * We found a "negative" match, ENOENT notifies client of this match.
2150 	 */
2151 	NCHSTAT(ncs_neghits);
2152 
2153 	NAME_CACHE_UNLOCK();
2154 	return ENOENT;
2155 }
2156 
2157 const char *
cache_enter_create(vnode_t dvp,vnode_t vp,struct componentname * cnp)2158 cache_enter_create(vnode_t dvp, vnode_t vp, struct componentname *cnp)
2159 {
2160 	const char *strname;
2161 
2162 	if (cnp->cn_hash == 0) {
2163 		cnp->cn_hash = hash_string(cnp->cn_nameptr, cnp->cn_namelen);
2164 	}
2165 
2166 	/*
2167 	 * grab 2 references on the string entered
2168 	 * one for the cache_enter_locked to consume
2169 	 * and the second to be consumed by v_name (vnode_create call point)
2170 	 */
2171 	strname = add_name_internal(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, TRUE, 0);
2172 
2173 	NAME_CACHE_LOCK();
2174 
2175 	cache_enter_locked(dvp, vp, cnp, strname);
2176 
2177 	NAME_CACHE_UNLOCK();
2178 
2179 	return strname;
2180 }
2181 
2182 
2183 /*
2184  * Add an entry to the cache...
2185  * but first check to see if the directory
2186  * that this entry is to be associated with has
2187  * had any cache_purges applied since we took
2188  * our identity snapshot... this check needs to
2189  * be done behind the name cache lock
2190  */
2191 void
cache_enter_with_gen(struct vnode * dvp,struct vnode * vp,struct componentname * cnp,int gen)2192 cache_enter_with_gen(struct vnode *dvp, struct vnode *vp, struct componentname *cnp, int gen)
2193 {
2194 	if (cnp->cn_hash == 0) {
2195 		cnp->cn_hash = hash_string(cnp->cn_nameptr, cnp->cn_namelen);
2196 	}
2197 
2198 	NAME_CACHE_LOCK();
2199 
2200 	if (dvp->v_nc_generation == gen) {
2201 		(void)cache_enter_locked(dvp, vp, cnp, NULL);
2202 	}
2203 
2204 	NAME_CACHE_UNLOCK();
2205 }
2206 
2207 
2208 /*
2209  * Add an entry to the cache.
2210  */
2211 void
cache_enter(struct vnode * dvp,struct vnode * vp,struct componentname * cnp)2212 cache_enter(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2213 {
2214 	const char *strname;
2215 
2216 	if (cnp->cn_hash == 0) {
2217 		cnp->cn_hash = hash_string(cnp->cn_nameptr, cnp->cn_namelen);
2218 	}
2219 
2220 	/*
2221 	 * grab 1 reference on the string entered
2222 	 * for the cache_enter_locked to consume
2223 	 */
2224 	strname = add_name_internal(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, FALSE, 0);
2225 
2226 	NAME_CACHE_LOCK();
2227 
2228 	cache_enter_locked(dvp, vp, cnp, strname);
2229 
2230 	NAME_CACHE_UNLOCK();
2231 }
2232 
2233 
2234 static void
cache_enter_locked(struct vnode * dvp,struct vnode * vp,struct componentname * cnp,const char * strname)2235 cache_enter_locked(struct vnode *dvp, struct vnode *vp, struct componentname *cnp, const char *strname)
2236 {
2237 	struct namecache *ncp, *negp;
2238 	struct nchashhead *ncpp;
2239 
2240 	if (nc_disabled) {
2241 		return;
2242 	}
2243 
2244 	/*
2245 	 * if the entry is for -ve caching vp is null
2246 	 */
2247 	if ((vp != NULLVP) && (LIST_FIRST(&vp->v_nclinks))) {
2248 		/*
2249 		 * someone beat us to the punch..
2250 		 * this vnode is already in the cache
2251 		 */
2252 		if (strname != NULL) {
2253 			vfs_removename(strname);
2254 		}
2255 		return;
2256 	}
2257 	/*
2258 	 * We allocate a new entry if we are less than the maximum
2259 	 * allowed and the one at the front of the list is in use.
2260 	 * Otherwise we use the one at the front of the list.
2261 	 */
2262 	if (numcache < desiredNodes &&
2263 	    ((ncp = nchead.tqh_first) == NULL ||
2264 	    ncp->nc_hash.le_prev != 0)) {
2265 		/*
2266 		 * Allocate one more entry
2267 		 */
2268 		ncp = zalloc(namecache_zone);
2269 		numcache++;
2270 	} else {
2271 		/*
2272 		 * reuse an old entry
2273 		 */
2274 		ncp = TAILQ_FIRST(&nchead);
2275 		TAILQ_REMOVE(&nchead, ncp, nc_entry);
2276 
2277 		if (ncp->nc_hash.le_prev != 0) {
2278 			/*
2279 			 * still in use... we need to
2280 			 * delete it before re-using it
2281 			 */
2282 			NCHSTAT(ncs_stolen);
2283 			cache_delete(ncp, 0);
2284 		}
2285 	}
2286 	NCHSTAT(ncs_enters);
2287 
2288 	/*
2289 	 * Fill in cache info, if vp is NULL this is a "negative" cache entry.
2290 	 */
2291 	ncp->nc_vp = vp;
2292 	ncp->nc_dvp = dvp;
2293 	ncp->nc_hashval = cnp->cn_hash;
2294 
2295 	if (strname == NULL) {
2296 		ncp->nc_name = add_name_internal(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, FALSE, 0);
2297 	} else {
2298 		ncp->nc_name = strname;
2299 	}
2300 
2301 	//
2302 	// If the bytes of the name associated with the vnode differ,
2303 	// use the name associated with the vnode since the file system
2304 	// may have set that explicitly in the case of a lookup on a
2305 	// case-insensitive file system where the case of the looked up
2306 	// name differs from what is on disk.  For more details, see:
2307 	//   <rdar://problem/8044697> FSEvents doesn't always decompose diacritical unicode chars in the paths of the changed directories
2308 	//
2309 	const char *vn_name = vp ? vp->v_name : NULL;
2310 	unsigned int len = vn_name ? (unsigned int)strlen(vn_name) : 0;
2311 	if (vn_name && ncp && ncp->nc_name && strncmp(ncp->nc_name, vn_name, len) != 0) {
2312 		unsigned int hash = hash_string(vn_name, len);
2313 
2314 		vfs_removename(ncp->nc_name);
2315 		ncp->nc_name = add_name_internal(vn_name, len, hash, FALSE, 0);
2316 		ncp->nc_hashval = hash;
2317 	}
2318 
2319 	/*
2320 	 * make us the newest entry in the cache
2321 	 * i.e. we'll be the last to be stolen
2322 	 */
2323 	TAILQ_INSERT_TAIL(&nchead, ncp, nc_entry);
2324 
2325 	ncpp = NCHHASH(dvp, cnp->cn_hash);
2326 #if DIAGNOSTIC
2327 	{
2328 		struct namecache *p;
2329 
2330 		for (p = ncpp->lh_first; p != 0; p = p->nc_hash.le_next) {
2331 			if (p == ncp) {
2332 				panic("cache_enter: duplicate");
2333 			}
2334 		}
2335 	}
2336 #endif
2337 	/*
2338 	 * make us available to be found via lookup
2339 	 */
2340 	LIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2341 
2342 	if (vp) {
2343 		/*
2344 		 * add to the list of name cache entries
2345 		 * that point at vp
2346 		 */
2347 		LIST_INSERT_HEAD(&vp->v_nclinks, ncp, nc_un.nc_link);
2348 	} else {
2349 		/*
2350 		 * this is a negative cache entry (vp == NULL)
2351 		 * stick it on the negative cache list.
2352 		 */
2353 		TAILQ_INSERT_TAIL(&neghead, ncp, nc_un.nc_negentry);
2354 
2355 		ncs_negtotal++;
2356 
2357 		if (ncs_negtotal > desiredNegNodes) {
2358 			/*
2359 			 * if we've reached our desired limit
2360 			 * of negative cache entries, delete
2361 			 * the oldest
2362 			 */
2363 			negp = TAILQ_FIRST(&neghead);
2364 			cache_delete(negp, 1);
2365 		}
2366 	}
2367 	/*
2368 	 * add us to the list of name cache entries that
2369 	 * are children of dvp
2370 	 */
2371 	if (vp) {
2372 		TAILQ_INSERT_TAIL(&dvp->v_ncchildren, ncp, nc_child);
2373 	} else {
2374 		TAILQ_INSERT_HEAD(&dvp->v_ncchildren, ncp, nc_child);
2375 	}
2376 }
2377 
2378 
2379 /*
2380  * Initialize CRC-32 remainder table.
2381  */
2382 static void
init_crc32(void)2383 init_crc32(void)
2384 {
2385 	/*
2386 	 * the CRC-32 generator polynomial is:
2387 	 *   x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^10
2388 	 *        + x^8  + x^7  + x^5  + x^4  + x^2  + x + 1
2389 	 */
2390 	unsigned int crc32_polynomial = 0x04c11db7;
2391 	unsigned int i, j;
2392 
2393 	/*
2394 	 * pre-calculate the CRC-32 remainder for each possible octet encoding
2395 	 */
2396 	for (i = 0; i < 256; i++) {
2397 		unsigned int crc_rem = i << 24;
2398 
2399 		for (j = 0; j < 8; j++) {
2400 			if (crc_rem & 0x80000000) {
2401 				crc_rem = (crc_rem << 1) ^ crc32_polynomial;
2402 			} else {
2403 				crc_rem = (crc_rem << 1);
2404 			}
2405 		}
2406 		crc32tab[i] = crc_rem;
2407 	}
2408 }
2409 
2410 
2411 /*
2412  * Name cache initialization, from vfs_init() when we are booting
2413  */
2414 void
nchinit(void)2415 nchinit(void)
2416 {
2417 	desiredNegNodes = (desiredvnodes / 10);
2418 	desiredNodes = desiredvnodes + desiredNegNodes;
2419 
2420 	TAILQ_INIT(&nchead);
2421 	TAILQ_INIT(&neghead);
2422 
2423 	init_crc32();
2424 
2425 	nchashtbl = hashinit(MAX(CONFIG_NC_HASH, (2 * desiredNodes)), M_CACHE, &nchash);
2426 	nchashmask = nchash;
2427 	nchash++;
2428 
2429 	init_string_table();
2430 
2431 	for (int i = 0; i < NUM_STRCACHE_LOCKS; i++) {
2432 		lck_mtx_init(&strcache_mtx_locks[i], &strcache_lck_grp, &strcache_lck_attr);
2433 	}
2434 }
2435 
2436 void
name_cache_lock_shared(void)2437 name_cache_lock_shared(void)
2438 {
2439 	lck_rw_lock_shared(&namecache_rw_lock);
2440 }
2441 
2442 void
name_cache_lock(void)2443 name_cache_lock(void)
2444 {
2445 	lck_rw_lock_exclusive(&namecache_rw_lock);
2446 }
2447 
2448 void
name_cache_unlock(void)2449 name_cache_unlock(void)
2450 {
2451 	lck_rw_done(&namecache_rw_lock);
2452 }
2453 
2454 
2455 int
resize_namecache(int newsize)2456 resize_namecache(int newsize)
2457 {
2458 	struct nchashhead   *new_table;
2459 	struct nchashhead   *old_table;
2460 	struct nchashhead   *old_head, *head;
2461 	struct namecache    *entry, *next;
2462 	uint32_t            i, hashval;
2463 	int                 dNodes, dNegNodes, nelements;
2464 	u_long              new_size, old_size;
2465 
2466 	if (newsize < 0) {
2467 		return EINVAL;
2468 	}
2469 
2470 	dNegNodes = (newsize / 10);
2471 	dNodes = newsize + dNegNodes;
2472 	// we don't support shrinking yet
2473 	if (dNodes <= desiredNodes) {
2474 		return 0;
2475 	}
2476 
2477 	if (os_mul_overflow(dNodes, 2, &nelements)) {
2478 		return EINVAL;
2479 	}
2480 
2481 	new_table = hashinit(nelements, M_CACHE, &nchashmask);
2482 	new_size  = nchashmask + 1;
2483 
2484 	if (new_table == NULL) {
2485 		return ENOMEM;
2486 	}
2487 
2488 	NAME_CACHE_LOCK();
2489 	// do the switch!
2490 	old_table = nchashtbl;
2491 	nchashtbl = new_table;
2492 	old_size  = nchash;
2493 	nchash    = new_size;
2494 
2495 	// walk the old table and insert all the entries into
2496 	// the new table
2497 	//
2498 	for (i = 0; i < old_size; i++) {
2499 		old_head = &old_table[i];
2500 		for (entry = old_head->lh_first; entry != NULL; entry = next) {
2501 			//
2502 			// XXXdbg - Beware: this assumes that hash_string() does
2503 			//                  the same thing as what happens in
2504 			//                  lookup() over in vfs_lookup.c
2505 			hashval = hash_string(entry->nc_name, 0);
2506 			entry->nc_hashval = hashval;
2507 			head = NCHHASH(entry->nc_dvp, hashval);
2508 
2509 			next = entry->nc_hash.le_next;
2510 			LIST_INSERT_HEAD(head, entry, nc_hash);
2511 		}
2512 	}
2513 	desiredNodes = dNodes;
2514 	desiredNegNodes = dNegNodes;
2515 
2516 	NAME_CACHE_UNLOCK();
2517 	hashdestroy(old_table, M_CACHE, old_size - 1);
2518 
2519 	return 0;
2520 }
2521 
2522 static void
cache_delete(struct namecache * ncp,int free_entry)2523 cache_delete(struct namecache *ncp, int free_entry)
2524 {
2525 	NCHSTAT(ncs_deletes);
2526 
2527 	if (ncp->nc_vp) {
2528 		LIST_REMOVE(ncp, nc_un.nc_link);
2529 	} else {
2530 		TAILQ_REMOVE(&neghead, ncp, nc_un.nc_negentry);
2531 		ncs_negtotal--;
2532 	}
2533 	TAILQ_REMOVE(&(ncp->nc_dvp->v_ncchildren), ncp, nc_child);
2534 
2535 	LIST_REMOVE(ncp, nc_hash);
2536 	/*
2537 	 * this field is used to indicate
2538 	 * that the entry is in use and
2539 	 * must be deleted before it can
2540 	 * be reused...
2541 	 */
2542 	ncp->nc_hash.le_prev = NULL;
2543 
2544 	vfs_removename(ncp->nc_name);
2545 	ncp->nc_name = NULL;
2546 	if (free_entry) {
2547 		TAILQ_REMOVE(&nchead, ncp, nc_entry);
2548 		zfree(namecache_zone, ncp);
2549 		numcache--;
2550 	}
2551 }
2552 
2553 
2554 /*
2555  * purge the entry associated with the
2556  * specified vnode from the name cache
2557  */
2558 static void
cache_purge_locked(vnode_t vp,kauth_cred_t * credp)2559 cache_purge_locked(vnode_t vp, kauth_cred_t *credp)
2560 {
2561 	struct namecache *ncp;
2562 
2563 	*credp = NULL;
2564 	if ((LIST_FIRST(&vp->v_nclinks) == NULL) &&
2565 	    (TAILQ_FIRST(&vp->v_ncchildren) == NULL) &&
2566 	    (vnode_cred(vp) == NOCRED) &&
2567 	    (vp->v_parent == NULLVP)) {
2568 		return;
2569 	}
2570 
2571 	if (vp->v_parent) {
2572 		vp->v_parent->v_nc_generation++;
2573 	}
2574 
2575 	while ((ncp = LIST_FIRST(&vp->v_nclinks))) {
2576 		cache_delete(ncp, 1);
2577 	}
2578 
2579 	while ((ncp = TAILQ_FIRST(&vp->v_ncchildren))) {
2580 		cache_delete(ncp, 1);
2581 	}
2582 
2583 	/*
2584 	 * Use a temp variable to avoid kauth_cred_unref() while NAME_CACHE_LOCK is held
2585 	 */
2586 	*credp = vnode_cred(vp);
2587 	vp->v_cred = NOCRED;
2588 	vp->v_authorized_actions = 0;
2589 }
2590 
2591 void
cache_purge(vnode_t vp)2592 cache_purge(vnode_t vp)
2593 {
2594 	kauth_cred_t tcred = NULL;
2595 
2596 	if ((LIST_FIRST(&vp->v_nclinks) == NULL) &&
2597 	    (TAILQ_FIRST(&vp->v_ncchildren) == NULL) &&
2598 	    (vnode_cred(vp) == NOCRED) &&
2599 	    (vp->v_parent == NULLVP)) {
2600 		return;
2601 	}
2602 
2603 	NAME_CACHE_LOCK();
2604 
2605 	cache_purge_locked(vp, &tcred);
2606 
2607 	NAME_CACHE_UNLOCK();
2608 
2609 	kauth_cred_set(&tcred, NOCRED);
2610 }
2611 
2612 /*
2613  * Purge all negative cache entries that are children of the
2614  * given vnode.  A case-insensitive file system (or any file
2615  * system that has multiple equivalent names for the same
2616  * directory entry) can use this when creating or renaming
2617  * to remove negative entries that may no longer apply.
2618  */
2619 void
cache_purge_negatives(vnode_t vp)2620 cache_purge_negatives(vnode_t vp)
2621 {
2622 	struct namecache *ncp, *next_ncp;
2623 
2624 	NAME_CACHE_LOCK();
2625 
2626 	TAILQ_FOREACH_SAFE(ncp, &vp->v_ncchildren, nc_child, next_ncp) {
2627 		if (ncp->nc_vp) {
2628 			break;
2629 		}
2630 
2631 		cache_delete(ncp, 1);
2632 	}
2633 
2634 	NAME_CACHE_UNLOCK();
2635 }
2636 
2637 /*
2638  * Flush all entries referencing a particular filesystem.
2639  *
2640  * Since we need to check it anyway, we will flush all the invalid
2641  * entries at the same time.
2642  */
2643 void
cache_purgevfs(struct mount * mp)2644 cache_purgevfs(struct mount *mp)
2645 {
2646 	struct nchashhead *ncpp;
2647 	struct namecache *ncp;
2648 
2649 	NAME_CACHE_LOCK();
2650 	/* Scan hash tables for applicable entries */
2651 	for (ncpp = &nchashtbl[nchash - 1]; ncpp >= nchashtbl; ncpp--) {
2652 restart:
2653 		for (ncp = ncpp->lh_first; ncp != 0; ncp = ncp->nc_hash.le_next) {
2654 			if (ncp->nc_dvp->v_mount == mp) {
2655 				cache_delete(ncp, 0);
2656 				goto restart;
2657 			}
2658 		}
2659 	}
2660 	NAME_CACHE_UNLOCK();
2661 }
2662 
2663 
2664 
2665 //
2666 // String ref routines
2667 //
2668 static LIST_HEAD(stringhead, string_t) * string_ref_table;
2669 static u_long   string_table_mask;
2670 static uint32_t filled_buckets = 0;
2671 
2672 
2673 typedef struct string_t {
2674 	LIST_ENTRY(string_t)  hash_chain;
2675 	char                  *str;
2676 	uint32_t              strbuflen;
2677 	uint32_t              refcount;
2678 } string_t;
2679 
2680 
2681 static void
resize_string_ref_table(void)2682 resize_string_ref_table(void)
2683 {
2684 	struct stringhead *new_table;
2685 	struct stringhead *old_table;
2686 	struct stringhead *old_head, *head;
2687 	string_t          *entry, *next;
2688 	uint32_t           i, hashval;
2689 	u_long             new_mask, old_mask;
2690 
2691 	/*
2692 	 * need to hold the table lock exclusively
2693 	 * in order to grow the table... need to recheck
2694 	 * the need to resize again after we've taken
2695 	 * the lock exclusively in case some other thread
2696 	 * beat us to the punch
2697 	 */
2698 	lck_rw_lock_exclusive(&strtable_rw_lock);
2699 
2700 	if (4 * filled_buckets < ((string_table_mask + 1) * 3)) {
2701 		lck_rw_done(&strtable_rw_lock);
2702 		return;
2703 	}
2704 	assert(string_table_mask < INT32_MAX);
2705 	new_table = hashinit((int)(string_table_mask + 1) * 2, M_CACHE, &new_mask);
2706 
2707 	if (new_table == NULL) {
2708 		printf("failed to resize the hash table.\n");
2709 		lck_rw_done(&strtable_rw_lock);
2710 		return;
2711 	}
2712 
2713 	// do the switch!
2714 	old_table         = string_ref_table;
2715 	string_ref_table  = new_table;
2716 	old_mask          = string_table_mask;
2717 	string_table_mask = new_mask;
2718 	filled_buckets    = 0;
2719 
2720 	// walk the old table and insert all the entries into
2721 	// the new table
2722 	//
2723 	for (i = 0; i <= old_mask; i++) {
2724 		old_head = &old_table[i];
2725 		for (entry = old_head->lh_first; entry != NULL; entry = next) {
2726 			hashval = hash_string((const char *)entry->str, 0);
2727 			head = &string_ref_table[hashval & string_table_mask];
2728 			if (head->lh_first == NULL) {
2729 				filled_buckets++;
2730 			}
2731 			next = entry->hash_chain.le_next;
2732 			LIST_INSERT_HEAD(head, entry, hash_chain);
2733 		}
2734 	}
2735 	lck_rw_done(&strtable_rw_lock);
2736 
2737 	hashdestroy(old_table, M_CACHE, old_mask);
2738 }
2739 
2740 
2741 static void
init_string_table(void)2742 init_string_table(void)
2743 {
2744 	string_ref_table = hashinit(CONFIG_VFS_NAMES, M_CACHE, &string_table_mask);
2745 }
2746 
2747 
2748 const char *
vfs_addname(const char * name,uint32_t len,u_int hashval,u_int flags)2749 vfs_addname(const char *name, uint32_t len, u_int hashval, u_int flags)
2750 {
2751 	return add_name_internal(name, len, hashval, FALSE, flags);
2752 }
2753 
2754 
2755 static const char *
add_name_internal(const char * name,uint32_t len,u_int hashval,boolean_t need_extra_ref,__unused u_int flags)2756 add_name_internal(const char *name, uint32_t len, u_int hashval, boolean_t need_extra_ref, __unused u_int flags)
2757 {
2758 	struct stringhead *head;
2759 	string_t          *entry;
2760 	uint32_t          chain_len = 0;
2761 	uint32_t          hash_index;
2762 	uint32_t          lock_index;
2763 	char              *ptr;
2764 
2765 	if (len > MAXPATHLEN) {
2766 		len = MAXPATHLEN;
2767 	}
2768 
2769 	/*
2770 	 * if the length already accounts for the null-byte, then
2771 	 * subtract one so later on we don't index past the end
2772 	 * of the string.
2773 	 */
2774 	if (len > 0 && name[len - 1] == '\0') {
2775 		len--;
2776 	}
2777 	if (hashval == 0) {
2778 		hashval = hash_string(name, len);
2779 	}
2780 
2781 	/*
2782 	 * take this lock 'shared' to keep the hash stable
2783 	 * if someone else decides to grow the pool they
2784 	 * will take this lock exclusively
2785 	 */
2786 	lck_rw_lock_shared(&strtable_rw_lock);
2787 
2788 	/*
2789 	 * If the table gets more than 3/4 full, resize it
2790 	 */
2791 	if (4 * filled_buckets >= ((string_table_mask + 1) * 3)) {
2792 		lck_rw_done(&strtable_rw_lock);
2793 
2794 		resize_string_ref_table();
2795 
2796 		lck_rw_lock_shared(&strtable_rw_lock);
2797 	}
2798 	hash_index = hashval & string_table_mask;
2799 	lock_index = hash_index % NUM_STRCACHE_LOCKS;
2800 
2801 	head = &string_ref_table[hash_index];
2802 
2803 	lck_mtx_lock_spin(&strcache_mtx_locks[lock_index]);
2804 
2805 	for (entry = head->lh_first; entry != NULL; chain_len++, entry = entry->hash_chain.le_next) {
2806 		if (strncmp(entry->str, name, len) == 0 && entry->str[len] == 0) {
2807 			entry->refcount++;
2808 			break;
2809 		}
2810 	}
2811 	if (entry == NULL) {
2812 		const uint32_t buflen = len + 1;
2813 
2814 		lck_mtx_convert_spin(&strcache_mtx_locks[lock_index]);
2815 		/*
2816 		 * it wasn't already there so add it.
2817 		 */
2818 		entry = kalloc_type(string_t, Z_WAITOK);
2819 
2820 		if (head->lh_first == NULL) {
2821 			OSAddAtomic(1, &filled_buckets);
2822 		}
2823 		ptr = kalloc_data(buflen, Z_WAITOK);
2824 		strncpy(ptr, name, len);
2825 		ptr[len] = '\0';
2826 		entry->str = ptr;
2827 		entry->strbuflen = buflen;
2828 		entry->refcount = 1;
2829 		LIST_INSERT_HEAD(head, entry, hash_chain);
2830 	}
2831 	if (need_extra_ref == TRUE) {
2832 		entry->refcount++;
2833 	}
2834 
2835 	lck_mtx_unlock(&strcache_mtx_locks[lock_index]);
2836 	lck_rw_done(&strtable_rw_lock);
2837 
2838 	return (const char *)entry->str;
2839 }
2840 
2841 
2842 int
vfs_removename(const char * nameref)2843 vfs_removename(const char *nameref)
2844 {
2845 	struct stringhead *head;
2846 	string_t          *entry;
2847 	uint32_t           hashval;
2848 	uint32_t           hash_index;
2849 	uint32_t           lock_index;
2850 	int                retval = ENOENT;
2851 
2852 	hashval = hash_string(nameref, 0);
2853 
2854 	/*
2855 	 * take this lock 'shared' to keep the hash stable
2856 	 * if someone else decides to grow the pool they
2857 	 * will take this lock exclusively
2858 	 */
2859 	lck_rw_lock_shared(&strtable_rw_lock);
2860 	/*
2861 	 * must compute the head behind the table lock
2862 	 * since the size and location of the table
2863 	 * can change on the fly
2864 	 */
2865 	hash_index = hashval & string_table_mask;
2866 	lock_index = hash_index % NUM_STRCACHE_LOCKS;
2867 
2868 	head = &string_ref_table[hash_index];
2869 
2870 	lck_mtx_lock_spin(&strcache_mtx_locks[lock_index]);
2871 
2872 	for (entry = head->lh_first; entry != NULL; entry = entry->hash_chain.le_next) {
2873 		if (entry->str == nameref) {
2874 			entry->refcount--;
2875 
2876 			if (entry->refcount == 0) {
2877 				LIST_REMOVE(entry, hash_chain);
2878 
2879 				if (head->lh_first == NULL) {
2880 					OSAddAtomic(-1, &filled_buckets);
2881 				}
2882 			} else {
2883 				entry = NULL;
2884 			}
2885 			retval = 0;
2886 			break;
2887 		}
2888 	}
2889 	lck_mtx_unlock(&strcache_mtx_locks[lock_index]);
2890 	lck_rw_done(&strtable_rw_lock);
2891 
2892 	if (entry) {
2893 		assert(entry->refcount == 0);
2894 		kfree_data(entry->str, entry->strbuflen);
2895 		entry->str = NULL;
2896 		entry->strbuflen = 0;
2897 		kfree_type(string_t, entry);
2898 	}
2899 
2900 	return retval;
2901 }
2902 
2903 
2904 #ifdef DUMP_STRING_TABLE
2905 void
dump_string_table(void)2906 dump_string_table(void)
2907 {
2908 	struct stringhead *head;
2909 	string_t          *entry;
2910 	u_long            i;
2911 
2912 	lck_rw_lock_shared(&strtable_rw_lock);
2913 
2914 	for (i = 0; i <= string_table_mask; i++) {
2915 		head = &string_ref_table[i];
2916 		for (entry = head->lh_first; entry != NULL; entry = entry->hash_chain.le_next) {
2917 			printf("%6d - %s\n", entry->refcount, entry->str);
2918 		}
2919 	}
2920 	lck_rw_done(&strtable_rw_lock);
2921 }
2922 #endif  /* DUMP_STRING_TABLE */
2923