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