xref: /xnu-10002.41.9/bsd/vfs/vfs_cache.c (revision 699cd48037512bf4380799317ca44ca453c82f57)
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 struct smrq_list_head *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 __options_decl(nc_smr_level_t, uint32_t, {
123 	NC_SMR_DISABLED = 0,
124 	NC_SMR_LOOKUP = 1
125 });
126 TUNABLE(nc_smr_level_t, nc_smr_enabled, "ncsmr", NC_SMR_LOOKUP);
127 TAILQ_HEAD(, namecache) nchead;         /* chain of all name cache entries */
128 TAILQ_HEAD(, namecache) neghead;        /* chain of only negative cache entries */
129 
130 
131 #if COLLECT_STATS
132 
133 struct  nchstats nchstats;              /* cache effectiveness statistics */
134 
135 #define NCHSTAT(v) {            \
136 	nchstats.v++;           \
137 }
138 #define NAME_CACHE_LOCK_SHARED()        name_cache_lock()
139 #define NAME_CACHE_LOCK_SHARED_TO_EXCLUSIVE() TRUE
140 
141 #else
142 
143 #define NCHSTAT(v)
144 #define NAME_CACHE_LOCK_SHARED()        name_cache_lock_shared()
145 #define NAME_CACHE_LOCK_SHARED_TO_EXCLUSIVE()             name_cache_lock_shared_to_exclusive()
146 
147 #endif
148 
149 #define NAME_CACHE_LOCK()               name_cache_lock()
150 #define NAME_CACHE_UNLOCK()             name_cache_unlock()
151 
152 /* vars for name cache list lock */
153 static LCK_GRP_DECLARE(namecache_lck_grp, "Name Cache");
154 static LCK_RW_DECLARE(namecache_rw_lock, &namecache_lck_grp);
155 
156 typedef struct string_t {
157 	LIST_ENTRY(string_t)  hash_chain;
158 	char                  *str;
159 	uint32_t              strbuflen;
160 	uint32_t              refcount;
161 } string_t;
162 
163 ZONE_DEFINE_TYPE(stringcache_zone, "vfsstringcache", string_t, ZC_NONE);
164 
165 static LCK_GRP_DECLARE(strcache_lck_grp, "String Cache");
166 static LCK_ATTR_DECLARE(strcache_lck_attr, 0, 0);
167 LCK_RW_DECLARE_ATTR(strtable_rw_lock, &strcache_lck_grp, &strcache_lck_attr);
168 
169 static LCK_GRP_DECLARE(rootvnode_lck_grp, "rootvnode");
170 LCK_RW_DECLARE(rootvnode_rw_lock, &rootvnode_lck_grp);
171 
172 #define NUM_STRCACHE_LOCKS 1024
173 
174 lck_mtx_t strcache_mtx_locks[NUM_STRCACHE_LOCKS];
175 
176 SYSCTL_NODE(_vfs, OID_AUTO, ncstats, CTLFLAG_RD | CTLFLAG_LOCKED, NULL, "vfs name cache stats");
177 
178 SYSCTL_COMPAT_INT(_vfs_ncstats, OID_AUTO, nc_smr_enabled,
179     CTLFLAG_RD | CTLFLAG_LOCKED,
180     &nc_smr_enabled, 0, "");
181 
182 #if COLLECT_NC_SMR_STATS
183 struct ncstats {
184 	uint64_t cl_smr_hits;
185 	uint64_t cl_smr_miss;
186 	uint64_t cl_smr_negative_hits;
187 	uint64_t cl_smr_fallback;
188 	uint64_t cl_lock_hits;
189 	uint64_t clp_next;
190 	uint64_t clp_next_fail;
191 	uint64_t clp_smr_next;
192 	uint64_t clp_smr_next_fail;
193 	uint64_t clp_smr_fallback;
194 	uint64_t nc_lock_shared;
195 	uint64_t nc_lock;
196 } ncstats = {0};
197 
198 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, cl_smr_hits,
199     CTLFLAG_RD | CTLFLAG_LOCKED,
200     &ncstats.cl_smr_hits, "");
201 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, cl_smr_misses,
202     CTLFLAG_RD | CTLFLAG_LOCKED,
203     &ncstats.cl_smr_miss, "");
204 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, cl_smr_negative_hits,
205     CTLFLAG_RD | CTLFLAG_LOCKED,
206     &ncstats.cl_smr_negative_hits, "");
207 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, cl_smr_fallback,
208     CTLFLAG_RD | CTLFLAG_LOCKED,
209     &ncstats.cl_smr_fallback, "");
210 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, cl_lock_hits,
211     CTLFLAG_RD | CTLFLAG_LOCKED,
212     &ncstats.cl_lock_hits, "");
213 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, clp_next,
214     CTLFLAG_RD | CTLFLAG_LOCKED,
215     &ncstats.clp_next, "");
216 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, clp_next_fail,
217     CTLFLAG_RD | CTLFLAG_LOCKED,
218     &ncstats.clp_next_fail, "");
219 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, clp_smr_next,
220     CTLFLAG_RD | CTLFLAG_LOCKED,
221     &ncstats.clp_smr_next, "");
222 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, clp_smr_next_fail,
223     CTLFLAG_RD | CTLFLAG_LOCKED,
224     &ncstats.clp_smr_next_fail, "");
225 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, nc_lock_shared,
226     CTLFLAG_RD | CTLFLAG_LOCKED,
227     &ncstats.nc_lock_shared, "");
228 SYSCTL_LONG(_vfs_ncstats, OID_AUTO, nc_lock,
229     CTLFLAG_RD | CTLFLAG_LOCKED,
230     &ncstats.nc_lock, "");
231 
232 #define NC_SMR_STATS(v)  os_atomic_inc(&ncstats.v, relaxed)
233 #else
234 #define NC_SMR_STATS(v)
235 #endif /* COLLECT_NC_SMR_STATS */
236 
237 static vnode_t cache_lookup_locked(vnode_t dvp, struct componentname *cnp, uint32_t *vidp);
238 static vnode_t cache_lookup_smr(vnode_t dvp, struct componentname *cnp, uint32_t *vidp);
239 static const char *add_name_internal(const char *, uint32_t, u_int, boolean_t, u_int);
240 static void init_string_table(void);
241 static void cache_delete(struct namecache *, int);
242 static void cache_enter_locked(vnode_t dvp, vnode_t vp, struct componentname *cnp, const char *strname);
243 static void cache_purge_locked(vnode_t vp, kauth_cred_t *credp);
244 static void namecache_smr_free(void *, size_t);
245 static void string_smr_free(void *, size_t);
246 
247 
248 #ifdef DUMP_STRING_TABLE
249 /*
250  * Internal dump function used for debugging
251  */
252 void dump_string_table(void);
253 #endif  /* DUMP_STRING_TABLE */
254 
255 static void init_crc32(void);
256 static unsigned int crc32tab[256];
257 
258 
259 #define NCHHASH(dvp, hash_val) \
260 	(&nchashtbl[(dvp->v_id ^ (hash_val)) & nchashmask])
261 
262 /*
263  * This function tries to check if a directory vp is a subdirectory of dvp
264  * only from valid v_parent pointers. It is called with the name cache lock
265  * held and does not drop the lock anytime inside the function.
266  *
267  * It returns a boolean that indicates whether or not it was able to
268  * successfully infer the parent/descendent relationship via the v_parent
269  * pointers, or if it could not infer such relationship and that the decision
270  * must be delegated to the owning filesystem.
271  *
272  * If it does not defer the decision, i.e. it was successfuly able to determine
273  * the parent/descendent relationship,  *is_subdir tells the caller if vp is a
274  * subdirectory of dvp.
275  *
276  * If the decision is deferred, *next_vp is where it stopped i.e. *next_vp
277  * is the vnode whose parent is to be determined from the filesystem.
278  * *is_subdir, in this case, is not indicative of anything and should be
279  * ignored.
280  *
281  * The return value and output args should be used as follows :
282  *
283  * defer = cache_check_vnode_issubdir(vp, dvp, is_subdir, next_vp);
284  * if (!defer) {
285  *      if (*is_subdir)
286  *              vp is subdirectory;
287  *      else
288  *              vp is not a subdirectory;
289  * } else {
290  *      if (*next_vp)
291  *              check this vnode's parent from the filesystem
292  *      else
293  *              error (likely because of forced unmount).
294  * }
295  *
296  */
297 static boolean_t
cache_check_vnode_issubdir(vnode_t vp,vnode_t dvp,boolean_t * is_subdir,vnode_t * next_vp)298 cache_check_vnode_issubdir(vnode_t vp, vnode_t dvp, boolean_t *is_subdir,
299     vnode_t *next_vp)
300 {
301 	vnode_t tvp = vp;
302 	int defer = FALSE;
303 
304 	*is_subdir = FALSE;
305 	*next_vp = NULLVP;
306 	while (1) {
307 		mount_t tmp;
308 
309 		if (tvp == dvp) {
310 			*is_subdir = TRUE;
311 			break;
312 		} else if (tvp == rootvnode) {
313 			/* *is_subdir = FALSE */
314 			break;
315 		}
316 
317 		tmp = tvp->v_mount;
318 		while ((tvp->v_flag & VROOT) && tmp && tmp->mnt_vnodecovered &&
319 		    tvp != dvp && tvp != rootvnode) {
320 			tvp = tmp->mnt_vnodecovered;
321 			tmp = tvp->v_mount;
322 		}
323 
324 		/*
325 		 * If dvp is not at the top of a mount "stack" then
326 		 * vp is not a subdirectory of dvp either.
327 		 */
328 		if (tvp == dvp || tvp == rootvnode) {
329 			/* *is_subdir = FALSE */
330 			break;
331 		}
332 
333 		if (!tmp) {
334 			defer = TRUE;
335 			*next_vp = NULLVP;
336 			break;
337 		}
338 
339 		if ((tvp->v_flag & VISHARDLINK) || !(tvp->v_parent)) {
340 			defer = TRUE;
341 			*next_vp = tvp;
342 			break;
343 		}
344 
345 		tvp = tvp->v_parent;
346 	}
347 
348 	return defer;
349 }
350 
351 /* maximum times retry from potentially transient errors in vnode_issubdir */
352 #define MAX_ERROR_RETRY 3
353 
354 /*
355  * This function checks if a given directory (vp) is a subdirectory of dvp.
356  * It walks backwards from vp and if it hits dvp in its parent chain,
357  * it is a subdirectory. If it encounters the root directory, it is not
358  * a subdirectory.
359  *
360  * This function returns an error if it is unsuccessful and 0 on success.
361  *
362  * On entry (and exit) vp has an iocount and if this function has to take
363  * any iocounts on other vnodes in the parent chain traversal, it releases them.
364  */
365 int
vnode_issubdir(vnode_t vp,vnode_t dvp,int * is_subdir,vfs_context_t ctx)366 vnode_issubdir(vnode_t vp, vnode_t dvp, int *is_subdir, vfs_context_t ctx)
367 {
368 	vnode_t start_vp, tvp;
369 	vnode_t vp_with_iocount;
370 	int error = 0;
371 	char dotdotbuf[] = "..";
372 	int error_retry_count = 0; /* retry count for potentially transient
373 	                            *  errors */
374 
375 	*is_subdir = FALSE;
376 	tvp = start_vp = vp;
377 	/*
378 	 * Anytime we acquire an iocount in this function, we save the vnode
379 	 * in this variable and release it before exiting.
380 	 */
381 	vp_with_iocount = NULLVP;
382 
383 	while (1) {
384 		boolean_t defer;
385 		vnode_t pvp;
386 		uint32_t vid = 0;
387 		struct componentname cn;
388 		boolean_t is_subdir_locked = FALSE;
389 
390 		if (tvp == dvp) {
391 			*is_subdir = TRUE;
392 			break;
393 		} else if (tvp == rootvnode) {
394 			/* *is_subdir = FALSE */
395 			break;
396 		}
397 
398 		NAME_CACHE_LOCK_SHARED();
399 
400 		defer = cache_check_vnode_issubdir(tvp, dvp, &is_subdir_locked,
401 		    &tvp);
402 
403 		if (defer && tvp) {
404 			vid = vnode_vid(tvp);
405 			vnode_hold(tvp);
406 		}
407 
408 		NAME_CACHE_UNLOCK();
409 
410 		if (!defer) {
411 			*is_subdir = is_subdir_locked;
412 			break;
413 		}
414 
415 		if (!tvp) {
416 			if (error_retry_count++ < MAX_ERROR_RETRY) {
417 				tvp = vp;
418 				continue;
419 			}
420 			error = ENOENT;
421 			break;
422 		}
423 
424 		if (tvp != start_vp) {
425 			if (vp_with_iocount) {
426 				vnode_put(vp_with_iocount);
427 				vp_with_iocount = NULLVP;
428 			}
429 
430 			error = vnode_getwithvid(tvp, vid);
431 			vnode_drop(tvp);
432 			if (error) {
433 				if (error_retry_count++ < MAX_ERROR_RETRY) {
434 					tvp = vp;
435 					error = 0;
436 					continue;
437 				}
438 				break;
439 			}
440 			vp_with_iocount = tvp;
441 		} else {
442 			tvp = vnode_drop(tvp);
443 		}
444 
445 		bzero(&cn, sizeof(cn));
446 		cn.cn_nameiop = LOOKUP;
447 		cn.cn_flags = ISLASTCN | ISDOTDOT;
448 		cn.cn_context = ctx;
449 		cn.cn_pnbuf = &dotdotbuf[0];
450 		cn.cn_pnlen = sizeof(dotdotbuf);
451 		cn.cn_nameptr = cn.cn_pnbuf;
452 		cn.cn_namelen = 2;
453 
454 		pvp = NULLVP;
455 		if ((error = VNOP_LOOKUP(tvp, &pvp, &cn, ctx))) {
456 			break;
457 		}
458 
459 		if (!(tvp->v_flag & VISHARDLINK) && tvp->v_parent != pvp) {
460 			(void)vnode_update_identity(tvp, pvp, NULL, 0, 0,
461 			    VNODE_UPDATE_PARENT);
462 		}
463 
464 		if (vp_with_iocount) {
465 			vnode_put(vp_with_iocount);
466 		}
467 
468 		vp_with_iocount = tvp = pvp;
469 	}
470 
471 	if (vp_with_iocount) {
472 		vnode_put(vp_with_iocount);
473 	}
474 
475 	return error;
476 }
477 
478 /*
479  * This function builds the path in "buff" from the supplied vnode.
480  * The length of the buffer *INCLUDING* the trailing zero byte is
481  * returned in outlen.  NOTE: the length includes the trailing zero
482  * byte and thus the length is one greater than what strlen would
483  * return.  This is important and lots of code elsewhere in the kernel
484  * assumes this behavior.
485  *
486  * This function can call vnop in file system if the parent vnode
487  * does not exist or when called for hardlinks via volfs path.
488  * If BUILDPATH_NO_FS_ENTER is set in flags, it only uses values present
489  * in the name cache and does not enter the file system.
490  *
491  * If BUILDPATH_CHECK_MOVED is set in flags, we return EAGAIN when
492  * we encounter ENOENT during path reconstruction.  ENOENT means that
493  * one of the parents moved while we were building the path.  The
494  * caller can special handle this case by calling build_path again.
495  *
496  * If BUILDPATH_VOLUME_RELATIVE is set in flags, we return path
497  * that is relative to the nearest mount point, i.e. do not
498  * cross over mount points during building the path.
499  *
500  * passed in vp must have a valid io_count reference
501  *
502  * If parent vnode is non-NULL it also must have an io count.  This
503  * allows build_path_with_parent to be safely called for operations
504  * unlink, rmdir and rename that already have io counts on the target
505  * and the directory. In this way build_path_with_parent does not have
506  * to try and obtain an additional io count on the parent.  Taking an
507  * io count ont the parent can lead to dead lock if a forced unmount
508  * occures at the right moment. For a fuller explaination on how this
509  * can occur see the comment for vn_getpath_with_parent.
510  *
511  */
512 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)513 build_path_with_parent(vnode_t first_vp, vnode_t parent_vp, char *buff, int buflen,
514     int *outlen, size_t *mntpt_outlen, int flags, vfs_context_t ctx)
515 {
516 	vnode_t vp, tvp;
517 	vnode_t vp_with_iocount;
518 	vnode_t proc_root_dir_vp;
519 	char *end;
520 	char *mntpt_end;
521 	const char *str;
522 	unsigned int  len;
523 	int  ret = 0;
524 	int  fixhardlink;
525 
526 	if (first_vp == NULLVP) {
527 		return EINVAL;
528 	}
529 
530 	if (buflen <= 1) {
531 		return ENOSPC;
532 	}
533 
534 	/*
535 	 * Grab the process fd so we can evaluate fd_rdir.
536 	 */
537 	if (!(flags & BUILDPATH_NO_PROCROOT)) {
538 		proc_root_dir_vp = vfs_context_proc(ctx)->p_fd.fd_rdir;
539 	} else {
540 		proc_root_dir_vp = NULL;
541 	}
542 
543 	vp_with_iocount = NULLVP;
544 again:
545 	vp = first_vp;
546 
547 	end = &buff[buflen - 1];
548 	*end = '\0';
549 	mntpt_end = NULL;
550 
551 	/*
552 	 * Catch a special corner case here: chroot to /full/path/to/dir, chdir to
553 	 * it, then open it. Without this check, the path to it will be
554 	 * /full/path/to/dir instead of "/".
555 	 */
556 	if (proc_root_dir_vp == first_vp) {
557 		*--end = '/';
558 		goto out;
559 	}
560 
561 	/*
562 	 * holding the NAME_CACHE_LOCK in shared mode is
563 	 * sufficient to stabilize both the vp->v_parent chain
564 	 * and the 'vp->v_mount->mnt_vnodecovered' chain
565 	 *
566 	 * if we need to drop this lock, we must first grab the v_id
567 	 * from the vnode we're currently working with... if that
568 	 * vnode doesn't already have an io_count reference (the vp
569 	 * passed in comes with one), we must grab a reference
570 	 * after we drop the NAME_CACHE_LOCK via vnode_getwithvid...
571 	 * deadlocks may result if you call vnode_get while holding
572 	 * the NAME_CACHE_LOCK... we lazily release the reference
573 	 * we pick up the next time we encounter a need to drop
574 	 * the NAME_CACHE_LOCK or before we return from this routine
575 	 */
576 	NAME_CACHE_LOCK_SHARED();
577 
578 #if CONFIG_FIRMLINKS
579 	if (!(flags & BUILDPATH_NO_FIRMLINK) &&
580 	    (vp->v_flag & VFMLINKTARGET) && vp->v_fmlink && (vp->v_fmlink->v_type == VDIR)) {
581 		vp = vp->v_fmlink;
582 	}
583 #endif
584 
585 	/*
586 	 * Check if this is the root of a file system.
587 	 */
588 	while (vp && vp->v_flag & VROOT) {
589 		if (vp->v_mount == NULL) {
590 			ret = EINVAL;
591 			goto out_unlock;
592 		}
593 		if ((vp->v_mount->mnt_flag & MNT_ROOTFS) || (vp == proc_root_dir_vp)) {
594 			/*
595 			 * It's the root of the root file system, so it's
596 			 * just "/".
597 			 */
598 			*--end = '/';
599 
600 			goto out_unlock;
601 		} else {
602 			/*
603 			 * This the root of the volume and the caller does not
604 			 * want to cross mount points.  Therefore just return
605 			 * '/' as the relative path.
606 			 */
607 #if CONFIG_FIRMLINKS
608 			if (!(flags & BUILDPATH_NO_FIRMLINK) &&
609 			    (vp->v_flag & VFMLINKTARGET) && vp->v_fmlink && (vp->v_fmlink->v_type == VDIR)) {
610 				vp = vp->v_fmlink;
611 			} else
612 #endif
613 			if (flags & BUILDPATH_VOLUME_RELATIVE) {
614 				*--end = '/';
615 				goto out_unlock;
616 			} else {
617 				vp = vp->v_mount->mnt_vnodecovered;
618 				if (!mntpt_end && vp) {
619 					mntpt_end = end;
620 				}
621 			}
622 		}
623 	}
624 
625 	while ((vp != NULLVP) && (vp->v_parent != vp)) {
626 		int  vid;
627 
628 		/*
629 		 * For hardlinks the v_name may be stale, so if its OK
630 		 * to enter a file system, ask the file system for the
631 		 * name and parent (below).
632 		 */
633 		fixhardlink = (vp->v_flag & VISHARDLINK) &&
634 		    (vp->v_mount->mnt_kern_flag & MNTK_PATH_FROM_ID) &&
635 		    !(flags & BUILDPATH_NO_FS_ENTER);
636 
637 		if (!fixhardlink) {
638 			str = vp->v_name;
639 
640 			if (str == NULL || *str == '\0') {
641 				if (vp->v_parent != NULL) {
642 					ret = EINVAL;
643 				} else {
644 					ret = ENOENT;
645 				}
646 				goto out_unlock;
647 			}
648 			len = (unsigned int)strlen(str);
649 			/*
650 			 * Check that there's enough space (including space for the '/')
651 			 */
652 			if ((unsigned int)(end - buff) < (len + 1)) {
653 				ret = ENOSPC;
654 				goto out_unlock;
655 			}
656 			/*
657 			 * Copy the name backwards.
658 			 */
659 			str += len;
660 
661 			for (; len > 0; len--) {
662 				*--end = *--str;
663 			}
664 			/*
665 			 * Add a path separator.
666 			 */
667 			*--end = '/';
668 		}
669 
670 		/*
671 		 * Walk up the parent chain.
672 		 */
673 		if (((vp->v_parent != NULLVP) && !fixhardlink) ||
674 		    (flags & BUILDPATH_NO_FS_ENTER)) {
675 			/*
676 			 * In this if () block we are not allowed to enter the filesystem
677 			 * to conclusively get the most accurate parent identifier.
678 			 * As a result, if 'vp' does not identify '/' and it
679 			 * does not have a valid v_parent, then error out
680 			 * and disallow further path construction
681 			 */
682 			if ((vp->v_parent == NULLVP) && (rootvnode != vp)) {
683 				/*
684 				 * Only '/' is allowed to have a NULL parent
685 				 * pointer. Upper level callers should ideally
686 				 * re-drive name lookup on receiving a ENOENT.
687 				 */
688 				ret = ENOENT;
689 
690 				/* The code below will exit early if 'tvp = vp' == NULL */
691 			}
692 			vp = vp->v_parent;
693 
694 			/*
695 			 * if the vnode we have in hand isn't a directory and it
696 			 * has a v_parent, then we started with the resource fork
697 			 * so skip up to avoid getting a duplicate copy of the
698 			 * file name in the path.
699 			 */
700 			if (vp && !vnode_isdir(vp) && vp->v_parent) {
701 				vp = vp->v_parent;
702 			}
703 		} else {
704 			/*
705 			 * No parent, go get it if supported.
706 			 */
707 			struct vnode_attr  va;
708 			vnode_t  dvp;
709 
710 			/*
711 			 * Make sure file system supports obtaining a path from id.
712 			 */
713 			if (!(vp->v_mount->mnt_kern_flag & MNTK_PATH_FROM_ID)) {
714 				ret = ENOENT;
715 				goto out_unlock;
716 			}
717 			vid = vp->v_id;
718 
719 			vnode_hold(vp);
720 			NAME_CACHE_UNLOCK();
721 
722 			if (vp != first_vp && vp != parent_vp && vp != vp_with_iocount) {
723 				if (vp_with_iocount) {
724 					vnode_put(vp_with_iocount);
725 					vp_with_iocount = NULLVP;
726 				}
727 				if (vnode_getwithvid(vp, vid)) {
728 					vnode_drop(vp);
729 					goto again;
730 				}
731 				vp_with_iocount = vp;
732 			}
733 
734 			vnode_drop(vp);
735 
736 			VATTR_INIT(&va);
737 			VATTR_WANTED(&va, va_parentid);
738 
739 			if (fixhardlink) {
740 				VATTR_WANTED(&va, va_name);
741 				va.va_name = zalloc(ZV_NAMEI);
742 			} else {
743 				va.va_name = NULL;
744 			}
745 			/*
746 			 * Ask the file system for its parent id and for its name (optional).
747 			 */
748 			ret = vnode_getattr(vp, &va, ctx);
749 
750 			if (fixhardlink) {
751 				if ((ret == 0) && (VATTR_IS_SUPPORTED(&va, va_name))) {
752 					str = va.va_name;
753 					vnode_update_identity(vp, NULL, str, (unsigned int)strlen(str), 0, VNODE_UPDATE_NAME);
754 				} else if (vp->v_name) {
755 					str = vp->v_name;
756 					ret = 0;
757 				} else {
758 					ret = ENOENT;
759 					goto bad_news;
760 				}
761 				len = (unsigned int)strlen(str);
762 
763 				/*
764 				 * Check that there's enough space.
765 				 */
766 				if ((unsigned int)(end - buff) < (len + 1)) {
767 					ret = ENOSPC;
768 				} else {
769 					/* Copy the name backwards. */
770 					str += len;
771 
772 					for (; len > 0; len--) {
773 						*--end = *--str;
774 					}
775 					/*
776 					 * Add a path separator.
777 					 */
778 					*--end = '/';
779 				}
780 bad_news:
781 				zfree(ZV_NAMEI, va.va_name);
782 			}
783 			if (ret || !VATTR_IS_SUPPORTED(&va, va_parentid)) {
784 				ret = ENOENT;
785 				goto out;
786 			}
787 			/*
788 			 * Ask the file system for the parent vnode.
789 			 */
790 			if ((ret = VFS_VGET(vp->v_mount, (ino64_t)va.va_parentid, &dvp, ctx))) {
791 				goto out;
792 			}
793 
794 			if (!fixhardlink && (vp->v_parent != dvp)) {
795 				vnode_update_identity(vp, dvp, NULL, 0, 0, VNODE_UPDATE_PARENT);
796 			}
797 
798 			if (vp_with_iocount) {
799 				vnode_put(vp_with_iocount);
800 			}
801 			vp = dvp;
802 			vp_with_iocount = vp;
803 
804 			NAME_CACHE_LOCK_SHARED();
805 
806 			/*
807 			 * if the vnode we have in hand isn't a directory and it
808 			 * has a v_parent, then we started with the resource fork
809 			 * so skip up to avoid getting a duplicate copy of the
810 			 * file name in the path.
811 			 */
812 			if (vp && !vnode_isdir(vp) && vp->v_parent) {
813 				vp = vp->v_parent;
814 			}
815 		}
816 
817 		if (vp && (flags & BUILDPATH_CHECKACCESS)) {
818 			vid = vp->v_id;
819 
820 			vnode_hold(vp);
821 			NAME_CACHE_UNLOCK();
822 
823 			if (vp != first_vp && vp != parent_vp && vp != vp_with_iocount) {
824 				if (vp_with_iocount) {
825 					vnode_put(vp_with_iocount);
826 					vp_with_iocount = NULLVP;
827 				}
828 				if (vnode_getwithvid(vp, vid)) {
829 					vnode_drop(vp);
830 					goto again;
831 				}
832 				vp_with_iocount = vp;
833 			}
834 			vnode_drop(vp);
835 
836 			if ((ret = vnode_authorize(vp, NULL, KAUTH_VNODE_SEARCH, ctx))) {
837 				goto out;       /* no peeking */
838 			}
839 			NAME_CACHE_LOCK_SHARED();
840 		}
841 
842 		/*
843 		 * When a mount point is crossed switch the vp.
844 		 * Continue until we find the root or we find
845 		 * a vnode that's not the root of a mounted
846 		 * file system.
847 		 */
848 		tvp = vp;
849 
850 		while (tvp) {
851 			if (tvp == proc_root_dir_vp) {
852 				goto out_unlock;        /* encountered the root */
853 			}
854 
855 #if CONFIG_FIRMLINKS
856 			if (!(flags & BUILDPATH_NO_FIRMLINK) &&
857 			    (tvp->v_flag & VFMLINKTARGET) && tvp->v_fmlink && (tvp->v_fmlink->v_type == VDIR)) {
858 				tvp = tvp->v_fmlink;
859 				break;
860 			}
861 #endif
862 
863 			if (!(tvp->v_flag & VROOT) || !tvp->v_mount) {
864 				break;                  /* not the root of a mounted FS */
865 			}
866 			if (flags & BUILDPATH_VOLUME_RELATIVE) {
867 				/* Do not cross over mount points */
868 				tvp = NULL;
869 			} else {
870 				tvp = tvp->v_mount->mnt_vnodecovered;
871 				if (!mntpt_end && tvp) {
872 					mntpt_end = end;
873 				}
874 			}
875 		}
876 		if (tvp == NULLVP) {
877 			goto out_unlock;
878 		}
879 		vp = tvp;
880 	}
881 out_unlock:
882 	NAME_CACHE_UNLOCK();
883 out:
884 	if (vp_with_iocount) {
885 		vnode_put(vp_with_iocount);
886 	}
887 	/*
888 	 * Slide the name down to the beginning of the buffer.
889 	 */
890 	memmove(buff, end, &buff[buflen] - end);
891 
892 	/*
893 	 * length includes the trailing zero byte
894 	 */
895 	*outlen = (int)(&buff[buflen] - end);
896 	if (mntpt_outlen && mntpt_end) {
897 		*mntpt_outlen = (size_t)*outlen - (size_t)(&buff[buflen] - mntpt_end);
898 	}
899 
900 	/* One of the parents was moved during path reconstruction.
901 	 * The caller is interested in knowing whether any of the
902 	 * parents moved via BUILDPATH_CHECK_MOVED, so return EAGAIN.
903 	 */
904 	if ((ret == ENOENT) && (flags & BUILDPATH_CHECK_MOVED)) {
905 		ret = EAGAIN;
906 	}
907 
908 	return ret;
909 }
910 
911 int
build_path(vnode_t first_vp,char * buff,int buflen,int * outlen,int flags,vfs_context_t ctx)912 build_path(vnode_t first_vp, char *buff, int buflen, int *outlen, int flags, vfs_context_t ctx)
913 {
914 	return build_path_with_parent(first_vp, NULL, buff, buflen, outlen, NULL, flags, ctx);
915 }
916 
917 /*
918  * return NULLVP if vp's parent doesn't
919  * exist, or we can't get a valid iocount
920  * else return the parent of vp
921  */
922 vnode_t
vnode_getparent(vnode_t vp)923 vnode_getparent(vnode_t vp)
924 {
925 	vnode_t pvp = NULLVP;
926 	int     pvid;
927 
928 	NAME_CACHE_LOCK_SHARED();
929 
930 	pvp = vp->v_parent;
931 
932 	/*
933 	 * v_parent is stable behind the name_cache lock
934 	 * however, the only thing we can really guarantee
935 	 * is that we've grabbed a valid iocount on the
936 	 * parent of 'vp' at the time we took the name_cache lock...
937 	 * once we drop the lock, vp could get re-parented
938 	 */
939 	if (pvp != NULLVP) {
940 		pvid = pvp->v_id;
941 
942 		vnode_hold(pvp);
943 		NAME_CACHE_UNLOCK();
944 
945 		if (vnode_getwithvid(pvp, pvid) != 0) {
946 			vnode_drop(pvp);
947 			pvp = NULL;
948 		} else {
949 			vnode_drop(pvp);
950 		}
951 	} else {
952 		NAME_CACHE_UNLOCK();
953 	}
954 	return pvp;
955 }
956 
957 /*
958  * Similar to vnode_getparent() but only returned parent vnode (with iocount
959  * held) if the actual parent vnode is different than the given 'pvp'.
960  */
961 __private_extern__ vnode_t
vnode_getparent_if_different(vnode_t vp,vnode_t pvp)962 vnode_getparent_if_different(vnode_t vp, vnode_t pvp)
963 {
964 	vnode_t real_pvp = NULLVP;
965 	int     pvid;
966 
967 	if (vp->v_parent == pvp) {
968 		goto out;
969 	}
970 
971 	NAME_CACHE_LOCK_SHARED();
972 
973 	real_pvp = vp->v_parent;
974 	if (real_pvp == NULLVP) {
975 		NAME_CACHE_UNLOCK();
976 		goto out;
977 	}
978 
979 	/*
980 	 * Do the check again after namecache lock is acquired as the parent vnode
981 	 * could have changed.
982 	 */
983 	if (real_pvp != pvp) {
984 		pvid = real_pvp->v_id;
985 
986 		vnode_hold(real_pvp);
987 		NAME_CACHE_UNLOCK();
988 
989 		if (vnode_getwithvid(real_pvp, pvid) != 0) {
990 			vnode_drop(real_pvp);
991 			real_pvp = NULLVP;
992 		} else {
993 			vnode_drop(real_pvp);
994 		}
995 	} else {
996 		real_pvp = NULLVP;
997 		NAME_CACHE_UNLOCK();
998 	}
999 
1000 out:
1001 	return real_pvp;
1002 }
1003 
1004 const char *
vnode_getname(vnode_t vp)1005 vnode_getname(vnode_t vp)
1006 {
1007 	const char *name = NULL;
1008 
1009 	NAME_CACHE_LOCK_SHARED();
1010 
1011 	if (vp->v_name) {
1012 		name = vfs_addname(vp->v_name, (unsigned int)strlen(vp->v_name), 0, 0);
1013 	}
1014 	NAME_CACHE_UNLOCK();
1015 
1016 	return name;
1017 }
1018 
1019 void
vnode_putname(const char * name)1020 vnode_putname(const char *name)
1021 {
1022 	vfs_removename(name);
1023 }
1024 
1025 static const char unknown_vnodename[] = "(unknown vnode name)";
1026 
1027 const char *
vnode_getname_printable(vnode_t vp)1028 vnode_getname_printable(vnode_t vp)
1029 {
1030 	const char *name = vnode_getname(vp);
1031 	if (name != NULL) {
1032 		return name;
1033 	}
1034 
1035 	switch (vp->v_type) {
1036 	case VCHR:
1037 	case VBLK:
1038 	{
1039 		/*
1040 		 * Create an artificial dev name from
1041 		 * major and minor device number
1042 		 */
1043 		char dev_name[64];
1044 		(void) snprintf(dev_name, sizeof(dev_name),
1045 		    "%c(%u, %u)", VCHR == vp->v_type ? 'c':'b',
1046 		    major(vp->v_rdev), minor(vp->v_rdev));
1047 		/*
1048 		 * Add the newly created dev name to the name
1049 		 * cache to allow easier cleanup. Also,
1050 		 * vfs_addname allocates memory for the new name
1051 		 * and returns it.
1052 		 */
1053 		NAME_CACHE_LOCK_SHARED();
1054 		name = vfs_addname(dev_name, (unsigned int)strlen(dev_name), 0, 0);
1055 		NAME_CACHE_UNLOCK();
1056 		return name;
1057 	}
1058 	default:
1059 		return unknown_vnodename;
1060 	}
1061 }
1062 
1063 void
vnode_putname_printable(const char * name)1064 vnode_putname_printable(const char *name)
1065 {
1066 	if (name == unknown_vnodename) {
1067 		return;
1068 	}
1069 	vnode_putname(name);
1070 }
1071 
1072 
1073 /*
1074  * if VNODE_UPDATE_PARENT, and we can take
1075  * a reference on dvp, then update vp with
1076  * it's new parent... if vp already has a parent,
1077  * then drop the reference vp held on it
1078  *
1079  * if VNODE_UPDATE_NAME,
1080  * then drop string ref on v_name if it exists, and if name is non-NULL
1081  * then pick up a string reference on name and record it in v_name...
1082  * optionally pass in the length and hashval of name if known
1083  *
1084  * if VNODE_UPDATE_CACHE, flush the name cache entries associated with vp
1085  */
1086 void
vnode_update_identity(vnode_t vp,vnode_t dvp,const char * name,int name_len,uint32_t name_hashval,int flags)1087 vnode_update_identity(vnode_t vp, vnode_t dvp, const char *name, int name_len, uint32_t name_hashval, int flags)
1088 {
1089 	struct  namecache *ncp;
1090 	vnode_t old_parentvp = NULLVP;
1091 	int isstream = (vp->v_flag & VISNAMEDSTREAM);
1092 	int kusecountbumped = 0;
1093 	kauth_cred_t tcred = NULL;
1094 	const char *vname = NULL;
1095 	const char *tname = NULL;
1096 
1097 	if (name_len < 0) {
1098 		return;
1099 	}
1100 
1101 	if (flags & VNODE_UPDATE_PARENT) {
1102 		if (dvp && vnode_ref(dvp) != 0) {
1103 			dvp = NULLVP;
1104 		}
1105 		/* Don't count a stream's parent ref during unmounts */
1106 		if (isstream && dvp && (dvp != vp) && (dvp != vp->v_parent) && (dvp->v_type == VREG)) {
1107 			vnode_lock_spin(dvp);
1108 			++dvp->v_kusecount;
1109 			kusecountbumped = 1;
1110 			vnode_unlock(dvp);
1111 		}
1112 	} else {
1113 		dvp = NULLVP;
1114 	}
1115 	if ((flags & VNODE_UPDATE_NAME)) {
1116 		if (name != vp->v_name) {
1117 			if (name && *name) {
1118 				if (name_len == 0) {
1119 					name_len = (int)strlen(name);
1120 				}
1121 				tname = vfs_addname(name, name_len, name_hashval, 0);
1122 			}
1123 		} else {
1124 			flags &= ~VNODE_UPDATE_NAME;
1125 		}
1126 	}
1127 	if ((flags & (VNODE_UPDATE_PURGE | VNODE_UPDATE_PARENT | VNODE_UPDATE_CACHE | VNODE_UPDATE_NAME | VNODE_UPDATE_PURGEFIRMLINK))) {
1128 		NAME_CACHE_LOCK();
1129 
1130 #if CONFIG_FIRMLINKS
1131 		if (flags & VNODE_UPDATE_PURGEFIRMLINK) {
1132 			vnode_t old_fvp = vp->v_fmlink;
1133 			if (old_fvp) {
1134 				vnode_lock_spin(vp);
1135 				vp->v_flag &= ~VFMLINKTARGET;
1136 				vp->v_fmlink = NULLVP;
1137 				vnode_unlock(vp);
1138 				NAME_CACHE_UNLOCK();
1139 
1140 				/*
1141 				 * vnode_rele can result in cascading series of
1142 				 * usecount releases. The combination of calling
1143 				 * vnode_recycle and dont_reenter (3rd arg to
1144 				 * vnode_rele_internal) ensures we don't have
1145 				 * that issue.
1146 				 */
1147 				vnode_recycle(old_fvp);
1148 				vnode_rele_internal(old_fvp, O_EVTONLY, 1, 0);
1149 
1150 				NAME_CACHE_LOCK();
1151 			}
1152 		}
1153 #endif
1154 
1155 		if ((flags & VNODE_UPDATE_PURGE)) {
1156 			if (vp->v_parent) {
1157 				vp->v_parent->v_nc_generation++;
1158 			}
1159 
1160 			while ((ncp = LIST_FIRST(&vp->v_nclinks))) {
1161 				cache_delete(ncp, 1);
1162 			}
1163 
1164 			while ((ncp = TAILQ_FIRST(&vp->v_ncchildren))) {
1165 				cache_delete(ncp, 1);
1166 			}
1167 
1168 			/*
1169 			 * Use a temp variable to avoid kauth_cred_drop() while NAME_CACHE_LOCK is held
1170 			 */
1171 			tcred = vnode_cred(vp);
1172 			vp->v_cred = NOCRED;
1173 			vp->v_authorized_actions = 0;
1174 			vp->v_cred_timestamp = 0;
1175 		}
1176 		if ((flags & VNODE_UPDATE_NAME)) {
1177 			vname = vp->v_name;
1178 			vp->v_name = tname;
1179 		}
1180 		if (flags & VNODE_UPDATE_PARENT) {
1181 			if (dvp != vp && dvp != vp->v_parent) {
1182 				old_parentvp = vp->v_parent;
1183 				vp->v_parent = dvp;
1184 				dvp = NULLVP;
1185 
1186 				if (old_parentvp) {
1187 					flags |= VNODE_UPDATE_CACHE;
1188 				}
1189 			}
1190 		}
1191 		if (flags & VNODE_UPDATE_CACHE) {
1192 			while ((ncp = LIST_FIRST(&vp->v_nclinks))) {
1193 				cache_delete(ncp, 1);
1194 			}
1195 		}
1196 		NAME_CACHE_UNLOCK();
1197 
1198 		if (vname != NULL) {
1199 			vfs_removename(vname);
1200 		}
1201 
1202 		if (IS_VALID_CRED(tcred)) {
1203 			kauth_cred_unref(&tcred);
1204 		}
1205 	}
1206 	if (dvp != NULLVP) {
1207 		/* Back-out the ref we took if we lost a race for vp->v_parent. */
1208 		if (kusecountbumped) {
1209 			vnode_lock_spin(dvp);
1210 			if (dvp->v_kusecount > 0) {
1211 				--dvp->v_kusecount;
1212 			}
1213 			vnode_unlock(dvp);
1214 		}
1215 		vnode_rele(dvp);
1216 	}
1217 	if (old_parentvp) {
1218 		struct  uthread *ut;
1219 		vnode_t vreclaims = NULLVP;
1220 
1221 		if (isstream) {
1222 			vnode_lock_spin(old_parentvp);
1223 			if ((old_parentvp->v_type != VDIR) && (old_parentvp->v_kusecount > 0)) {
1224 				--old_parentvp->v_kusecount;
1225 			}
1226 			vnode_unlock(old_parentvp);
1227 		}
1228 		ut = current_uthread();
1229 
1230 		/*
1231 		 * indicated to vnode_rele that it shouldn't do a
1232 		 * vnode_reclaim at this time... instead it will
1233 		 * chain the vnode to the uu_vreclaims list...
1234 		 * we'll be responsible for calling vnode_reclaim
1235 		 * on each of the vnodes in this list...
1236 		 */
1237 		ut->uu_defer_reclaims = 1;
1238 		ut->uu_vreclaims = NULLVP;
1239 
1240 		while ((vp = old_parentvp) != NULLVP) {
1241 			vnode_hold(vp);
1242 			vnode_lock_spin(vp);
1243 			vnode_rele_internal(vp, 0, 0, 1);
1244 
1245 			/*
1246 			 * check to see if the vnode is now in the state
1247 			 * that would have triggered a vnode_reclaim in vnode_rele
1248 			 * if it is, we save it's parent pointer and then NULL
1249 			 * out the v_parent field... we'll drop the reference
1250 			 * that was held on the next iteration of this loop...
1251 			 * this short circuits a potential deep recursion if we
1252 			 * have a long chain of parents in this state...
1253 			 * we'll sit in this loop until we run into
1254 			 * a parent in this chain that is not in this state
1255 			 *
1256 			 * make our check and the vnode_rele atomic
1257 			 * with respect to the current vnode we're working on
1258 			 * by holding the vnode lock
1259 			 * if vnode_rele deferred the vnode_reclaim and has put
1260 			 * this vnode on the list to be reaped by us, than
1261 			 * it has left this vnode with an iocount == 1
1262 			 */
1263 			if (ut->uu_vreclaims == vp) {
1264 				/*
1265 				 * This vnode is on the head of the uu_vreclaims chain
1266 				 * which means vnode_rele wanted to do a vnode_reclaim
1267 				 * on this vnode. Pull the parent pointer now so that when we do the
1268 				 * vnode_reclaim for each of the vnodes in the uu_vreclaims
1269 				 * list, we won't recurse back through here
1270 				 *
1271 				 * need to do a convert here in case vnode_rele_internal
1272 				 * returns with the lock held in the spin mode... it
1273 				 * can drop and retake the lock under certain circumstances
1274 				 */
1275 				vnode_lock_convert(vp);
1276 
1277 				NAME_CACHE_LOCK();
1278 				old_parentvp = vp->v_parent;
1279 				vp->v_parent = NULLVP;
1280 				NAME_CACHE_UNLOCK();
1281 			} else {
1282 				/*
1283 				 * we're done... we ran into a vnode that isn't
1284 				 * being terminated
1285 				 */
1286 				old_parentvp = NULLVP;
1287 			}
1288 			vnode_drop_and_unlock(vp);
1289 		}
1290 		vreclaims = ut->uu_vreclaims;
1291 		ut->uu_vreclaims = NULLVP;
1292 		ut->uu_defer_reclaims = 0;
1293 
1294 		while ((vp = vreclaims) != NULLVP) {
1295 			vreclaims = vp->v_defer_reclaimlist;
1296 
1297 			/*
1298 			 * vnode_put will drive the vnode_reclaim if
1299 			 * we are still the only reference on this vnode
1300 			 */
1301 			vnode_put(vp);
1302 		}
1303 	}
1304 }
1305 
1306 #if CONFIG_FIRMLINKS
1307 errno_t
vnode_setasfirmlink(vnode_t vp,vnode_t target_vp)1308 vnode_setasfirmlink(vnode_t vp, vnode_t target_vp)
1309 {
1310 	int error = 0;
1311 	vnode_t old_target_vp = NULLVP;
1312 	vnode_t old_target_vp_v_fmlink = NULLVP;
1313 	kauth_cred_t target_vp_cred = NULL;
1314 	kauth_cred_t old_target_vp_cred = NULL;
1315 
1316 	if (!vp) {
1317 		return EINVAL;
1318 	}
1319 
1320 	if (target_vp) {
1321 		if (vp->v_fmlink == target_vp) { /* Will be checked again under the name cache lock */
1322 			return 0;
1323 		}
1324 
1325 		/*
1326 		 * Firmlink source and target will take both a usecount
1327 		 * and kusecount on each other.
1328 		 */
1329 		if ((error = vnode_ref_ext(target_vp, O_EVTONLY, VNODE_REF_FORCE))) {
1330 			return error;
1331 		}
1332 
1333 		if ((error = vnode_ref_ext(vp, O_EVTONLY, VNODE_REF_FORCE))) {
1334 			vnode_rele_ext(target_vp, O_EVTONLY, 1);
1335 			return error;
1336 		}
1337 	}
1338 
1339 	NAME_CACHE_LOCK();
1340 
1341 	old_target_vp = vp->v_fmlink;
1342 	if (target_vp && (target_vp == old_target_vp)) {
1343 		NAME_CACHE_UNLOCK();
1344 		return 0;
1345 	}
1346 	vp->v_fmlink = target_vp;
1347 
1348 	vnode_lock_spin(vp);
1349 	vp->v_flag &= ~VFMLINKTARGET;
1350 	vnode_unlock(vp);
1351 
1352 	if (target_vp) {
1353 		target_vp->v_fmlink = vp;
1354 		vnode_lock_spin(target_vp);
1355 		target_vp->v_flag |= VFMLINKTARGET;
1356 		vnode_unlock(target_vp);
1357 		cache_purge_locked(vp, &target_vp_cred);
1358 	}
1359 
1360 	if (old_target_vp) {
1361 		old_target_vp_v_fmlink = old_target_vp->v_fmlink;
1362 		old_target_vp->v_fmlink = NULLVP;
1363 		vnode_lock_spin(old_target_vp);
1364 		old_target_vp->v_flag &= ~VFMLINKTARGET;
1365 		vnode_unlock(old_target_vp);
1366 		cache_purge_locked(vp, &old_target_vp_cred);
1367 	}
1368 
1369 	NAME_CACHE_UNLOCK();
1370 
1371 	if (IS_VALID_CRED(target_vp_cred)) {
1372 		kauth_cred_unref(&target_vp_cred);
1373 	}
1374 
1375 	if (old_target_vp) {
1376 		if (IS_VALID_CRED(old_target_vp_cred)) {
1377 			kauth_cred_unref(&old_target_vp_cred);
1378 		}
1379 
1380 		vnode_rele_ext(old_target_vp, O_EVTONLY, 1);
1381 		if (old_target_vp_v_fmlink) {
1382 			vnode_rele_ext(old_target_vp_v_fmlink, O_EVTONLY, 1);
1383 		}
1384 	}
1385 
1386 	return 0;
1387 }
1388 
1389 errno_t
vnode_getfirmlink(vnode_t vp,vnode_t * target_vp)1390 vnode_getfirmlink(vnode_t vp, vnode_t *target_vp)
1391 {
1392 	int error;
1393 
1394 	if (!vp->v_fmlink) {
1395 		return ENODEV;
1396 	}
1397 
1398 	NAME_CACHE_LOCK_SHARED();
1399 	if (vp->v_fmlink && !(vp->v_flag & VFMLINKTARGET) &&
1400 	    (vnode_get(vp->v_fmlink) == 0)) {
1401 		vnode_t tvp = vp->v_fmlink;
1402 
1403 		vnode_lock_spin(tvp);
1404 		if (tvp->v_lflag & (VL_TERMINATE | VL_DEAD)) {
1405 			vnode_unlock(tvp);
1406 			NAME_CACHE_UNLOCK();
1407 			vnode_put(tvp);
1408 			return ENOENT;
1409 		}
1410 		if (!(tvp->v_flag & VFMLINKTARGET)) {
1411 			panic("firmlink target for vnode %p does not have flag set", vp);
1412 		}
1413 		vnode_unlock(tvp);
1414 		*target_vp = tvp;
1415 		error = 0;
1416 	} else {
1417 		*target_vp = NULLVP;
1418 		error = ENODEV;
1419 	}
1420 	NAME_CACHE_UNLOCK();
1421 	return error;
1422 }
1423 
1424 #else /* CONFIG_FIRMLINKS */
1425 
1426 errno_t
vnode_setasfirmlink(__unused vnode_t vp,__unused vnode_t src_vp)1427 vnode_setasfirmlink(__unused vnode_t vp, __unused vnode_t src_vp)
1428 {
1429 	return ENOTSUP;
1430 }
1431 
1432 errno_t
vnode_getfirmlink(__unused vnode_t vp,__unused vnode_t * target_vp)1433 vnode_getfirmlink(__unused vnode_t vp, __unused vnode_t *target_vp)
1434 {
1435 	return ENOTSUP;
1436 }
1437 
1438 #endif
1439 
1440 /*
1441  * Mark a vnode as having multiple hard links.  HFS makes use of this
1442  * because it keeps track of each link separately, and wants to know
1443  * which link was actually used.
1444  *
1445  * This will cause the name cache to force a VNOP_LOOKUP on the vnode
1446  * so that HFS can post-process the lookup.  Also, volfs will call
1447  * VNOP_GETATTR2 to determine the parent, instead of using v_parent.
1448  */
1449 void
vnode_setmultipath(vnode_t vp)1450 vnode_setmultipath(vnode_t vp)
1451 {
1452 	vnode_lock_spin(vp);
1453 
1454 	/*
1455 	 * In theory, we're changing the vnode's identity as far as the
1456 	 * name cache is concerned, so we ought to grab the name cache lock
1457 	 * here.  However, there is already a race, and grabbing the name
1458 	 * cache lock only makes the race window slightly smaller.
1459 	 *
1460 	 * The race happens because the vnode already exists in the name
1461 	 * cache, and could be found by one thread before another thread
1462 	 * can set the hard link flag.
1463 	 */
1464 
1465 	vp->v_flag |= VISHARDLINK;
1466 
1467 	vnode_unlock(vp);
1468 }
1469 
1470 
1471 
1472 /*
1473  * backwards compatibility
1474  */
1475 void
vnode_uncache_credentials(vnode_t vp)1476 vnode_uncache_credentials(vnode_t vp)
1477 {
1478 	vnode_uncache_authorized_action(vp, KAUTH_INVALIDATE_CACHED_RIGHTS);
1479 }
1480 
1481 
1482 /*
1483  * use the exclusive form of NAME_CACHE_LOCK to protect the update of the
1484  * following fields in the vnode: v_cred_timestamp, v_cred, v_authorized_actions
1485  * we use this lock so that we can look at the v_cred and v_authorized_actions
1486  * atomically while behind the NAME_CACHE_LOCK in shared mode in 'cache_lookup_path',
1487  * which is the super-hot path... if we are updating the authorized actions for this
1488  * vnode, we are already in the super-slow and far less frequented path so its not
1489  * that bad that we take the lock exclusive for this case... of course we strive
1490  * to hold it for the minimum amount of time possible
1491  */
1492 
1493 void
vnode_uncache_authorized_action(vnode_t vp,kauth_action_t action)1494 vnode_uncache_authorized_action(vnode_t vp, kauth_action_t action)
1495 {
1496 	kauth_cred_t tcred = NOCRED;
1497 
1498 	NAME_CACHE_LOCK();
1499 
1500 	vp->v_authorized_actions &= ~action;
1501 
1502 	if (action == KAUTH_INVALIDATE_CACHED_RIGHTS &&
1503 	    IS_VALID_CRED(vp->v_cred)) {
1504 		/*
1505 		 * Use a temp variable to avoid kauth_cred_unref() while NAME_CACHE_LOCK is held
1506 		 */
1507 		tcred = vnode_cred(vp);
1508 		vp->v_cred = NOCRED;
1509 	}
1510 	NAME_CACHE_UNLOCK();
1511 
1512 	if (IS_VALID_CRED(tcred)) {
1513 		kauth_cred_unref(&tcred);
1514 	}
1515 }
1516 
1517 
1518 /* disable vnode_cache_is_authorized() by setting vnode_cache_defeat */
1519 static TUNABLE(int, bootarg_vnode_cache_defeat, "-vnode_cache_defeat", 0);
1520 
1521 boolean_t
vnode_cache_is_authorized(vnode_t vp,vfs_context_t ctx,kauth_action_t action)1522 vnode_cache_is_authorized(vnode_t vp, vfs_context_t ctx, kauth_action_t action)
1523 {
1524 	kauth_cred_t    ucred;
1525 	boolean_t       retval = FALSE;
1526 
1527 	/* Boot argument to defeat rights caching */
1528 	if (bootarg_vnode_cache_defeat) {
1529 		return FALSE;
1530 	}
1531 
1532 	if ((vp->v_mount->mnt_kern_flag & (MNTK_AUTH_OPAQUE | MNTK_AUTH_CACHE_TTL))) {
1533 		/*
1534 		 * a TTL is enabled on the rights cache... handle it here
1535 		 * a TTL of 0 indicates that no rights should be cached
1536 		 */
1537 		if (vp->v_mount->mnt_authcache_ttl) {
1538 			if (!(vp->v_mount->mnt_kern_flag & MNTK_AUTH_CACHE_TTL)) {
1539 				/*
1540 				 * For filesystems marked only MNTK_AUTH_OPAQUE (generally network ones),
1541 				 * we will only allow a SEARCH right on a directory to be cached...
1542 				 * that cached right always has a default TTL associated with it
1543 				 */
1544 				if (action != KAUTH_VNODE_SEARCH || vp->v_type != VDIR) {
1545 					vp = NULLVP;
1546 				}
1547 			}
1548 			if (vp != NULLVP && vnode_cache_is_stale(vp) == TRUE) {
1549 				vnode_uncache_authorized_action(vp, vp->v_authorized_actions);
1550 				vp = NULLVP;
1551 			}
1552 		} else {
1553 			vp = NULLVP;
1554 		}
1555 	}
1556 	if (vp != NULLVP) {
1557 		ucred = vfs_context_ucred(ctx);
1558 
1559 		NAME_CACHE_LOCK_SHARED();
1560 
1561 		if (vnode_cred(vp) == ucred && (vp->v_authorized_actions & action) == action) {
1562 			retval = TRUE;
1563 		}
1564 
1565 		NAME_CACHE_UNLOCK();
1566 	}
1567 	return retval;
1568 }
1569 
1570 
1571 void
vnode_cache_authorized_action(vnode_t vp,vfs_context_t ctx,kauth_action_t action)1572 vnode_cache_authorized_action(vnode_t vp, vfs_context_t ctx, kauth_action_t action)
1573 {
1574 	kauth_cred_t tcred = NOCRED;
1575 	kauth_cred_t ucred;
1576 	struct timeval tv;
1577 	boolean_t ttl_active = FALSE;
1578 
1579 	ucred = vfs_context_ucred(ctx);
1580 
1581 	if (!IS_VALID_CRED(ucred) || action == 0) {
1582 		return;
1583 	}
1584 
1585 	if ((vp->v_mount->mnt_kern_flag & (MNTK_AUTH_OPAQUE | MNTK_AUTH_CACHE_TTL))) {
1586 		/*
1587 		 * a TTL is enabled on the rights cache... handle it here
1588 		 * a TTL of 0 indicates that no rights should be cached
1589 		 */
1590 		if (vp->v_mount->mnt_authcache_ttl == 0) {
1591 			return;
1592 		}
1593 
1594 		if (!(vp->v_mount->mnt_kern_flag & MNTK_AUTH_CACHE_TTL)) {
1595 			/*
1596 			 * only cache SEARCH action for filesystems marked
1597 			 * MNTK_AUTH_OPAQUE on VDIRs...
1598 			 * the lookup_path code will time these out
1599 			 */
1600 			if ((action & ~KAUTH_VNODE_SEARCH) || vp->v_type != VDIR) {
1601 				return;
1602 			}
1603 		}
1604 		ttl_active = TRUE;
1605 
1606 		microuptime(&tv);
1607 	}
1608 	NAME_CACHE_LOCK();
1609 
1610 	tcred = vnode_cred(vp);
1611 	if (tcred == ucred) {
1612 		tcred = NOCRED;
1613 	} else {
1614 		/*
1615 		 * Use a temp variable to avoid kauth_cred_drop() while NAME_CACHE_LOCK is held
1616 		 */
1617 		kauth_cred_ref(ucred);
1618 		vp->v_cred = ucred;
1619 		vp->v_authorized_actions = 0;
1620 	}
1621 	if (ttl_active == TRUE && vp->v_authorized_actions == 0) {
1622 		/*
1623 		 * only reset the timestamnp on the
1624 		 * first authorization cached after the previous
1625 		 * timer has expired or we're switching creds...
1626 		 * 'vnode_cache_is_authorized' will clear the
1627 		 * authorized actions if the TTL is active and
1628 		 * it has expired
1629 		 */
1630 		vp->v_cred_timestamp = (int)tv.tv_sec;
1631 	}
1632 	vp->v_authorized_actions |= action;
1633 
1634 	NAME_CACHE_UNLOCK();
1635 
1636 	if (IS_VALID_CRED(tcred)) {
1637 		kauth_cred_unref(&tcred);
1638 	}
1639 }
1640 
1641 
1642 boolean_t
vnode_cache_is_stale(vnode_t vp)1643 vnode_cache_is_stale(vnode_t vp)
1644 {
1645 	struct timeval  tv;
1646 	boolean_t       retval;
1647 
1648 	microuptime(&tv);
1649 
1650 	if ((tv.tv_sec - vp->v_cred_timestamp) > vp->v_mount->mnt_authcache_ttl) {
1651 		retval = TRUE;
1652 	} else {
1653 		retval = FALSE;
1654 	}
1655 
1656 	return retval;
1657 }
1658 
1659 VFS_SMR_DECLARE;
1660 
1661 /*
1662  * Components of nameidata (or objects it can point to) which may
1663  * need restoring in case fast path lookup fails.
1664  */
1665 struct nameidata_state {
1666 	u_long  ni_loopcnt;
1667 	char *ni_next;
1668 	u_int ni_pathlen;
1669 	int32_t ni_flag;
1670 	char *cn_nameptr;
1671 	int cn_namelen;
1672 	int cn_flags;
1673 	uint32_t cn_hash;
1674 };
1675 
1676 static void
save_ndp_state(struct nameidata * ndp,struct componentname * cnp,struct nameidata_state * saved_statep)1677 save_ndp_state(struct nameidata *ndp, struct componentname *cnp, struct nameidata_state *saved_statep)
1678 {
1679 	saved_statep->ni_loopcnt = ndp->ni_loopcnt;
1680 	saved_statep->ni_next = ndp->ni_next;
1681 	saved_statep->ni_pathlen = ndp->ni_pathlen;
1682 	saved_statep->ni_flag = ndp->ni_flag;
1683 	saved_statep->cn_nameptr = cnp->cn_nameptr;
1684 	saved_statep->cn_namelen = cnp->cn_namelen;
1685 	saved_statep->cn_flags = cnp->cn_flags;
1686 	saved_statep->cn_hash = cnp->cn_hash;
1687 }
1688 
1689 static void
restore_ndp_state(struct nameidata * ndp,struct componentname * cnp,struct nameidata_state * saved_statep)1690 restore_ndp_state(struct nameidata *ndp, struct componentname *cnp, struct nameidata_state *saved_statep)
1691 {
1692 	ndp->ni_loopcnt = saved_statep->ni_loopcnt;
1693 	ndp->ni_next = saved_statep->ni_next;
1694 	ndp->ni_pathlen = saved_statep->ni_pathlen;
1695 	ndp->ni_flag = saved_statep->ni_flag;
1696 	cnp->cn_nameptr = saved_statep->cn_nameptr;
1697 	cnp->cn_namelen = saved_statep->cn_namelen;
1698 	cnp->cn_flags = saved_statep->cn_flags;
1699 	cnp->cn_hash = saved_statep->cn_hash;
1700 }
1701 
1702 static inline bool
vid_is_same(vnode_t vp,uint32_t vid)1703 vid_is_same(vnode_t vp, uint32_t vid)
1704 {
1705 	return !(os_atomic_load(&vp->v_lflag, relaxed) & (VL_DRAIN | VL_TERMINATE | VL_DEAD)) && (vnode_vid(vp) == vid);
1706 }
1707 
1708 static inline bool
can_check_v_mountedhere(vnode_t vp)1709 can_check_v_mountedhere(vnode_t vp)
1710 {
1711 	return (os_atomic_load(&vp->v_usecount, relaxed) > 0) &&
1712 	       (os_atomic_load(&vp->v_flag, relaxed) & VMOUNTEDHERE) &&
1713 	       !(os_atomic_load(&vp->v_lflag, relaxed) & (VL_TERMINATE | VL_DEAD) &&
1714 	       (vp->v_type == VDIR));
1715 }
1716 
1717 /*
1718  * Returns:	0			Success
1719  *		ERECYCLE		vnode was recycled from underneath us.  Force lookup to be re-driven from namei.
1720  *                                              This errno value should not be seen by anyone outside of the kernel.
1721  */
1722 int
cache_lookup_path(struct nameidata * ndp,struct componentname * cnp,vnode_t dp,vfs_context_t ctx,int * dp_authorized,vnode_t last_dp)1723 cache_lookup_path(struct nameidata *ndp, struct componentname *cnp, vnode_t dp,
1724     vfs_context_t ctx, int *dp_authorized, vnode_t last_dp)
1725 {
1726 	struct nameidata_state saved_state;
1727 	char            *cp;            /* pointer into pathname argument */
1728 	uint32_t        vid;
1729 	uint32_t        vvid = 0;       /* protected by vp != NULLVP */
1730 	vnode_t         vp = NULLVP;
1731 	vnode_t         tdp = NULLVP;
1732 	vnode_t         start_dp = dp;
1733 	kauth_cred_t    ucred;
1734 	boolean_t       ttl_enabled = FALSE;
1735 	struct timeval  tv;
1736 	mount_t         mp;
1737 	mount_t         dmp;
1738 	unsigned int    hash;
1739 	int             error = 0;
1740 	boolean_t       dotdotchecked = FALSE;
1741 	bool            locked = false;
1742 	bool            needs_lock = false;
1743 	bool            dp_iocount_taken = false;
1744 
1745 #if CONFIG_TRIGGERS
1746 	vnode_t         trigger_vp;
1747 #endif /* CONFIG_TRIGGERS */
1748 
1749 	ucred = vfs_context_ucred(ctx);
1750 retry:
1751 	if (nc_smr_enabled && !needs_lock) {
1752 		save_ndp_state(ndp, cnp, &saved_state);
1753 		vfs_smr_enter();
1754 	} else {
1755 		NAME_CACHE_LOCK_SHARED();
1756 		locked = true;
1757 	}
1758 	ndp->ni_flag &= ~(NAMEI_TRAILINGSLASH);
1759 
1760 	dmp = dp->v_mount;
1761 	vid = dp->v_id;
1762 	if (dmp && (dmp->mnt_kern_flag & (MNTK_AUTH_OPAQUE | MNTK_AUTH_CACHE_TTL))) {
1763 		ttl_enabled = TRUE;
1764 		microuptime(&tv);
1765 	}
1766 	for (;;) {
1767 		/*
1768 		 * Search a directory.
1769 		 *
1770 		 * The cn_hash value is for use by cache_lookup
1771 		 * The last component of the filename is left accessible via
1772 		 * cnp->cn_nameptr for callers that need the name.
1773 		 */
1774 		hash = 0;
1775 		cp = cnp->cn_nameptr;
1776 
1777 		while (*cp && (*cp != '/')) {
1778 			hash = crc32tab[((hash >> 24) ^ (unsigned char)*cp++)] ^ hash << 8;
1779 		}
1780 		/*
1781 		 * the crc generator can legitimately generate
1782 		 * a 0... however, 0 for us means that we
1783 		 * haven't computed a hash, so use 1 instead
1784 		 */
1785 		if (hash == 0) {
1786 			hash = 1;
1787 		}
1788 		cnp->cn_hash = hash;
1789 		cnp->cn_namelen = (int)(cp - cnp->cn_nameptr);
1790 
1791 		ndp->ni_pathlen -= cnp->cn_namelen;
1792 		ndp->ni_next = cp;
1793 
1794 		/*
1795 		 * Replace multiple slashes by a single slash and trailing slashes
1796 		 * by a null.  This must be done before VNOP_LOOKUP() because some
1797 		 * fs's don't know about trailing slashes.  Remember if there were
1798 		 * trailing slashes to handle symlinks, existing non-directories
1799 		 * and non-existing files that won't be directories specially later.
1800 		 */
1801 		while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
1802 			cp++;
1803 			ndp->ni_pathlen--;
1804 
1805 			if (*cp == '\0') {
1806 				ndp->ni_flag |= NAMEI_TRAILINGSLASH;
1807 				*ndp->ni_next = '\0';
1808 			}
1809 		}
1810 		ndp->ni_next = cp;
1811 
1812 		cnp->cn_flags &= ~(MAKEENTRY | ISLASTCN | ISDOTDOT);
1813 
1814 		if (*cp == '\0') {
1815 			cnp->cn_flags |= ISLASTCN;
1816 		}
1817 
1818 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.') {
1819 			cnp->cn_flags |= ISDOTDOT;
1820 		}
1821 
1822 #if NAMEDRSRCFORK
1823 		/*
1824 		 * Process a request for a file's resource fork.
1825 		 *
1826 		 * Consume the _PATH_RSRCFORKSPEC suffix and tag the path.
1827 		 */
1828 		if ((ndp->ni_pathlen == sizeof(_PATH_RSRCFORKSPEC)) &&
1829 		    (cp[1] == '.' && cp[2] == '.') &&
1830 		    bcmp(cp, _PATH_RSRCFORKSPEC, sizeof(_PATH_RSRCFORKSPEC)) == 0) {
1831 			/* Skip volfs file systems that don't support native streams. */
1832 			if ((dmp != NULL) &&
1833 			    (dmp->mnt_flag & MNT_DOVOLFS) &&
1834 			    (dmp->mnt_kern_flag & MNTK_NAMED_STREAMS) == 0) {
1835 				goto skiprsrcfork;
1836 			}
1837 			cnp->cn_flags |= CN_WANTSRSRCFORK;
1838 			cnp->cn_flags |= ISLASTCN;
1839 			ndp->ni_next[0] = '\0';
1840 			ndp->ni_pathlen = 1;
1841 		}
1842 skiprsrcfork:
1843 #endif
1844 
1845 		*dp_authorized = 0;
1846 
1847 #if CONFIG_FIRMLINKS
1848 		if ((cnp->cn_flags & ISDOTDOT) && (dp->v_flag & VFMLINKTARGET) && dp->v_fmlink) {
1849 			/*
1850 			 * If this is a firmlink target then dp has to be switched to the
1851 			 * firmlink "source" before exiting this loop.
1852 			 *
1853 			 * For a firmlink "target", the policy is to pick the parent of the
1854 			 * firmlink "source" as the parent. This means that you can never
1855 			 * get to the "real" parent of firmlink target via a dotdot lookup.
1856 			 */
1857 			vnode_t v_fmlink = dp->v_fmlink;
1858 			uint32_t old_vid = vid;
1859 			mp = dmp;
1860 			if (v_fmlink) {
1861 				vid = v_fmlink->v_id;
1862 				dmp = v_fmlink->v_mount;
1863 				if ((dp->v_fmlink == v_fmlink) && dmp) {
1864 					dp = v_fmlink;
1865 				} else {
1866 					vid = old_vid;
1867 					dmp = mp;
1868 				}
1869 			}
1870 		}
1871 #endif
1872 
1873 
1874 		if (ttl_enabled &&
1875 		    (dmp->mnt_authcache_ttl == 0 ||
1876 		    ((tv.tv_sec - dp->v_cred_timestamp) > dmp->mnt_authcache_ttl))) {
1877 			break;
1878 		}
1879 
1880 		/*
1881 		 * NAME_CACHE_LOCK holds these fields stable
1882 		 *
1883 		 * We can't cache KAUTH_VNODE_SEARCHBYANYONE for root correctly
1884 		 * so we make an ugly check for root here. root is always
1885 		 * allowed and breaking out of here only to find out that is
1886 		 * authorized by virtue of being root is very very expensive.
1887 		 * However, the check for not root is valid only for filesystems
1888 		 * which use local authorization.
1889 		 *
1890 		 * XXX: Remove the check for root when we can reliably set
1891 		 * KAUTH_VNODE_SEARCHBYANYONE as root.
1892 		 */
1893 		int v_authorized_actions = os_atomic_load(&dp->v_authorized_actions, relaxed);
1894 		if ((vnode_cred(dp) != ucred || !(v_authorized_actions & KAUTH_VNODE_SEARCH)) &&
1895 		    !(v_authorized_actions & KAUTH_VNODE_SEARCHBYANYONE) &&
1896 		    (ttl_enabled || !vfs_context_issuser(ctx))) {
1897 			break;
1898 		}
1899 
1900 		/*
1901 		 * indicate that we're allowed to traverse this directory...
1902 		 * even if we fail the cache lookup or decide to bail for
1903 		 * some other reason, this information is valid and is used
1904 		 * to avoid doing a vnode_authorize before the call to VNOP_LOOKUP
1905 		 */
1906 		*dp_authorized = 1;
1907 
1908 		if ((cnp->cn_flags & (ISLASTCN | ISDOTDOT))) {
1909 			if (cnp->cn_nameiop != LOOKUP) {
1910 				break;
1911 			}
1912 			if (cnp->cn_flags & LOCKPARENT) {
1913 				break;
1914 			}
1915 			if (cnp->cn_flags & NOCACHE) {
1916 				break;
1917 			}
1918 
1919 			if (cnp->cn_flags & ISDOTDOT) {
1920 				/*
1921 				 * Force directory hardlinks to go to
1922 				 * file system for ".." requests.
1923 				 */
1924 				if ((dp->v_flag & VISHARDLINK)) {
1925 					break;
1926 				}
1927 				/*
1928 				 * Quit here only if we can't use
1929 				 * the parent directory pointer or
1930 				 * don't have one.  Otherwise, we'll
1931 				 * use it below.
1932 				 */
1933 				if ((dp->v_flag & VROOT) ||
1934 				    dp == ndp->ni_rootdir ||
1935 				    dp->v_parent == NULLVP) {
1936 					break;
1937 				}
1938 			}
1939 		}
1940 
1941 		if ((cnp->cn_flags & CN_SKIPNAMECACHE)) {
1942 			/*
1943 			 * Force lookup to go to the filesystem with
1944 			 * all cnp fields set up.
1945 			 */
1946 			break;
1947 		}
1948 
1949 		/*
1950 		 * "." and ".." aren't supposed to be cached, so check
1951 		 * for them before checking the cache.
1952 		 */
1953 		if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
1954 			vp = dp;
1955 			vvid = vid;
1956 		} else if ((cnp->cn_flags & ISDOTDOT)) {
1957 			/*
1958 			 * If this is a chrooted process, we need to check if
1959 			 * the process is trying to break out of its chrooted
1960 			 * jail. We do that by trying to determine if dp is
1961 			 * a subdirectory of ndp->ni_rootdir. If we aren't
1962 			 * able to determine that by the v_parent pointers, we
1963 			 * will leave the fast path.
1964 			 *
1965 			 * Since this function may see dotdot components
1966 			 * many times and it has the name cache lock held for
1967 			 * the entire duration, we optimise this by doing this
1968 			 * check only once per cache_lookup_path call.
1969 			 * If dotdotchecked is set, it means we've done this
1970 			 * check once already and don't need to do it again.
1971 			 */
1972 			if (!locked && (ndp->ni_rootdir != rootvnode)) {
1973 				vfs_smr_leave();
1974 				needs_lock = true;
1975 				goto prep_lock_retry;
1976 			} else if (locked && !dotdotchecked && (ndp->ni_rootdir != rootvnode)) {
1977 				vnode_t tvp = dp;
1978 				boolean_t defer = FALSE;
1979 				boolean_t is_subdir = FALSE;
1980 
1981 				defer = cache_check_vnode_issubdir(tvp,
1982 				    ndp->ni_rootdir, &is_subdir, &tvp);
1983 
1984 				if (defer) {
1985 					/* defer to Filesystem */
1986 					break;
1987 				} else if (!is_subdir) {
1988 					/*
1989 					 * This process is trying to break  out
1990 					 * of its chrooted jail, so all its
1991 					 * dotdot accesses will be translated to
1992 					 * its root directory.
1993 					 */
1994 					vp = ndp->ni_rootdir;
1995 				} else {
1996 					/*
1997 					 * All good, let this dotdot access
1998 					 * proceed normally
1999 					 */
2000 					vp = dp->v_parent;
2001 				}
2002 				dotdotchecked = TRUE;
2003 			} else {
2004 				vp = dp->v_parent;
2005 			}
2006 			if (!vp) {
2007 				break;
2008 			}
2009 			vvid = vp->v_id;
2010 		} else {
2011 			if (!locked) {
2012 				vp = cache_lookup_smr(dp, cnp, &vvid);
2013 				if (!vid_is_same(dp, vid)) {
2014 					vp = NULLVP;
2015 					needs_lock = true;
2016 					vfs_smr_leave();
2017 					goto prep_lock_retry;
2018 				}
2019 			} else {
2020 				vp = cache_lookup_locked(dp, cnp, &vvid);
2021 			}
2022 
2023 
2024 			if (!vp) {
2025 				break;
2026 			}
2027 
2028 			if ((vp->v_flag & VISHARDLINK)) {
2029 				/*
2030 				 * The file system wants a VNOP_LOOKUP on this vnode
2031 				 */
2032 				vp = NULL;
2033 				break;
2034 			}
2035 
2036 #if CONFIG_FIRMLINKS
2037 			vnode_t v_fmlink = vp->v_fmlink;
2038 			if (v_fmlink && !(vp->v_flag & VFMLINKTARGET)) {
2039 				if (cnp->cn_flags & CN_FIRMLINK_NOFOLLOW ||
2040 				    ((vp->v_type != VDIR) && (vp->v_type != VLNK))) {
2041 					/* Leave it to the filesystem */
2042 					vp = NULLVP;
2043 					break;
2044 				}
2045 
2046 				/*
2047 				 * Always switch to the target unless it is a VLNK
2048 				 * and it is the last component and we have NOFOLLOW
2049 				 * semantics
2050 				 */
2051 				if (vp->v_type == VDIR) {
2052 					vp = v_fmlink;
2053 					vvid = vnode_vid(vp);
2054 				} else if ((cnp->cn_flags & FOLLOW) ||
2055 				    (ndp->ni_flag & NAMEI_TRAILINGSLASH) || *ndp->ni_next == '/') {
2056 					if (ndp->ni_loopcnt >= MAXSYMLINKS - 1) {
2057 						vp = NULLVP;
2058 						break;
2059 					}
2060 					ndp->ni_loopcnt++;
2061 					vp = v_fmlink;
2062 					vvid = vnode_vid(vp);
2063 				}
2064 			}
2065 #endif
2066 		}
2067 		if ((cnp->cn_flags & ISLASTCN)) {
2068 			break;
2069 		}
2070 
2071 		if (vp->v_type != VDIR) {
2072 			if (vp->v_type != VLNK) {
2073 				vp = NULL;
2074 			}
2075 			break;
2076 		}
2077 
2078 		/*
2079 		 * v_mountedhere is PAC protected which means vp has to be a VDIR
2080 		 * to access that pointer as v_mountedhere. However, if we don't
2081 		 * have the name cache lock or an iocount (which we won't in the
2082 		 * !locked case) we can't guarantee that. So we try to detect it
2083 		 * via other fields to avoid having to dereference v_mountedhere
2084 		 * when we don't need to. Note that in theory if entire reclaim
2085 		 * happens between the time we check can_check_v_mountedhere()
2086 		 * and the subsequent access this will still fail but the fields
2087 		 * we check make that exceedingly unlikely and will result in
2088 		 * the chances of that happening being practically zero (but not
2089 		 * zero).
2090 		 */
2091 		if ((locked || can_check_v_mountedhere(vp)) &&
2092 		    (mp = vp->v_mountedhere) && ((cnp->cn_flags & NOCROSSMOUNT) == 0)) {
2093 			vnode_t tmp_vp;
2094 			int tmp_vid;
2095 
2096 			if (!(locked || vid_is_same(vp, vvid))) {
2097 				vp = NULL;
2098 				break;
2099 			}
2100 			tmp_vp = mp->mnt_realrootvp;
2101 			tmp_vid = mp->mnt_realrootvp_vid;
2102 			if (tmp_vp == NULLVP || mp->mnt_generation != mount_generation ||
2103 			    tmp_vid != tmp_vp->v_id) {
2104 				break;
2105 			}
2106 
2107 			if ((mp = tmp_vp->v_mount) == NULL) {
2108 				break;
2109 			}
2110 
2111 			vp = tmp_vp;
2112 			vvid = tmp_vid;
2113 			dmp = mp;
2114 			if (dmp->mnt_kern_flag & (MNTK_AUTH_OPAQUE | MNTK_AUTH_CACHE_TTL)) {
2115 				ttl_enabled = TRUE;
2116 				microuptime(&tv);
2117 			} else {
2118 				ttl_enabled = FALSE;
2119 			}
2120 		}
2121 
2122 #if CONFIG_TRIGGERS
2123 		/*
2124 		 * After traversing all mountpoints stacked here, if we have a
2125 		 * trigger in hand, resolve it.  Note that we don't need to
2126 		 * leave the fast path if the mount has already happened.
2127 		 */
2128 		if (vp->v_resolve) {
2129 			break;
2130 		}
2131 #endif /* CONFIG_TRIGGERS */
2132 
2133 		if (!(locked || vid_is_same(vp, vvid))) {
2134 			vp = NULL;
2135 			break;
2136 		}
2137 
2138 		dp = vp;
2139 		vid = vvid;
2140 		vp = NULLVP;
2141 		vvid = 0;
2142 
2143 		cnp->cn_nameptr = ndp->ni_next + 1;
2144 		ndp->ni_pathlen--;
2145 		while (*cnp->cn_nameptr == '/') {
2146 			cnp->cn_nameptr++;
2147 			ndp->ni_pathlen--;
2148 		}
2149 	}
2150 	if (!locked) {
2151 		if (vp && !vnode_hold_smr(vp)) {
2152 			vp = NULLVP;
2153 			vvid = 0;
2154 		}
2155 		if (!vnode_hold_smr(dp)) {
2156 			vfs_smr_leave();
2157 			if (vp) {
2158 				vnode_drop(vp);
2159 				vp = NULLVP;
2160 				vvid = 0;
2161 			}
2162 			goto prep_lock_retry;
2163 		}
2164 		vfs_smr_leave();
2165 	} else {
2166 		if (vp != NULLVP) {
2167 			vvid = vp->v_id;
2168 			vnode_hold(vp);
2169 		}
2170 		vid = dp->v_id;
2171 
2172 		vnode_hold(dp);
2173 		NAME_CACHE_UNLOCK();
2174 	}
2175 
2176 	tdp = NULLVP;
2177 	if (!(cnp->cn_flags & DONOTAUTH) &&
2178 	    (vp != NULLVP) && (vp->v_type != VLNK) &&
2179 	    ((cnp->cn_flags & (ISLASTCN | LOCKPARENT | WANTPARENT | SAVESTART)) == ISLASTCN)) {
2180 		/*
2181 		 * if we've got a child and it's the last component, and
2182 		 * the lookup doesn't need to return the parent then we
2183 		 * can skip grabbing an iocount on the parent, since all
2184 		 * we're going to do with it is a vnode_put just before
2185 		 * we return from 'lookup'.  If it's a symbolic link,
2186 		 * we need the parent in case the link happens to be
2187 		 * a relative pathname.
2188 		 *
2189 		 * However, we can't make this optimisation if we have to call
2190 		 * a MAC hook.
2191 		 */
2192 		tdp = dp;
2193 		dp = NULLVP;
2194 	} else {
2195 need_dp:
2196 		/*
2197 		 * return the last directory we looked at
2198 		 * with an io reference held. If it was the one passed
2199 		 * in as a result of the last iteration of VNOP_LOOKUP,
2200 		 * it should already hold an io ref. No need to increase ref.
2201 		 */
2202 		if (last_dp != dp) {
2203 			if (dp == ndp->ni_usedvp) {
2204 				/*
2205 				 * if this vnode matches the one passed in via USEDVP
2206 				 * than this context already holds an io_count... just
2207 				 * use vnode_get to get an extra ref for lookup to play
2208 				 * with... can't use the getwithvid variant here because
2209 				 * it will block behind a vnode_drain which would result
2210 				 * in a deadlock (since we already own an io_count that the
2211 				 * vnode_drain is waiting on)... vnode_get grabs the io_count
2212 				 * immediately w/o waiting... it always succeeds
2213 				 */
2214 				vnode_get(dp);
2215 			} else if ((error = vnode_getwithvid_drainok(dp, vid))) {
2216 				/*
2217 				 * failure indicates the vnode
2218 				 * changed identity or is being
2219 				 * TERMINATED... in either case
2220 				 * punt this lookup.
2221 				 *
2222 				 * don't necessarily return ENOENT, though, because
2223 				 * we really want to go back to disk and make sure it's
2224 				 * there or not if someone else is changing this
2225 				 * vnode. That being said, the one case where we do want
2226 				 * to return ENOENT is when the vnode's mount point is
2227 				 * in the process of unmounting and we might cause a deadlock
2228 				 * in our attempt to take an iocount. An ENODEV error return
2229 				 * is from vnode_get* is an indication this but we change that
2230 				 * ENOENT for upper layers.
2231 				 */
2232 				if (error == ENODEV) {
2233 					error = ENOENT;
2234 				} else {
2235 					error = ERECYCLE;
2236 				}
2237 				vnode_drop(dp);
2238 				if (vp) {
2239 					vnode_drop(vp);
2240 				}
2241 				goto errorout;
2242 			}
2243 			dp_iocount_taken = true;
2244 		}
2245 		vnode_drop(dp);
2246 	}
2247 
2248 #if CONFIG_MACF
2249 	/*
2250 	 * Name cache provides authorization caching (see below)
2251 	 * that will short circuit MAC checks in lookup().
2252 	 * We must perform MAC check here.  On denial
2253 	 * dp_authorized will remain 0 and second check will
2254 	 * be perfomed in lookup().
2255 	 */
2256 	if (!(cnp->cn_flags & DONOTAUTH)) {
2257 		error = mac_vnode_check_lookup(ctx, dp, cnp);
2258 		if (error) {
2259 			*dp_authorized = 0;
2260 			if (dp_iocount_taken) {
2261 				vnode_put(dp);
2262 			}
2263 			if (vp) {
2264 				vnode_drop(vp);
2265 				vp = NULLVP;
2266 			}
2267 			goto errorout;
2268 		}
2269 	}
2270 #endif /* MAC */
2271 
2272 	if (vp != NULLVP) {
2273 		if ((vnode_getwithvid_drainok(vp, vvid))) {
2274 			vnode_drop(vp);
2275 			vp = NULLVP;
2276 
2277 			/*
2278 			 * can't get reference on the vp we'd like
2279 			 * to return... if we didn't grab a reference
2280 			 * on the directory (due to fast path bypass),
2281 			 * then we need to do it now... we can't return
2282 			 * with both ni_dvp and ni_vp NULL, and no
2283 			 * error condition
2284 			 */
2285 			if (dp == NULLVP) {
2286 				dp = tdp;
2287 				tdp = NULLVP;
2288 				goto need_dp;
2289 			}
2290 		} else {
2291 			vnode_drop(vp);
2292 		}
2293 		if (dp_iocount_taken && vp && (vp->v_type != VLNK) &&
2294 		    ((cnp->cn_flags & (ISLASTCN | LOCKPARENT | WANTPARENT | SAVESTART)) == ISLASTCN)) {
2295 			vnode_put(dp);
2296 			dp = NULLVP;
2297 		}
2298 	}
2299 
2300 	if (tdp) {
2301 		vnode_drop(tdp);
2302 		tdp = NULLVP;
2303 	}
2304 
2305 	ndp->ni_dvp = dp;
2306 	ndp->ni_vp  = vp;
2307 
2308 #if CONFIG_TRIGGERS
2309 	trigger_vp = vp ? vp : dp;
2310 	if ((error == 0) && (trigger_vp != NULLVP) && vnode_isdir(trigger_vp)) {
2311 		error = vnode_trigger_resolve(trigger_vp, ndp, ctx);
2312 		if (error) {
2313 			if (vp) {
2314 				vnode_put(vp);
2315 			}
2316 			if (dp) {
2317 				vnode_put(dp);
2318 			}
2319 			goto errorout;
2320 		}
2321 	}
2322 #endif /* CONFIG_TRIGGERS */
2323 
2324 errorout:
2325 	/*
2326 	 * If we came into cache_lookup_path after an iteration of the lookup loop that
2327 	 * resulted in a call to VNOP_LOOKUP, then VNOP_LOOKUP returned a vnode with a io ref
2328 	 * on it.  It is now the job of cache_lookup_path to drop the ref on this vnode
2329 	 * when it is no longer needed.  If we get to this point, and last_dp is not NULL
2330 	 * and it is ALSO not the dvp we want to return to caller of this function, it MUST be
2331 	 * the case that we got to a subsequent path component and this previous vnode is
2332 	 * no longer needed.  We can then drop the io ref on it.
2333 	 */
2334 	if ((last_dp != NULLVP) && (last_dp != ndp->ni_dvp)) {
2335 		vnode_put(last_dp);
2336 	}
2337 
2338 	//initialized to 0, should be the same if no error cases occurred.
2339 	return error;
2340 
2341 prep_lock_retry:
2342 	restore_ndp_state(ndp, cnp, &saved_state);
2343 	dp = start_dp;
2344 	goto retry;
2345 }
2346 
2347 
2348 static vnode_t
cache_lookup_locked(vnode_t dvp,struct componentname * cnp,uint32_t * vidp)2349 cache_lookup_locked(vnode_t dvp, struct componentname *cnp, uint32_t *vidp)
2350 {
2351 	struct namecache *ncp;
2352 	long namelen = cnp->cn_namelen;
2353 	unsigned int hashval = cnp->cn_hash;
2354 
2355 	if (nc_disabled) {
2356 		return NULL;
2357 	}
2358 
2359 	smrq_serialized_foreach(ncp, NCHHASH(dvp, cnp->cn_hash), nc_hash) {
2360 		if ((ncp->nc_dvp == dvp) && (ncp->nc_hashval == hashval)) {
2361 			if (strncmp(ncp->nc_name, cnp->cn_nameptr, namelen) == 0 && ncp->nc_name[namelen] == 0) {
2362 				break;
2363 			}
2364 		}
2365 	}
2366 	if (ncp == 0) {
2367 		/*
2368 		 * We failed to find an entry
2369 		 */
2370 		NCHSTAT(ncs_miss);
2371 		NC_SMR_STATS(clp_next_fail);
2372 		return NULL;
2373 	}
2374 	NCHSTAT(ncs_goodhits);
2375 
2376 	if (!ncp->nc_vp) {
2377 		return NULL;
2378 	}
2379 
2380 	*vidp = ncp->nc_vid;
2381 	NC_SMR_STATS(clp_next);
2382 
2383 	return ncp->nc_vp;
2384 }
2385 
2386 static vnode_t
cache_lookup_smr(vnode_t dvp,struct componentname * cnp,uint32_t * vidp)2387 cache_lookup_smr(vnode_t dvp, struct componentname *cnp, uint32_t *vidp)
2388 {
2389 	struct namecache *ncp;
2390 	long namelen = cnp->cn_namelen;
2391 	unsigned int hashval = cnp->cn_hash;
2392 	vnode_t vp = NULLVP;
2393 	uint32_t vid = 0;
2394 	uint32_t counter = 1;
2395 
2396 	if (nc_disabled) {
2397 		return NULL;
2398 	}
2399 
2400 	smrq_entered_foreach(ncp, NCHHASH(dvp, cnp->cn_hash), nc_hash) {
2401 		counter = os_atomic_load(&ncp->nc_counter, acquire);
2402 		if (!(counter & NC_VALID)) {
2403 			ncp = NULL;
2404 			goto out;
2405 		}
2406 		if ((ncp->nc_dvp == dvp) && (ncp->nc_hashval == hashval)) {
2407 			const char *nc_name =
2408 			    os_atomic_load(&ncp->nc_name, relaxed);
2409 			if (nc_name &&
2410 			    strncmp(nc_name, cnp->cn_nameptr, namelen) == 0 &&
2411 			    nc_name[namelen] == 0) {
2412 				break;
2413 			} else if (!nc_name) {
2414 				ncp = NULL;
2415 				goto out;
2416 			}
2417 		}
2418 	}
2419 
2420 	/* We failed to find an entry */
2421 	if (ncp == 0) {
2422 		goto out;
2423 	}
2424 
2425 	vp = ncp->nc_vp;
2426 	vid = ncp->nc_vid;
2427 
2428 	/*
2429 	 * The validity of vp and vid depends on the value of the counter being
2430 	 * the same when we read it first in the loop and now. Anything else
2431 	 * and we can't use this vp & vid.
2432 	 * Hopefully this ncp wasn't reused 2 billion times between the time
2433 	 * we read it first and when we the counter value again.
2434 	 */
2435 	if (os_atomic_load(&ncp->nc_counter, acquire) != counter) {
2436 		vp = NULLVP;
2437 		goto out;
2438 	}
2439 
2440 	*vidp = vid;
2441 	NC_SMR_STATS(clp_smr_next);
2442 
2443 	return vp;
2444 
2445 out:
2446 	NC_SMR_STATS(clp_smr_next_fail);
2447 	return NULL;
2448 }
2449 
2450 
2451 unsigned int hash_string(const char *cp, int len);
2452 //
2453 // Have to take a len argument because we may only need to
2454 // hash part of a componentname.
2455 //
2456 unsigned int
hash_string(const char * cp,int len)2457 hash_string(const char *cp, int len)
2458 {
2459 	unsigned hash = 0;
2460 
2461 	if (len) {
2462 		while (len--) {
2463 			hash = crc32tab[((hash >> 24) ^ (unsigned char)*cp++)] ^ hash << 8;
2464 		}
2465 	} else {
2466 		while (*cp != '\0') {
2467 			hash = crc32tab[((hash >> 24) ^ (unsigned char)*cp++)] ^ hash << 8;
2468 		}
2469 	}
2470 	/*
2471 	 * the crc generator can legitimately generate
2472 	 * a 0... however, 0 for us means that we
2473 	 * haven't computed a hash, so use 1 instead
2474 	 */
2475 	if (hash == 0) {
2476 		hash = 1;
2477 	}
2478 	return hash;
2479 }
2480 
2481 
2482 /*
2483  * Lookup an entry in the cache
2484  *
2485  * We don't do this if the segment name is long, simply so the cache
2486  * can avoid holding long names (which would either waste space, or
2487  * add greatly to the complexity).
2488  *
2489  * Lookup is called with dvp pointing to the directory to search,
2490  * cnp pointing to the name of the entry being sought. If the lookup
2491  * succeeds, the vnode is returned in *vpp, and a status of -1 is
2492  * returned. If the lookup determines that the name does not exist
2493  * (negative cacheing), a status of ENOENT is returned. If the lookup
2494  * fails, a status of zero is returned.
2495  */
2496 
2497 static int
cache_lookup_fallback(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp)2498 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
2499 {
2500 	struct namecache *ncp;
2501 	long namelen = cnp->cn_namelen;
2502 	unsigned int hashval = cnp->cn_hash;
2503 	boolean_t       have_exclusive = FALSE;
2504 	uint32_t vid;
2505 	vnode_t  vp;
2506 
2507 	NAME_CACHE_LOCK_SHARED();
2508 
2509 relook:
2510 	smrq_serialized_foreach(ncp, NCHHASH(dvp, cnp->cn_hash), nc_hash) {
2511 		if ((ncp->nc_dvp == dvp) && (ncp->nc_hashval == hashval)) {
2512 			if (strncmp(ncp->nc_name, cnp->cn_nameptr, namelen) == 0 && ncp->nc_name[namelen] == 0) {
2513 				break;
2514 			}
2515 		}
2516 	}
2517 	/* We failed to find an entry */
2518 	if (ncp == 0) {
2519 		NCHSTAT(ncs_miss);
2520 		NAME_CACHE_UNLOCK();
2521 		return 0;
2522 	}
2523 
2524 	/* We don't want to have an entry, so dump it */
2525 	if ((cnp->cn_flags & MAKEENTRY) == 0) {
2526 		if (have_exclusive == TRUE) {
2527 			NCHSTAT(ncs_badhits);
2528 			cache_delete(ncp, 1);
2529 			NAME_CACHE_UNLOCK();
2530 			return 0;
2531 		}
2532 		if (!NAME_CACHE_LOCK_SHARED_TO_EXCLUSIVE()) {
2533 			NAME_CACHE_LOCK();
2534 		}
2535 		have_exclusive = TRUE;
2536 		goto relook;
2537 	}
2538 	vp = ncp->nc_vp;
2539 
2540 	/* We found a "positive" match, return the vnode */
2541 	if (vp) {
2542 		NCHSTAT(ncs_goodhits);
2543 
2544 		vid = ncp->nc_vid;
2545 		vnode_hold(vp);
2546 		NAME_CACHE_UNLOCK();
2547 
2548 		if (vnode_getwithvid(vp, vid)) {
2549 			vnode_drop(vp);
2550 #if COLLECT_STATS
2551 			NAME_CACHE_LOCK();
2552 			NCHSTAT(ncs_badvid);
2553 			NAME_CACHE_UNLOCK();
2554 #endif
2555 			return 0;
2556 		}
2557 		vnode_drop(vp);
2558 		*vpp = vp;
2559 		NC_SMR_STATS(cl_lock_hits);
2560 		return -1;
2561 	}
2562 
2563 	/* We found a negative match, and want to create it, so purge */
2564 	if (cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME) {
2565 		if (have_exclusive == TRUE) {
2566 			NCHSTAT(ncs_badhits);
2567 			cache_delete(ncp, 1);
2568 			NAME_CACHE_UNLOCK();
2569 			return 0;
2570 		}
2571 		if (!NAME_CACHE_LOCK_SHARED_TO_EXCLUSIVE()) {
2572 			NAME_CACHE_LOCK();
2573 		}
2574 		have_exclusive = TRUE;
2575 		goto relook;
2576 	}
2577 
2578 	/*
2579 	 * We found a "negative" match, ENOENT notifies client of this match.
2580 	 */
2581 	NCHSTAT(ncs_neghits);
2582 
2583 	NAME_CACHE_UNLOCK();
2584 	return ENOENT;
2585 }
2586 
2587 
2588 
2589 /*
2590  * Lookup an entry in the cache
2591  *
2592  * Lookup is called with dvp pointing to the directory to search,
2593  * cnp pointing to the name of the entry being sought. If the lookup
2594  * succeeds, the vnode is returned in *vpp, and a status of -1 is
2595  * returned. If the lookup determines that the name does not exist
2596  * (negative cacheing), a status of ENOENT is returned. If the lookup
2597  * fails, a status of zero is returned.
2598  */
2599 int
cache_lookup(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp)2600 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
2601 {
2602 	struct namecache *ncp;
2603 	long namelen = cnp->cn_namelen;
2604 	vnode_t  vp;
2605 	uint32_t vid = 0;
2606 	uint32_t counter = 1;
2607 	unsigned int hashval;
2608 
2609 	*vpp = NULLVP;
2610 
2611 	if (cnp->cn_hash == 0) {
2612 		cnp->cn_hash = hash_string(cnp->cn_nameptr, cnp->cn_namelen);
2613 	}
2614 	hashval = cnp->cn_hash;
2615 
2616 	if (nc_disabled) {
2617 		return 0;
2618 	}
2619 
2620 	if (!nc_smr_enabled) {
2621 		goto out_fallback;
2622 	}
2623 
2624 	/* We don't want to have an entry, so dump it */
2625 	if ((cnp->cn_flags & MAKEENTRY) == 0) {
2626 		goto out_fallback;
2627 	}
2628 
2629 	vfs_smr_enter();
2630 
2631 	smrq_entered_foreach(ncp, NCHHASH(dvp, cnp->cn_hash), nc_hash) {
2632 		counter = os_atomic_load(&ncp->nc_counter, acquire);
2633 		if (!(counter & NC_VALID)) {
2634 			vfs_smr_leave();
2635 			goto out_fallback;
2636 		}
2637 		if ((ncp->nc_dvp == dvp) && (ncp->nc_hashval == hashval)) {
2638 			const char *nc_name =
2639 			    os_atomic_load(&ncp->nc_name, relaxed);
2640 			if (nc_name &&
2641 			    strncmp(nc_name, cnp->cn_nameptr, namelen) == 0 &&
2642 			    nc_name[namelen] == 0) {
2643 				break;
2644 			} else if (!nc_name) {
2645 				vfs_smr_leave();
2646 				goto out_fallback;
2647 			}
2648 		}
2649 	}
2650 
2651 	/* We failed to find an entry */
2652 	if (ncp == 0) {
2653 		NCHSTAT(ncs_miss);
2654 		vfs_smr_leave();
2655 		NC_SMR_STATS(cl_smr_miss);
2656 		return 0;
2657 	}
2658 
2659 	vp = ncp->nc_vp;
2660 	vid = ncp->nc_vid;
2661 
2662 	/*
2663 	 * The validity of vp and vid depends on the value of the counter being
2664 	 * the same when we read it first in the loop and now. Anything else
2665 	 * and we can't use this vp & vid.
2666 	 * Hopefully this ncp wasn't reused 2 billion times between the time
2667 	 * we read it first and when we the counter value again.
2668 	 */
2669 	if (os_atomic_load(&ncp->nc_counter, acquire) != counter) {
2670 		vfs_smr_leave();
2671 		goto out_fallback;
2672 	}
2673 
2674 	if (vp) {
2675 		bool holdcount_acquired = vnode_hold_smr(vp);
2676 
2677 		vfs_smr_leave();
2678 
2679 		if (!holdcount_acquired) {
2680 			goto out_fallback;
2681 		}
2682 
2683 		if (vnode_getwithvid(vp, vid) != 0) {
2684 			vnode_drop(vp);
2685 			goto out_fallback;
2686 		}
2687 		vnode_drop(vp);
2688 		NCHSTAT(ncs_goodhits);
2689 
2690 		*vpp = vp;
2691 		NC_SMR_STATS(cl_smr_hits);
2692 		return -1;
2693 	}
2694 
2695 	vfs_smr_leave();
2696 
2697 	/* We found a negative match, and want to create it, so purge */
2698 	if (cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME) {
2699 		goto out_fallback;
2700 	}
2701 
2702 	/*
2703 	 * We found a "negative" match, ENOENT notifies client of this match.
2704 	 */
2705 	NCHSTAT(ncs_neghits);
2706 	NC_SMR_STATS(cl_smr_negative_hits);
2707 	return ENOENT;
2708 
2709 out_fallback:
2710 	NC_SMR_STATS(cl_smr_fallback);
2711 	return cache_lookup_fallback(dvp, vpp, cnp);
2712 }
2713 
2714 const char *
cache_enter_create(vnode_t dvp,vnode_t vp,struct componentname * cnp)2715 cache_enter_create(vnode_t dvp, vnode_t vp, struct componentname *cnp)
2716 {
2717 	const char *strname;
2718 
2719 	if (cnp->cn_hash == 0) {
2720 		cnp->cn_hash = hash_string(cnp->cn_nameptr, cnp->cn_namelen);
2721 	}
2722 
2723 	/*
2724 	 * grab 2 references on the string entered
2725 	 * one for the cache_enter_locked to consume
2726 	 * and the second to be consumed by v_name (vnode_create call point)
2727 	 */
2728 	strname = add_name_internal(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, TRUE, 0);
2729 
2730 	NAME_CACHE_LOCK();
2731 
2732 	cache_enter_locked(dvp, vp, cnp, strname);
2733 
2734 	NAME_CACHE_UNLOCK();
2735 
2736 	return strname;
2737 }
2738 
2739 
2740 /*
2741  * Add an entry to the cache...
2742  * but first check to see if the directory
2743  * that this entry is to be associated with has
2744  * had any cache_purges applied since we took
2745  * our identity snapshot... this check needs to
2746  * be done behind the name cache lock
2747  */
2748 void
cache_enter_with_gen(struct vnode * dvp,struct vnode * vp,struct componentname * cnp,int gen)2749 cache_enter_with_gen(struct vnode *dvp, struct vnode *vp, struct componentname *cnp, int gen)
2750 {
2751 	if (cnp->cn_hash == 0) {
2752 		cnp->cn_hash = hash_string(cnp->cn_nameptr, cnp->cn_namelen);
2753 	}
2754 
2755 	NAME_CACHE_LOCK();
2756 
2757 	if (dvp->v_nc_generation == gen) {
2758 		(void)cache_enter_locked(dvp, vp, cnp, NULL);
2759 	}
2760 
2761 	NAME_CACHE_UNLOCK();
2762 }
2763 
2764 
2765 /*
2766  * Add an entry to the cache.
2767  */
2768 void
cache_enter(struct vnode * dvp,struct vnode * vp,struct componentname * cnp)2769 cache_enter(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2770 {
2771 	const char *strname;
2772 
2773 	if (cnp->cn_hash == 0) {
2774 		cnp->cn_hash = hash_string(cnp->cn_nameptr, cnp->cn_namelen);
2775 	}
2776 
2777 	/*
2778 	 * grab 1 reference on the string entered
2779 	 * for the cache_enter_locked to consume
2780 	 */
2781 	strname = add_name_internal(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, FALSE, 0);
2782 
2783 	NAME_CACHE_LOCK();
2784 
2785 	cache_enter_locked(dvp, vp, cnp, strname);
2786 
2787 	NAME_CACHE_UNLOCK();
2788 }
2789 
2790 
2791 static void
cache_enter_locked(struct vnode * dvp,struct vnode * vp,struct componentname * cnp,const char * strname)2792 cache_enter_locked(struct vnode *dvp, struct vnode *vp, struct componentname *cnp, const char *strname)
2793 {
2794 	struct namecache *ncp, *negp;
2795 	struct smrq_list_head  *ncpp;
2796 
2797 	if (nc_disabled) {
2798 		return;
2799 	}
2800 
2801 	/*
2802 	 * if the entry is for -ve caching vp is null
2803 	 */
2804 	if ((vp != NULLVP) && (LIST_FIRST(&vp->v_nclinks))) {
2805 		/*
2806 		 * someone beat us to the punch..
2807 		 * this vnode is already in the cache
2808 		 */
2809 		if (strname != NULL) {
2810 			vfs_removename(strname);
2811 		}
2812 		return;
2813 	}
2814 	/*
2815 	 * We allocate a new entry if we are less than the maximum
2816 	 * allowed and the one at the front of the list is in use.
2817 	 * Otherwise we use the one at the front of the list.
2818 	 */
2819 	if (numcache < desiredNodes &&
2820 	    ((ncp = nchead.tqh_first) == NULL ||
2821 	    (ncp->nc_counter & NC_VALID))) {
2822 		/*
2823 		 * Allocate one more entry
2824 		 */
2825 		if (nc_smr_enabled) {
2826 			ncp = zalloc_smr(namecache_zone, Z_WAITOK_ZERO_NOFAIL);
2827 		} else {
2828 			ncp = zalloc(namecache_zone);
2829 		}
2830 		ncp->nc_counter = 0;
2831 		numcache++;
2832 	} else {
2833 		/*
2834 		 * reuse an old entry
2835 		 */
2836 		ncp = TAILQ_FIRST(&nchead);
2837 		TAILQ_REMOVE(&nchead, ncp, nc_entry);
2838 
2839 		if (ncp->nc_counter & NC_VALID) {
2840 			/*
2841 			 * still in use... we need to
2842 			 * delete it before re-using it
2843 			 */
2844 			NCHSTAT(ncs_stolen);
2845 			cache_delete(ncp, 0);
2846 		}
2847 	}
2848 	NCHSTAT(ncs_enters);
2849 
2850 	/*
2851 	 * Fill in cache info, if vp is NULL this is a "negative" cache entry.
2852 	 */
2853 	if (vp) {
2854 		ncp->nc_vid = vnode_vid(vp);
2855 		vnode_hold(vp);
2856 	}
2857 	ncp->nc_vp = vp;
2858 	ncp->nc_dvp = dvp;
2859 	ncp->nc_hashval = cnp->cn_hash;
2860 
2861 	if (strname == NULL) {
2862 		ncp->nc_name = add_name_internal(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, FALSE, 0);
2863 	} else {
2864 		ncp->nc_name = strname;
2865 	}
2866 
2867 	//
2868 	// If the bytes of the name associated with the vnode differ,
2869 	// use the name associated with the vnode since the file system
2870 	// may have set that explicitly in the case of a lookup on a
2871 	// case-insensitive file system where the case of the looked up
2872 	// name differs from what is on disk.  For more details, see:
2873 	//   <rdar://problem/8044697> FSEvents doesn't always decompose diacritical unicode chars in the paths of the changed directories
2874 	//
2875 	const char *vn_name = vp ? vp->v_name : NULL;
2876 	unsigned int len = vn_name ? (unsigned int)strlen(vn_name) : 0;
2877 	if (vn_name && ncp && ncp->nc_name && strncmp(ncp->nc_name, vn_name, len) != 0) {
2878 		unsigned int hash = hash_string(vn_name, len);
2879 
2880 		vfs_removename(ncp->nc_name);
2881 		ncp->nc_name = add_name_internal(vn_name, len, hash, FALSE, 0);
2882 		ncp->nc_hashval = hash;
2883 	}
2884 
2885 	/*
2886 	 * make us the newest entry in the cache
2887 	 * i.e. we'll be the last to be stolen
2888 	 */
2889 	TAILQ_INSERT_TAIL(&nchead, ncp, nc_entry);
2890 
2891 	ncpp = NCHHASH(dvp, cnp->cn_hash);
2892 #if DIAGNOSTIC
2893 	{
2894 		struct namecache *p;
2895 
2896 		smrq_serialized_foreach(p, ncpp, nc_hash) {
2897 			if (p == ncp) {
2898 				panic("cache_enter: duplicate");
2899 			}
2900 		}
2901 	}
2902 #endif
2903 	/*
2904 	 * make us available to be found via lookup
2905 	 */
2906 	smrq_serialized_insert_head(ncpp, &ncp->nc_hash);
2907 
2908 	if (vp) {
2909 		/*
2910 		 * add to the list of name cache entries
2911 		 * that point at vp
2912 		 */
2913 		LIST_INSERT_HEAD(&vp->v_nclinks, ncp, nc_un.nc_link);
2914 	} else {
2915 		/*
2916 		 * this is a negative cache entry (vp == NULL)
2917 		 * stick it on the negative cache list.
2918 		 */
2919 		TAILQ_INSERT_TAIL(&neghead, ncp, nc_un.nc_negentry);
2920 
2921 		ncs_negtotal++;
2922 
2923 		if (ncs_negtotal > desiredNegNodes) {
2924 			/*
2925 			 * if we've reached our desired limit
2926 			 * of negative cache entries, delete
2927 			 * the oldest
2928 			 */
2929 			negp = TAILQ_FIRST(&neghead);
2930 			cache_delete(negp, 1);
2931 		}
2932 	}
2933 
2934 	/*
2935 	 * add us to the list of name cache entries that
2936 	 * are children of dvp
2937 	 */
2938 	if (vp) {
2939 		TAILQ_INSERT_TAIL(&dvp->v_ncchildren, ncp, nc_child);
2940 	} else {
2941 		TAILQ_INSERT_HEAD(&dvp->v_ncchildren, ncp, nc_child);
2942 	}
2943 
2944 	/*
2945 	 * nc_counter represents a sequence counter and 1 bit valid flag.
2946 	 * When the counter value is odd, it represents a valid and in use
2947 	 * namecache structure. We increment the value on every state transition
2948 	 * (invalid to valid (here) and valid to invalid (in cache delete).
2949 	 * Lockless readers have to read the value before reading other fields
2950 	 * and ensure that the field is valid and remains the same after the fields
2951 	 * have been read.
2952 	 */
2953 	uint32_t old_count = os_atomic_inc_orig(&ncp->nc_counter, release);
2954 	if (old_count & NC_VALID) {
2955 		/* This is a invalid to valid transition */
2956 		panic("Incorrect state for old nc_counter(%d), should be even", old_count);
2957 	}
2958 }
2959 
2960 
2961 /*
2962  * Initialize CRC-32 remainder table.
2963  */
2964 static void
init_crc32(void)2965 init_crc32(void)
2966 {
2967 	/*
2968 	 * the CRC-32 generator polynomial is:
2969 	 *   x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^10
2970 	 *        + x^8  + x^7  + x^5  + x^4  + x^2  + x + 1
2971 	 */
2972 	unsigned int crc32_polynomial = 0x04c11db7;
2973 	unsigned int i, j;
2974 
2975 	/*
2976 	 * pre-calculate the CRC-32 remainder for each possible octet encoding
2977 	 */
2978 	for (i = 0; i < 256; i++) {
2979 		unsigned int crc_rem = i << 24;
2980 
2981 		for (j = 0; j < 8; j++) {
2982 			if (crc_rem & 0x80000000) {
2983 				crc_rem = (crc_rem << 1) ^ crc32_polynomial;
2984 			} else {
2985 				crc_rem = (crc_rem << 1);
2986 			}
2987 		}
2988 		crc32tab[i] = crc_rem;
2989 	}
2990 }
2991 
2992 
2993 /*
2994  * Name cache initialization, from vfs_init() when we are booting
2995  */
2996 void
nchinit(void)2997 nchinit(void)
2998 {
2999 	desiredNegNodes = (desiredvnodes / 10);
3000 	desiredNodes = desiredvnodes + desiredNegNodes;
3001 
3002 	if (nc_smr_enabled) {
3003 		zone_enable_smr(namecache_zone, VFS_SMR(), &namecache_smr_free);
3004 		zone_enable_smr(stringcache_zone, VFS_SMR(), &string_smr_free);
3005 	}
3006 	TAILQ_INIT(&nchead);
3007 	TAILQ_INIT(&neghead);
3008 
3009 	init_crc32();
3010 
3011 	nchashtbl = hashinit(MAX(CONFIG_NC_HASH, (2 * desiredNodes)), M_CACHE, &nchash);
3012 	nchashmask = nchash;
3013 	nchash++;
3014 
3015 	init_string_table();
3016 
3017 	for (int i = 0; i < NUM_STRCACHE_LOCKS; i++) {
3018 		lck_mtx_init(&strcache_mtx_locks[i], &strcache_lck_grp, &strcache_lck_attr);
3019 	}
3020 }
3021 
3022 void
name_cache_lock_shared(void)3023 name_cache_lock_shared(void)
3024 {
3025 	lck_rw_lock_shared(&namecache_rw_lock);
3026 	NC_SMR_STATS(nc_lock_shared);
3027 }
3028 
3029 void
name_cache_lock(void)3030 name_cache_lock(void)
3031 {
3032 	lck_rw_lock_exclusive(&namecache_rw_lock);
3033 	NC_SMR_STATS(nc_lock);
3034 }
3035 
3036 boolean_t
name_cache_lock_shared_to_exclusive(void)3037 name_cache_lock_shared_to_exclusive(void)
3038 {
3039 	return lck_rw_lock_shared_to_exclusive(&namecache_rw_lock);
3040 }
3041 
3042 void
name_cache_unlock(void)3043 name_cache_unlock(void)
3044 {
3045 	lck_rw_done(&namecache_rw_lock);
3046 }
3047 
3048 
3049 int
resize_namecache(int newsize)3050 resize_namecache(int newsize)
3051 {
3052 	struct smrq_list_head   *new_table;
3053 	struct smrq_list_head   *old_table;
3054 	struct smrq_list_head   *old_head;
3055 	struct namecache    *entry;
3056 	uint32_t            i, hashval;
3057 	int                 dNodes, dNegNodes, nelements;
3058 	u_long              new_size, old_size;
3059 
3060 	if (newsize < 0) {
3061 		return EINVAL;
3062 	}
3063 
3064 	dNegNodes = (newsize / 10);
3065 	dNodes = newsize + dNegNodes;
3066 	// we don't support shrinking yet
3067 	if (dNodes <= desiredNodes) {
3068 		return 0;
3069 	}
3070 
3071 	if (os_mul_overflow(dNodes, 2, &nelements)) {
3072 		return EINVAL;
3073 	}
3074 
3075 	new_table = hashinit(nelements, M_CACHE, &nchashmask);
3076 	new_size  = nchashmask + 1;
3077 
3078 	if (new_table == NULL) {
3079 		return ENOMEM;
3080 	}
3081 
3082 	NAME_CACHE_LOCK();
3083 
3084 	/* No need to switch if the hash table size hasn't changed. */
3085 	if (new_size == nchash) {
3086 		NAME_CACHE_UNLOCK();
3087 		hashdestroy(new_table, M_CACHE, new_size - 1);
3088 		return 0;
3089 	}
3090 
3091 	// do the switch!
3092 	old_table = nchashtbl;
3093 	nchashtbl = new_table;
3094 	old_size  = nchash;
3095 	nchash    = new_size;
3096 
3097 	// walk the old table and insert all the entries into
3098 	// the new table
3099 	//
3100 	for (i = 0; i < old_size; i++) {
3101 		old_head = &old_table[i];
3102 		smrq_serialized_foreach_safe(entry, old_head, nc_hash) {
3103 			//
3104 			// XXXdbg - Beware: this assumes that hash_string() does
3105 			//                  the same thing as what happens in
3106 			//                  lookup() over in vfs_lookup.c
3107 			hashval = hash_string(entry->nc_name, 0);
3108 			entry->nc_hashval = hashval;
3109 
3110 			smrq_serialized_insert_head(NCHHASH(entry->nc_dvp, hashval), &entry->nc_hash);
3111 		}
3112 	}
3113 	desiredNodes = dNodes;
3114 	desiredNegNodes = dNegNodes;
3115 
3116 	NAME_CACHE_UNLOCK();
3117 	hashdestroy(old_table, M_CACHE, old_size - 1);
3118 
3119 	return 0;
3120 }
3121 
3122 static void
namecache_smr_free(void * _ncp,__unused size_t _size)3123 namecache_smr_free(void *_ncp, __unused size_t _size)
3124 {
3125 	struct namecache *ncp = _ncp;
3126 
3127 	bzero(ncp, sizeof(*ncp));
3128 }
3129 
3130 static void
cache_delete(struct namecache * ncp,int free_entry)3131 cache_delete(struct namecache *ncp, int free_entry)
3132 {
3133 	NCHSTAT(ncs_deletes);
3134 
3135 	/*
3136 	 * See comment at the end of cache_enter_locked expalining the usage of
3137 	 * nc_counter.
3138 	 */
3139 	uint32_t old_count = os_atomic_inc_orig(&ncp->nc_counter, release);
3140 	if (!(old_count & NC_VALID)) {
3141 		/* This should be a valid to invalid transition */
3142 		panic("Incorrect state for old nc_counter(%d), should be odd", old_count);
3143 	}
3144 
3145 	if (ncp->nc_vp) {
3146 		LIST_REMOVE(ncp, nc_un.nc_link);
3147 	} else {
3148 		TAILQ_REMOVE(&neghead, ncp, nc_un.nc_negentry);
3149 		ncs_negtotal--;
3150 	}
3151 	TAILQ_REMOVE(&(ncp->nc_dvp->v_ncchildren), ncp, nc_child);
3152 
3153 	smrq_serialized_remove((NCHHASH(ncp->nc_dvp, ncp->nc_hashval)), &ncp->nc_hash);
3154 
3155 	const char *nc_name = ncp->nc_name;
3156 	ncp->nc_name = NULL;
3157 	vfs_removename(nc_name);
3158 	if (ncp->nc_vp) {
3159 		vnode_t vp = ncp->nc_vp;
3160 
3161 		ncp->nc_vp = NULLVP;
3162 		vnode_drop(vp);
3163 	}
3164 
3165 	if (free_entry) {
3166 		TAILQ_REMOVE(&nchead, ncp, nc_entry);
3167 		if (nc_smr_enabled) {
3168 			zfree_smr(namecache_zone, ncp);
3169 		} else {
3170 			zfree(namecache_zone, ncp);
3171 		}
3172 		numcache--;
3173 	}
3174 }
3175 
3176 
3177 /*
3178  * purge the entry associated with the
3179  * specified vnode from the name cache
3180  */
3181 static void
cache_purge_locked(vnode_t vp,kauth_cred_t * credp)3182 cache_purge_locked(vnode_t vp, kauth_cred_t *credp)
3183 {
3184 	struct namecache *ncp;
3185 
3186 	*credp = NULL;
3187 	if ((LIST_FIRST(&vp->v_nclinks) == NULL) &&
3188 	    (TAILQ_FIRST(&vp->v_ncchildren) == NULL) &&
3189 	    (vnode_cred(vp) == NOCRED) &&
3190 	    (vp->v_parent == NULLVP)) {
3191 		return;
3192 	}
3193 
3194 	if (vp->v_parent) {
3195 		vp->v_parent->v_nc_generation++;
3196 	}
3197 
3198 	while ((ncp = LIST_FIRST(&vp->v_nclinks))) {
3199 		cache_delete(ncp, 1);
3200 	}
3201 
3202 	while ((ncp = TAILQ_FIRST(&vp->v_ncchildren))) {
3203 		cache_delete(ncp, 1);
3204 	}
3205 
3206 	/*
3207 	 * Use a temp variable to avoid kauth_cred_unref() while NAME_CACHE_LOCK is held
3208 	 */
3209 	*credp = vnode_cred(vp);
3210 	vp->v_cred = NOCRED;
3211 	vp->v_authorized_actions = 0;
3212 }
3213 
3214 void
cache_purge(vnode_t vp)3215 cache_purge(vnode_t vp)
3216 {
3217 	kauth_cred_t tcred = NULL;
3218 
3219 	if ((LIST_FIRST(&vp->v_nclinks) == NULL) &&
3220 	    (TAILQ_FIRST(&vp->v_ncchildren) == NULL) &&
3221 	    (vnode_cred(vp) == NOCRED) &&
3222 	    (vp->v_parent == NULLVP)) {
3223 		return;
3224 	}
3225 
3226 	NAME_CACHE_LOCK();
3227 
3228 	cache_purge_locked(vp, &tcred);
3229 
3230 	NAME_CACHE_UNLOCK();
3231 
3232 	if (IS_VALID_CRED(tcred)) {
3233 		kauth_cred_unref(&tcred);
3234 	}
3235 }
3236 
3237 /*
3238  * Purge all negative cache entries that are children of the
3239  * given vnode.  A case-insensitive file system (or any file
3240  * system that has multiple equivalent names for the same
3241  * directory entry) can use this when creating or renaming
3242  * to remove negative entries that may no longer apply.
3243  */
3244 void
cache_purge_negatives(vnode_t vp)3245 cache_purge_negatives(vnode_t vp)
3246 {
3247 	struct namecache *ncp, *next_ncp;
3248 
3249 	NAME_CACHE_LOCK();
3250 
3251 	TAILQ_FOREACH_SAFE(ncp, &vp->v_ncchildren, nc_child, next_ncp) {
3252 		if (ncp->nc_vp) {
3253 			break;
3254 		}
3255 
3256 		cache_delete(ncp, 1);
3257 	}
3258 
3259 	NAME_CACHE_UNLOCK();
3260 }
3261 
3262 /*
3263  * Flush all entries referencing a particular filesystem.
3264  *
3265  * Since we need to check it anyway, we will flush all the invalid
3266  * entries at the same time.
3267  */
3268 void
cache_purgevfs(struct mount * mp)3269 cache_purgevfs(struct mount *mp)
3270 {
3271 	struct smrq_list_head *ncpp;
3272 	struct namecache *ncp;
3273 
3274 	NAME_CACHE_LOCK();
3275 	/* Scan hash tables for applicable entries */
3276 	for (ncpp = &nchashtbl[nchash - 1]; ncpp >= nchashtbl; ncpp--) {
3277 restart:
3278 		smrq_serialized_foreach(ncp, ncpp, nc_hash) {
3279 			if (ncp->nc_dvp->v_mount == mp) {
3280 				cache_delete(ncp, 0);
3281 				goto restart;
3282 			}
3283 		}
3284 	}
3285 	NAME_CACHE_UNLOCK();
3286 }
3287 
3288 
3289 
3290 //
3291 // String ref routines
3292 //
3293 static LIST_HEAD(stringhead, string_t) * string_ref_table;
3294 static u_long   string_table_mask;
3295 static uint32_t filled_buckets = 0;
3296 
3297 
3298 
3299 
3300 static void
resize_string_ref_table(void)3301 resize_string_ref_table(void)
3302 {
3303 	struct stringhead *new_table;
3304 	struct stringhead *old_table;
3305 	struct stringhead *old_head, *head;
3306 	string_t          *entry, *next;
3307 	uint32_t           i, hashval;
3308 	u_long             new_mask, old_mask;
3309 
3310 	/*
3311 	 * need to hold the table lock exclusively
3312 	 * in order to grow the table... need to recheck
3313 	 * the need to resize again after we've taken
3314 	 * the lock exclusively in case some other thread
3315 	 * beat us to the punch
3316 	 */
3317 	lck_rw_lock_exclusive(&strtable_rw_lock);
3318 
3319 	if (4 * filled_buckets < ((string_table_mask + 1) * 3)) {
3320 		lck_rw_done(&strtable_rw_lock);
3321 		return;
3322 	}
3323 	assert(string_table_mask < INT32_MAX);
3324 	new_table = hashinit((int)(string_table_mask + 1) * 2, M_CACHE, &new_mask);
3325 
3326 	if (new_table == NULL) {
3327 		printf("failed to resize the hash table.\n");
3328 		lck_rw_done(&strtable_rw_lock);
3329 		return;
3330 	}
3331 
3332 	// do the switch!
3333 	old_table         = string_ref_table;
3334 	string_ref_table  = new_table;
3335 	old_mask          = string_table_mask;
3336 	string_table_mask = new_mask;
3337 	filled_buckets    = 0;
3338 
3339 	// walk the old table and insert all the entries into
3340 	// the new table
3341 	//
3342 	for (i = 0; i <= old_mask; i++) {
3343 		old_head = &old_table[i];
3344 		for (entry = old_head->lh_first; entry != NULL; entry = next) {
3345 			hashval = hash_string((const char *)entry->str, 0);
3346 			head = &string_ref_table[hashval & string_table_mask];
3347 			if (head->lh_first == NULL) {
3348 				filled_buckets++;
3349 			}
3350 			next = entry->hash_chain.le_next;
3351 			LIST_INSERT_HEAD(head, entry, hash_chain);
3352 		}
3353 	}
3354 	lck_rw_done(&strtable_rw_lock);
3355 
3356 	hashdestroy(old_table, M_CACHE, old_mask);
3357 }
3358 
3359 
3360 static void
init_string_table(void)3361 init_string_table(void)
3362 {
3363 	string_ref_table = hashinit(CONFIG_VFS_NAMES, M_CACHE, &string_table_mask);
3364 }
3365 
3366 
3367 const char *
vfs_addname(const char * name,uint32_t len,u_int hashval,u_int flags)3368 vfs_addname(const char *name, uint32_t len, u_int hashval, u_int flags)
3369 {
3370 	return add_name_internal(name, len, hashval, FALSE, flags);
3371 }
3372 
3373 
3374 static const char *
add_name_internal(const char * name,uint32_t len,u_int hashval,boolean_t need_extra_ref,__unused u_int flags)3375 add_name_internal(const char *name, uint32_t len, u_int hashval, boolean_t need_extra_ref, __unused u_int flags)
3376 {
3377 	struct stringhead *head;
3378 	string_t          *entry;
3379 	uint32_t          chain_len = 0;
3380 	uint32_t          hash_index;
3381 	uint32_t          lock_index;
3382 	char              *ptr;
3383 
3384 	if (len > MAXPATHLEN) {
3385 		len = MAXPATHLEN;
3386 	}
3387 
3388 	/*
3389 	 * if the length already accounts for the null-byte, then
3390 	 * subtract one so later on we don't index past the end
3391 	 * of the string.
3392 	 */
3393 	if (len > 0 && name[len - 1] == '\0') {
3394 		len--;
3395 	}
3396 	if (hashval == 0) {
3397 		hashval = hash_string(name, len);
3398 	}
3399 
3400 	/*
3401 	 * take this lock 'shared' to keep the hash stable
3402 	 * if someone else decides to grow the pool they
3403 	 * will take this lock exclusively
3404 	 */
3405 	lck_rw_lock_shared(&strtable_rw_lock);
3406 
3407 	/*
3408 	 * If the table gets more than 3/4 full, resize it
3409 	 */
3410 	if (4 * filled_buckets >= ((string_table_mask + 1) * 3)) {
3411 		lck_rw_done(&strtable_rw_lock);
3412 
3413 		resize_string_ref_table();
3414 
3415 		lck_rw_lock_shared(&strtable_rw_lock);
3416 	}
3417 	hash_index = hashval & string_table_mask;
3418 	lock_index = hash_index % NUM_STRCACHE_LOCKS;
3419 
3420 	head = &string_ref_table[hash_index];
3421 
3422 	lck_mtx_lock_spin(&strcache_mtx_locks[lock_index]);
3423 
3424 	for (entry = head->lh_first; entry != NULL; chain_len++, entry = entry->hash_chain.le_next) {
3425 		if (strncmp(entry->str, name, len) == 0 && entry->str[len] == 0) {
3426 			entry->refcount++;
3427 			break;
3428 		}
3429 	}
3430 	if (entry == NULL) {
3431 		const uint32_t buflen = len + 1;
3432 
3433 		lck_mtx_convert_spin(&strcache_mtx_locks[lock_index]);
3434 		/*
3435 		 * it wasn't already there so add it.
3436 		 */
3437 		if (nc_smr_enabled) {
3438 			entry = zalloc_smr(stringcache_zone, Z_WAITOK_ZERO_NOFAIL);
3439 		} else {
3440 			entry = zalloc(stringcache_zone);
3441 		}
3442 
3443 		if (head->lh_first == NULL) {
3444 			OSAddAtomic(1, &filled_buckets);
3445 		}
3446 		ptr = kalloc_data(buflen, Z_WAITOK);
3447 		strncpy(ptr, name, len);
3448 		ptr[len] = '\0';
3449 		entry->str = ptr;
3450 		entry->strbuflen = buflen;
3451 		entry->refcount = 1;
3452 		LIST_INSERT_HEAD(head, entry, hash_chain);
3453 	}
3454 	if (need_extra_ref == TRUE) {
3455 		entry->refcount++;
3456 	}
3457 
3458 	lck_mtx_unlock(&strcache_mtx_locks[lock_index]);
3459 	lck_rw_done(&strtable_rw_lock);
3460 
3461 	return (const char *)entry->str;
3462 }
3463 
3464 static void
string_smr_free(void * _entry,__unused size_t size)3465 string_smr_free(void *_entry, __unused size_t size)
3466 {
3467 	string_t *entry = _entry;
3468 
3469 	kfree_data(entry->str, entry->strbuflen);
3470 	bzero(entry, sizeof(*entry));
3471 }
3472 
3473 int
vfs_removename(const char * nameref)3474 vfs_removename(const char *nameref)
3475 {
3476 	struct stringhead *head;
3477 	string_t          *entry;
3478 	uint32_t           hashval;
3479 	uint32_t           hash_index;
3480 	uint32_t           lock_index;
3481 	int                retval = ENOENT;
3482 
3483 	hashval = hash_string(nameref, 0);
3484 
3485 	/*
3486 	 * take this lock 'shared' to keep the hash stable
3487 	 * if someone else decides to grow the pool they
3488 	 * will take this lock exclusively
3489 	 */
3490 	lck_rw_lock_shared(&strtable_rw_lock);
3491 	/*
3492 	 * must compute the head behind the table lock
3493 	 * since the size and location of the table
3494 	 * can change on the fly
3495 	 */
3496 	hash_index = hashval & string_table_mask;
3497 	lock_index = hash_index % NUM_STRCACHE_LOCKS;
3498 
3499 	head = &string_ref_table[hash_index];
3500 
3501 	lck_mtx_lock_spin(&strcache_mtx_locks[lock_index]);
3502 
3503 	for (entry = head->lh_first; entry != NULL; entry = entry->hash_chain.le_next) {
3504 		if (entry->str == nameref) {
3505 			entry->refcount--;
3506 
3507 			if (entry->refcount == 0) {
3508 				LIST_REMOVE(entry, hash_chain);
3509 
3510 				if (head->lh_first == NULL) {
3511 					OSAddAtomic(-1, &filled_buckets);
3512 				}
3513 			} else {
3514 				entry = NULL;
3515 			}
3516 			retval = 0;
3517 			break;
3518 		}
3519 	}
3520 	lck_mtx_unlock(&strcache_mtx_locks[lock_index]);
3521 	lck_rw_done(&strtable_rw_lock);
3522 
3523 	if (entry) {
3524 		assert(entry->refcount == 0);
3525 		if (nc_smr_enabled) {
3526 			zfree_smr(stringcache_zone, entry);
3527 		} else {
3528 			kfree_data(entry->str, entry->strbuflen);
3529 			entry->str = NULL;
3530 			entry->strbuflen = 0;
3531 			zfree(stringcache_zone, entry);
3532 		}
3533 	}
3534 
3535 	return retval;
3536 }
3537 
3538 
3539 #ifdef DUMP_STRING_TABLE
3540 void
dump_string_table(void)3541 dump_string_table(void)
3542 {
3543 	struct stringhead *head;
3544 	string_t          *entry;
3545 	u_long            i;
3546 
3547 	lck_rw_lock_shared(&strtable_rw_lock);
3548 
3549 	for (i = 0; i <= string_table_mask; i++) {
3550 		head = &string_ref_table[i];
3551 		for (entry = head->lh_first; entry != NULL; entry = entry->hash_chain.le_next) {
3552 			printf("%6d - %s\n", entry->refcount, entry->str);
3553 		}
3554 	}
3555 	lck_rw_done(&strtable_rw_lock);
3556 }
3557 #endif  /* DUMP_STRING_TABLE */
3558