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