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