2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993, 1995
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Poul-Henning Kamp of the FreeBSD Project.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
41 #include "opt_ktrace.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/capsicum.h>
46 #include <sys/counter.h>
47 #include <sys/filedesc.h>
48 #include <sys/fnv_hash.h>
49 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/fcntl.h>
55 #include <sys/mount.h>
56 #include <sys/namei.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysproto.h>
65 #include <sys/vnode.h>
68 #include <sys/ktrace.h>
71 #include <machine/_inttypes.h>
74 #include <sys/capsicum.h>
76 #include <security/audit/audit.h>
77 #include <security/mac/mac_framework.h>
86 * High level overview of name caching in the VFS layer.
88 * Originally caching was implemented as part of UFS, later extracted to allow
89 * use by other filesystems. A decision was made to make it optional and
90 * completely detached from the rest of the kernel, which comes with limitations
91 * outlined near the end of this comment block.
93 * This fundamental choice needs to be revisited. In the meantime, the current
94 * state is described below. Significance of all notable routines is explained
95 * in comments placed above their implementation. Scattered thoroughout the
96 * file are TODO comments indicating shortcomings which can be fixed without
97 * reworking everything (most of the fixes will likely be reusable). Various
98 * details are omitted from this explanation to not clutter the overview, they
99 * have to be checked by reading the code and associated commentary.
101 * Keep in mind that it's individual path components which are cached, not full
102 * paths. That is, for a fully cached path "foo/bar/baz" there are 3 entries,
105 * I. Data organization
107 * Entries are described by "struct namecache" objects and stored in a hash
108 * table. See cache_get_hash for more information.
110 * "struct vnode" contains pointers to source entries (names which can be found
111 * when traversing through said vnode), destination entries (names of that
112 * vnode (see "Limitations" for a breakdown on the subject) and a pointer to
115 * The (directory vnode; name) tuple reliably determines the target entry if
118 * Since there are no small locks at this time (all are 32 bytes in size on
119 * LP64), the code works around the problem by introducing lock arrays to
120 * protect hash buckets and vnode lists.
122 * II. Filesystem integration
124 * Filesystems participating in name caching do the following:
125 * - set vop_lookup routine to vfs_cache_lookup
126 * - set vop_cachedlookup to whatever can perform the lookup if the above fails
127 * - if they support lockless lookup (see below), vop_fplookup_vexec and
128 * vop_fplookup_symlink are set along with the MNTK_FPLOOKUP flag on the
130 * - call cache_purge or cache_vop_* routines to eliminate stale entries as
132 * - call cache_enter to add entries depending on the MAKEENTRY flag
134 * With the above in mind, there are 2 entry points when doing lookups:
135 * - ... -> namei -> cache_fplookup -- this is the default
136 * - ... -> VOP_LOOKUP -> vfs_cache_lookup -- normally only called by namei
137 * should the above fail
139 * Example code flow how an entry is added:
140 * ... -> namei -> cache_fplookup -> cache_fplookup_noentry -> VOP_LOOKUP ->
141 * vfs_cache_lookup -> VOP_CACHEDLOOKUP -> ufs_lookup_ino -> cache_enter
143 * III. Performance considerations
145 * For lockless case forward lookup avoids any writes to shared areas apart
146 * from the terminal path component. In other words non-modifying lookups of
147 * different files don't suffer any scalability problems in the namecache.
148 * Looking up the same file is limited by VFS and goes beyond the scope of this
151 * At least on amd64 the single-threaded bottleneck for long paths is hashing
152 * (see cache_get_hash). There are cases where the code issues acquire fence
153 * multiple times, they can be combined on architectures which suffer from it.
155 * For locked case each encountered vnode has to be referenced and locked in
156 * order to be handed out to the caller (normally that's namei). This
157 * introduces significant hit single-threaded and serialization multi-threaded.
159 * Reverse lookup (e.g., "getcwd") fully scales provided it is fully cached --
160 * avoids any writes to shared areas to any components.
162 * Unrelated insertions are partially serialized on updating the global entry
163 * counter and possibly serialized on colliding bucket or vnode locks.
167 * Note not everything has an explicit dtrace probe nor it should have, thus
168 * some of the one-liners below depend on implementation details.
172 * # Check what lookups failed to be handled in a lockless manner. Column 1 is
173 * # line number, column 2 is status code (see cache_fpl_status)
174 * dtrace -n 'vfs:fplookup:lookup:done { @[arg1, arg2] = count(); }'
176 * # Lengths of names added by binary name
177 * dtrace -n 'fbt::cache_enter_time:entry { @[execname] = quantize(args[2]->cn_namelen); }'
179 * # Same as above but only those which exceed 64 characters
180 * dtrace -n 'fbt::cache_enter_time:entry /args[2]->cn_namelen > 64/ { @[execname] = quantize(args[2]->cn_namelen); }'
182 * # Who is performing lookups with spurious slashes (e.g., "foo//bar") and what
184 * dtrace -n 'fbt::cache_fplookup_skip_slashes:entry { @[execname, stringof(args[0]->cnp->cn_pnbuf)] = count(); }'
186 * V. Limitations and implementation defects
188 * - since it is possible there is no entry for an open file, tools like
189 * "procstat" may fail to resolve fd -> vnode -> path to anything
190 * - even if a filesystem adds an entry, it may get purged (e.g., due to memory
191 * shortage) in which case the above problem applies
192 * - hardlinks are not tracked, thus if a vnode is reachable in more than one
193 * way, resolving a name may return a different path than the one used to
194 * open it (even if said path is still valid)
195 * - by default entries are not added for newly created files
196 * - adding an entry may need to evict negative entry first, which happens in 2
197 * distinct places (evicting on lookup, adding in a later VOP) making it
198 * impossible to simply reuse it
199 * - there is a simple scheme to evict negative entries as the cache is approaching
200 * its capacity, but it is very unclear if doing so is a good idea to begin with
201 * - vnodes are subject to being recycled even if target inode is left in memory,
202 * which loses the name cache entries when it perhaps should not. in case of tmpfs
203 * names get duplicated -- kept by filesystem itself and namecache separately
204 * - struct namecache has a fixed size and comes in 2 variants, often wasting space.
205 * now hard to replace with malloc due to dependence on SMR.
206 * - lack of better integration with the kernel also turns nullfs into a layered
207 * filesystem instead of something which can take advantage of caching
210 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
213 SDT_PROVIDER_DECLARE(vfs);
214 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
216 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
218 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
220 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
222 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
223 "struct namecache *", "int", "int");
224 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
225 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
226 "char *", "struct vnode *");
227 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
228 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
229 "struct vnode *", "char *");
230 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
232 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
233 "struct vnode *", "char *");
234 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
236 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
237 "struct componentname *");
238 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
239 "struct componentname *");
240 SDT_PROBE_DEFINE3(vfs, namecache, purge, done, "struct vnode *", "size_t", "size_t");
241 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
242 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
243 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
244 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
246 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
248 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
250 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
252 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
253 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
254 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
256 static char __read_frequently cache_fast_lookup_enabled = true;
259 * This structure describes the elements in the cache of recent
260 * names looked up by namei.
266 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
267 "the state must fit in a union with a pointer without growing it");
270 LIST_ENTRY(namecache) nc_src; /* source vnode list */
271 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
272 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
273 struct vnode *nc_dvp; /* vnode of parent of name */
275 struct vnode *nu_vp; /* vnode the name refers to */
276 struct negstate nu_neg;/* negative entry state */
278 u_char nc_flag; /* flag bits */
279 u_char nc_nlen; /* length of name */
280 char nc_name[]; /* segment name + nul */
284 * struct namecache_ts repeats struct namecache layout up to the
286 * struct namecache_ts is used in place of struct namecache when time(s) need
287 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
288 * both a non-dotdot directory name plus dotdot for the directory's
291 * See below for alignment requirement.
293 struct namecache_ts {
294 struct timespec nc_time; /* timespec provided by fs */
295 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
296 int nc_ticks; /* ticks value when entry was added */
298 struct namecache nc_nc;
301 TAILQ_HEAD(cache_freebatch, namecache);
304 * At least mips n32 performs 64-bit accesses to timespec as found
305 * in namecache_ts and requires them to be aligned. Since others
306 * may be in the same spot suffer a little bit and enforce the
307 * alignment for everyone. Note this is a nop for 64-bit platforms.
309 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
312 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
313 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
314 * smaller and the value was bumped to retain the total size, but it
315 * was never re-evaluated for suitability. A simple test counting
316 * lengths during package building shows that the value of 45 covers
317 * about 86% of all added entries, reaching 99% at 65.
319 * Regardless of the above, use of dedicated zones instead of malloc may be
320 * inducing additional waste. This may be hard to address as said zones are
321 * tied to VFS SMR. Even if retaining them, the current split should be
325 #define CACHE_PATH_CUTOFF 45
326 #define CACHE_LARGE_PAD 6
328 #define CACHE_PATH_CUTOFF 41
329 #define CACHE_LARGE_PAD 2
332 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
333 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
334 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
335 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
337 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
338 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
339 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
340 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
342 #define nc_vp n_un.nu_vp
343 #define nc_neg n_un.nu_neg
346 * Flags in namecache.nc_flag
348 #define NCF_WHITE 0x01
349 #define NCF_ISDOTDOT 0x02
352 #define NCF_DVDROP 0x10
353 #define NCF_NEGATIVE 0x20
354 #define NCF_INVALID 0x40
358 * Flags in negstate.neg_flag
362 static bool cache_neg_evict_cond(u_long lnumcache);
365 * Mark an entry as invalid.
367 * This is called before it starts getting deconstructed.
370 cache_ncp_invalidate(struct namecache *ncp)
373 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
374 ("%s: entry %p already invalid", __func__, ncp));
375 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
376 atomic_thread_fence_rel();
380 * Check whether the entry can be safely used.
382 * All places which elide locks are supposed to call this after they are
383 * done with reading from an entry.
385 #define cache_ncp_canuse(ncp) ({ \
386 struct namecache *_ncp = (ncp); \
389 atomic_thread_fence_acq(); \
390 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
391 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0); \
395 * Like the above but also checks NCF_WHITE.
397 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
398 struct namecache *_ncp = (ncp); \
401 atomic_thread_fence_acq(); \
402 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
403 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
408 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
409 "Name cache parameters");
411 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
412 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
413 "Total namecache capacity");
415 u_int ncsizefactor = 2;
416 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
417 "Size factor for namecache");
419 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
420 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
421 "Ratio of negative namecache entries");
424 * Negative entry % of namecache capacity above which automatic eviction is allowed.
426 * Check cache_neg_evict_cond for details.
428 static u_int ncnegminpct = 3;
430 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
431 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
432 "Negative entry count above which automatic eviction is allowed");
435 * Structures associated with name caching.
437 #define NCHHASH(hash) \
438 (&nchashtbl[(hash) & nchash])
439 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
440 static u_long __read_mostly nchash; /* size of hash table */
441 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
442 "Size of namecache hash table");
443 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
444 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
446 struct nchstats nchstats; /* cache effectiveness statistics */
448 static u_int __exclusive_cache_line neg_cycle;
451 #define numneglists (ncneghash + 1)
454 struct mtx nl_evict_lock;
455 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
456 TAILQ_HEAD(, namecache) nl_list;
457 TAILQ_HEAD(, namecache) nl_hotlist;
459 } __aligned(CACHE_LINE_SIZE);
461 static struct neglist neglists[numneglists];
463 static inline struct neglist *
464 NCP2NEGLIST(struct namecache *ncp)
467 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
470 static inline struct negstate *
471 NCP2NEGSTATE(struct namecache *ncp)
474 MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
475 return (&ncp->nc_neg);
478 #define numbucketlocks (ncbuckethash + 1)
479 static u_int __read_mostly ncbuckethash;
480 static struct mtx_padalign __read_mostly *bucketlocks;
481 #define HASH2BUCKETLOCK(hash) \
482 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
484 #define numvnodelocks (ncvnodehash + 1)
485 static u_int __read_mostly ncvnodehash;
486 static struct mtx __read_mostly *vnodelocks;
487 static inline struct mtx *
488 VP2VNODELOCK(struct vnode *vp)
491 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
495 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
497 struct namecache_ts *ncp_ts;
499 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
500 (tsp == NULL && ticksp == NULL),
506 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
507 *tsp = ncp_ts->nc_time;
508 *ticksp = ncp_ts->nc_ticks;
512 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
513 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
514 "VFS namecache enabled");
517 /* Export size information to userland */
518 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
519 sizeof(struct namecache), "sizeof(struct namecache)");
522 * The new name cache statistics
524 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
525 "Name cache statistics");
527 #define STATNODE_ULONG(name, varname, descr) \
528 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
529 #define STATNODE_COUNTER(name, varname, descr) \
530 static COUNTER_U64_DEFINE_EARLY(varname); \
531 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
533 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
534 STATNODE_ULONG(count, numcache, "Number of cache entries");
535 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
536 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
537 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
538 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
539 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
540 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
541 STATNODE_COUNTER(posszaps, numposzaps,
542 "Number of cache hits (positive) we do not want to cache");
543 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
544 STATNODE_COUNTER(negzaps, numnegzaps,
545 "Number of cache hits (negative) we do not want to cache");
546 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
547 /* These count for vn_getcwd(), too. */
548 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
549 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
550 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
551 "Number of fullpath search errors (VOP_VPTOCNP failures)");
552 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
553 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
554 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
557 * Debug or developer statistics.
559 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
560 "Name cache debugging");
561 #define DEBUGNODE_ULONG(name, varname, descr) \
562 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
563 #define DEBUGNODE_COUNTER(name, varname, descr) \
564 static COUNTER_U64_DEFINE_EARLY(varname); \
565 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
567 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
568 "Number of successful removals after relocking");
569 static long zap_bucket_fail;
570 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
571 static long zap_bucket_fail2;
572 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
573 static long cache_lock_vnodes_cel_3_failures;
574 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
575 "Number of times 3-way vnode locking failed");
577 static void cache_zap_locked(struct namecache *ncp);
578 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
579 char **retbuf, size_t *buflen, size_t addend);
580 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
581 char **retbuf, size_t *buflen);
582 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
583 char **retbuf, size_t *len, size_t addend);
585 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
588 cache_assert_vlp_locked(struct mtx *vlp)
592 mtx_assert(vlp, MA_OWNED);
596 cache_assert_vnode_locked(struct vnode *vp)
600 vlp = VP2VNODELOCK(vp);
601 cache_assert_vlp_locked(vlp);
605 * Directory vnodes with entries are held for two reasons:
606 * 1. make them less of a target for reclamation in vnlru
607 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
609 * It will be feasible to stop doing it altogether if all filesystems start
610 * supporting lockless lookup.
613 cache_hold_vnode(struct vnode *vp)
616 cache_assert_vnode_locked(vp);
617 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
619 counter_u64_add(numcachehv, 1);
623 cache_drop_vnode(struct vnode *vp)
627 * Called after all locks are dropped, meaning we can't assert
628 * on the state of v_cache_src.
631 counter_u64_add(numcachehv, -1);
637 static uma_zone_t __read_mostly cache_zone_small;
638 static uma_zone_t __read_mostly cache_zone_small_ts;
639 static uma_zone_t __read_mostly cache_zone_large;
640 static uma_zone_t __read_mostly cache_zone_large_ts;
643 cache_symlink_alloc(size_t size, int flags)
646 if (size < CACHE_ZONE_SMALL_SIZE) {
647 return (uma_zalloc_smr(cache_zone_small, flags));
649 if (size < CACHE_ZONE_LARGE_SIZE) {
650 return (uma_zalloc_smr(cache_zone_large, flags));
652 counter_u64_add(symlinktoobig, 1);
653 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
658 cache_symlink_free(char *string, size_t size)
661 MPASS(string != NULL);
662 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
663 ("%s: size %zu too big", __func__, size));
665 if (size < CACHE_ZONE_SMALL_SIZE) {
666 uma_zfree_smr(cache_zone_small, string);
669 if (size < CACHE_ZONE_LARGE_SIZE) {
670 uma_zfree_smr(cache_zone_large, string);
673 __assert_unreachable();
676 static struct namecache *
677 cache_alloc_uma(int len, bool ts)
679 struct namecache_ts *ncp_ts;
680 struct namecache *ncp;
682 if (__predict_false(ts)) {
683 if (len <= CACHE_PATH_CUTOFF)
684 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
686 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
687 ncp = &ncp_ts->nc_nc;
689 if (len <= CACHE_PATH_CUTOFF)
690 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
692 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
698 cache_free_uma(struct namecache *ncp)
700 struct namecache_ts *ncp_ts;
702 if (__predict_false(ncp->nc_flag & NCF_TS)) {
703 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
704 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
705 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
707 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
709 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
710 uma_zfree_smr(cache_zone_small, ncp);
712 uma_zfree_smr(cache_zone_large, ncp);
716 static struct namecache *
717 cache_alloc(int len, bool ts)
722 * Avoid blowout in namecache entries.
725 * 1. filesystems may end up trying to add an already existing entry
726 * (for example this can happen after a cache miss during concurrent
727 * lookup), in which case we will call cache_neg_evict despite not
729 * 2. the routine may fail to free anything and no provisions are made
730 * to make it try harder (see the inside for failure modes)
731 * 3. it only ever looks at negative entries.
733 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
734 if (cache_neg_evict_cond(lnumcache)) {
735 lnumcache = atomic_load_long(&numcache);
737 if (__predict_false(lnumcache >= ncsize)) {
738 atomic_subtract_long(&numcache, 1);
739 counter_u64_add(numdrops, 1);
742 return (cache_alloc_uma(len, ts));
746 cache_free(struct namecache *ncp)
750 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
751 cache_drop_vnode(ncp->nc_dvp);
754 atomic_subtract_long(&numcache, 1);
758 cache_free_batch(struct cache_freebatch *batch)
760 struct namecache *ncp, *nnp;
764 if (TAILQ_EMPTY(batch))
766 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
767 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
768 cache_drop_vnode(ncp->nc_dvp);
773 atomic_subtract_long(&numcache, i);
775 SDT_PROBE1(vfs, namecache, purge, batch, i);
781 * The code was made to use FNV in 2001 and this choice needs to be revisited.
783 * Short summary of the difficulty:
784 * The longest name which can be inserted is NAME_MAX characters in length (or
785 * 255 at the time of writing this comment), while majority of names used in
786 * practice are significantly shorter (mostly below 10). More importantly
787 * majority of lookups performed find names are even shorter than that.
789 * This poses a problem where hashes which do better than FNV past word size
790 * (or so) tend to come with additional overhead when finalizing the result,
791 * making them noticeably slower for the most commonly used range.
793 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
795 * When looking it up the most time consuming part by a large margin (at least
796 * on amd64) is hashing. Replacing FNV with something which pessimizes short
797 * input would make the slowest part stand out even more.
801 * TODO: With the value stored we can do better than computing the hash based
805 cache_prehash(struct vnode *vp)
808 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
812 cache_get_hash(char *name, u_char len, struct vnode *dvp)
815 return (fnv_32_buf(name, len, dvp->v_nchash));
819 cache_get_hash_iter_start(struct vnode *dvp)
822 return (dvp->v_nchash);
826 cache_get_hash_iter(char c, uint32_t hash)
829 return (fnv_32_buf(&c, 1, hash));
833 cache_get_hash_iter_finish(uint32_t hash)
839 static inline struct nchashhead *
840 NCP2BUCKET(struct namecache *ncp)
844 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
845 return (NCHHASH(hash));
848 static inline struct mtx *
849 NCP2BUCKETLOCK(struct namecache *ncp)
853 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
854 return (HASH2BUCKETLOCK(hash));
859 cache_assert_bucket_locked(struct namecache *ncp)
863 blp = NCP2BUCKETLOCK(ncp);
864 mtx_assert(blp, MA_OWNED);
868 cache_assert_bucket_unlocked(struct namecache *ncp)
872 blp = NCP2BUCKETLOCK(ncp);
873 mtx_assert(blp, MA_NOTOWNED);
876 #define cache_assert_bucket_locked(x) do { } while (0)
877 #define cache_assert_bucket_unlocked(x) do { } while (0)
880 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
882 _cache_sort_vnodes(void **p1, void **p2)
886 MPASS(*p1 != NULL || *p2 != NULL);
896 cache_lock_all_buckets(void)
900 for (i = 0; i < numbucketlocks; i++)
901 mtx_lock(&bucketlocks[i]);
905 cache_unlock_all_buckets(void)
909 for (i = 0; i < numbucketlocks; i++)
910 mtx_unlock(&bucketlocks[i]);
914 cache_lock_all_vnodes(void)
918 for (i = 0; i < numvnodelocks; i++)
919 mtx_lock(&vnodelocks[i]);
923 cache_unlock_all_vnodes(void)
927 for (i = 0; i < numvnodelocks; i++)
928 mtx_unlock(&vnodelocks[i]);
932 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
935 cache_sort_vnodes(&vlp1, &vlp2);
938 if (!mtx_trylock(vlp1))
941 if (!mtx_trylock(vlp2)) {
951 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
954 MPASS(vlp1 != NULL || vlp2 != NULL);
964 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
967 MPASS(vlp1 != NULL || vlp2 != NULL);
976 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
978 struct nchstats snap;
980 if (req->oldptr == NULL)
981 return (SYSCTL_OUT(req, 0, sizeof(snap)));
984 snap.ncs_goodhits = counter_u64_fetch(numposhits);
985 snap.ncs_neghits = counter_u64_fetch(numneghits);
986 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
987 counter_u64_fetch(numnegzaps);
988 snap.ncs_miss = counter_u64_fetch(nummisszap) +
989 counter_u64_fetch(nummiss);
991 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
993 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
994 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
995 "VFS cache effectiveness statistics");
998 cache_recalc_neg_min(u_int val)
1001 neg_min = (ncsize * val) / 100;
1005 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1011 error = sysctl_handle_int(oidp, &val, 0, req);
1012 if (error != 0 || req->newptr == NULL)
1015 if (val == ncnegminpct)
1017 if (val < 0 || val > 99)
1020 cache_recalc_neg_min(val);
1024 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1025 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1026 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1030 * Grab an atomic snapshot of the name cache hash chain lengths
1032 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1033 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1034 "hash table stats");
1037 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1039 struct nchashhead *ncpp;
1040 struct namecache *ncp;
1041 int i, error, n_nchash, *cntbuf;
1044 n_nchash = nchash + 1; /* nchash is max index, not count */
1045 if (req->oldptr == NULL)
1046 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1047 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1048 cache_lock_all_buckets();
1049 if (n_nchash != nchash + 1) {
1050 cache_unlock_all_buckets();
1051 free(cntbuf, M_TEMP);
1054 /* Scan hash tables counting entries */
1055 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1056 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1058 cache_unlock_all_buckets();
1059 for (error = 0, i = 0; i < n_nchash; i++)
1060 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1062 free(cntbuf, M_TEMP);
1065 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1066 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1067 "nchash chain lengths");
1070 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1073 struct nchashhead *ncpp;
1074 struct namecache *ncp;
1076 int count, maxlength, used, pct;
1079 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1081 cache_lock_all_buckets();
1082 n_nchash = nchash + 1; /* nchash is max index, not count */
1086 /* Scan hash tables for applicable entries */
1087 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1089 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1094 if (maxlength < count)
1097 n_nchash = nchash + 1;
1098 cache_unlock_all_buckets();
1099 pct = (used * 100) / (n_nchash / 100);
1100 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1103 error = SYSCTL_OUT(req, &used, sizeof(used));
1106 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1109 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1114 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1115 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1116 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1120 * Negative entries management
1122 * Various workloads create plenty of negative entries and barely use them
1123 * afterwards. Moreover malicious users can keep performing bogus lookups
1124 * adding even more entries. For example "make tinderbox" as of writing this
1125 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1128 * As such, a rather aggressive eviction method is needed. The currently
1129 * employed method is a placeholder.
1131 * Entries are split over numneglists separate lists, each of which is further
1132 * split into hot and cold entries. Entries get promoted after getting a hit.
1133 * Eviction happens on addition of new entry.
1135 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1136 "Name cache negative entry statistics");
1138 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1139 "Number of negative cache entries");
1141 static COUNTER_U64_DEFINE_EARLY(neg_created);
1142 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1143 "Number of created negative entries");
1145 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1146 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1147 "Number of evicted negative entries");
1149 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1150 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1151 &neg_evict_skipped_empty,
1152 "Number of times evicting failed due to lack of entries");
1154 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1155 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1156 &neg_evict_skipped_missed,
1157 "Number of times evicting failed due to target entry disappearing");
1159 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1160 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1161 &neg_evict_skipped_contended,
1162 "Number of times evicting failed due to contention");
1164 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1165 "Number of cache hits (negative)");
1168 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1173 for (i = 0; i < numneglists; i++)
1174 out += neglists[i].nl_hotnum;
1176 return (SYSCTL_OUT(req, &out, sizeof(out)));
1178 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1179 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1180 "Number of hot negative entries");
1183 cache_neg_init(struct namecache *ncp)
1185 struct negstate *ns;
1187 ncp->nc_flag |= NCF_NEGATIVE;
1188 ns = NCP2NEGSTATE(ncp);
1191 counter_u64_add(neg_created, 1);
1194 #define CACHE_NEG_PROMOTION_THRESH 2
1197 cache_neg_hit_prep(struct namecache *ncp)
1199 struct negstate *ns;
1202 ns = NCP2NEGSTATE(ncp);
1203 n = atomic_load_char(&ns->neg_hit);
1205 if (n >= CACHE_NEG_PROMOTION_THRESH)
1207 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1210 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1214 * Nothing to do here but it is provided for completeness as some
1215 * cache_neg_hit_prep callers may end up returning without even
1216 * trying to promote.
1218 #define cache_neg_hit_abort(ncp) do { } while (0)
1221 cache_neg_hit_finish(struct namecache *ncp)
1224 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1225 counter_u64_add(numneghits, 1);
1229 * Move a negative entry to the hot list.
1232 cache_neg_promote_locked(struct namecache *ncp)
1235 struct negstate *ns;
1237 ns = NCP2NEGSTATE(ncp);
1238 nl = NCP2NEGLIST(ncp);
1239 mtx_assert(&nl->nl_lock, MA_OWNED);
1240 if ((ns->neg_flag & NEG_HOT) == 0) {
1241 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1242 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1244 ns->neg_flag |= NEG_HOT;
1249 * Move a hot negative entry to the cold list.
1252 cache_neg_demote_locked(struct namecache *ncp)
1255 struct negstate *ns;
1257 ns = NCP2NEGSTATE(ncp);
1258 nl = NCP2NEGLIST(ncp);
1259 mtx_assert(&nl->nl_lock, MA_OWNED);
1260 MPASS(ns->neg_flag & NEG_HOT);
1261 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1262 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1264 ns->neg_flag &= ~NEG_HOT;
1265 atomic_store_char(&ns->neg_hit, 0);
1269 * Move a negative entry to the hot list if it matches the lookup.
1271 * We have to take locks, but they may be contended and in the worst
1272 * case we may need to go off CPU. We don't want to spin within the
1273 * smr section and we can't block with it. Exiting the section means
1274 * the found entry could have been evicted. We are going to look it
1278 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1279 struct namecache *oncp, uint32_t hash)
1281 struct namecache *ncp;
1285 nl = NCP2NEGLIST(oncp);
1287 mtx_lock(&nl->nl_lock);
1289 * For hash iteration.
1294 * Avoid all surprises by only succeeding if we got the same entry and
1295 * bailing completely otherwise.
1296 * XXX There are no provisions to keep the vnode around, meaning we may
1297 * end up promoting a negative entry for a *new* vnode and returning
1298 * ENOENT on its account. This is the error we want to return anyway
1299 * and promotion is harmless.
1301 * In particular at this point there can be a new ncp which matches the
1302 * search but hashes to a different neglist.
1304 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1310 * No match to begin with.
1312 if (__predict_false(ncp == NULL)) {
1317 * The newly found entry may be something different...
1319 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1320 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1325 * ... and not even negative.
1327 nc_flag = atomic_load_char(&ncp->nc_flag);
1328 if ((nc_flag & NCF_NEGATIVE) == 0) {
1332 if (!cache_ncp_canuse(ncp)) {
1336 cache_neg_promote_locked(ncp);
1337 cache_neg_hit_finish(ncp);
1339 mtx_unlock(&nl->nl_lock);
1343 mtx_unlock(&nl->nl_lock);
1348 cache_neg_promote(struct namecache *ncp)
1352 nl = NCP2NEGLIST(ncp);
1353 mtx_lock(&nl->nl_lock);
1354 cache_neg_promote_locked(ncp);
1355 mtx_unlock(&nl->nl_lock);
1359 cache_neg_insert(struct namecache *ncp)
1363 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1364 cache_assert_bucket_locked(ncp);
1365 nl = NCP2NEGLIST(ncp);
1366 mtx_lock(&nl->nl_lock);
1367 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1368 mtx_unlock(&nl->nl_lock);
1369 atomic_add_long(&numneg, 1);
1373 cache_neg_remove(struct namecache *ncp)
1376 struct negstate *ns;
1378 cache_assert_bucket_locked(ncp);
1379 nl = NCP2NEGLIST(ncp);
1380 ns = NCP2NEGSTATE(ncp);
1381 mtx_lock(&nl->nl_lock);
1382 if ((ns->neg_flag & NEG_HOT) != 0) {
1383 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1386 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1388 mtx_unlock(&nl->nl_lock);
1389 atomic_subtract_long(&numneg, 1);
1392 static struct neglist *
1393 cache_neg_evict_select_list(void)
1398 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1399 nl = &neglists[c % numneglists];
1400 if (!mtx_trylock(&nl->nl_evict_lock)) {
1401 counter_u64_add(neg_evict_skipped_contended, 1);
1407 static struct namecache *
1408 cache_neg_evict_select_entry(struct neglist *nl)
1410 struct namecache *ncp, *lncp;
1411 struct negstate *ns, *lns;
1414 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1415 mtx_assert(&nl->nl_lock, MA_OWNED);
1416 ncp = TAILQ_FIRST(&nl->nl_list);
1420 lns = NCP2NEGSTATE(lncp);
1421 for (i = 1; i < 4; i++) {
1422 ncp = TAILQ_NEXT(ncp, nc_dst);
1425 ns = NCP2NEGSTATE(ncp);
1426 if (ns->neg_hit < lns->neg_hit) {
1435 cache_neg_evict(void)
1437 struct namecache *ncp, *ncp2;
1446 nl = cache_neg_evict_select_list();
1451 mtx_lock(&nl->nl_lock);
1452 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1454 cache_neg_demote_locked(ncp);
1456 ncp = cache_neg_evict_select_entry(nl);
1458 counter_u64_add(neg_evict_skipped_empty, 1);
1459 mtx_unlock(&nl->nl_lock);
1460 mtx_unlock(&nl->nl_evict_lock);
1463 nlen = ncp->nc_nlen;
1465 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1466 dvlp = VP2VNODELOCK(dvp);
1467 blp = HASH2BUCKETLOCK(hash);
1468 mtx_unlock(&nl->nl_lock);
1469 mtx_unlock(&nl->nl_evict_lock);
1473 * Note that since all locks were dropped above, the entry may be
1474 * gone or reallocated to be something else.
1476 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1477 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1478 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1482 counter_u64_add(neg_evict_skipped_missed, 1);
1486 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1487 MPASS(blp == NCP2BUCKETLOCK(ncp));
1488 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1490 cache_zap_locked(ncp);
1491 counter_u64_add(neg_evicted, 1);
1502 * Maybe evict a negative entry to create more room.
1504 * The ncnegfactor parameter limits what fraction of the total count
1505 * can comprise of negative entries. However, if the cache is just
1506 * warming up this leads to excessive evictions. As such, ncnegminpct
1507 * (recomputed to neg_min) dictates whether the above should be
1510 * Try evicting if the cache is close to full capacity regardless of
1511 * other considerations.
1514 cache_neg_evict_cond(u_long lnumcache)
1518 if (ncsize - 1000 < lnumcache)
1520 lnumneg = atomic_load_long(&numneg);
1521 if (lnumneg < neg_min)
1523 if (lnumneg * ncnegfactor < lnumcache)
1526 return (cache_neg_evict());
1530 * cache_zap_locked():
1532 * Removes a namecache entry from cache, whether it contains an actual
1533 * pointer to a vnode or if it is just a negative cache entry.
1536 cache_zap_locked(struct namecache *ncp)
1538 struct nchashhead *ncpp;
1539 struct vnode *dvp, *vp;
1544 if (!(ncp->nc_flag & NCF_NEGATIVE))
1545 cache_assert_vnode_locked(vp);
1546 cache_assert_vnode_locked(dvp);
1547 cache_assert_bucket_locked(ncp);
1549 cache_ncp_invalidate(ncp);
1551 ncpp = NCP2BUCKET(ncp);
1552 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1553 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1554 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1555 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1556 if (ncp == vp->v_cache_dd) {
1557 atomic_store_ptr(&vp->v_cache_dd, NULL);
1560 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1561 cache_neg_remove(ncp);
1563 if (ncp->nc_flag & NCF_ISDOTDOT) {
1564 if (ncp == dvp->v_cache_dd) {
1565 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1568 LIST_REMOVE(ncp, nc_src);
1569 if (LIST_EMPTY(&dvp->v_cache_src)) {
1570 ncp->nc_flag |= NCF_DVDROP;
1576 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1580 MPASS(ncp->nc_dvp == vp);
1581 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1582 cache_assert_vnode_locked(vp);
1584 blp = NCP2BUCKETLOCK(ncp);
1586 cache_zap_locked(ncp);
1591 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1594 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1597 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1598 cache_assert_vnode_locked(vp);
1600 if (ncp->nc_flag & NCF_NEGATIVE) {
1601 if (*vlpp != NULL) {
1605 cache_zap_negative_locked_vnode_kl(ncp, vp);
1609 pvlp = VP2VNODELOCK(vp);
1610 blp = NCP2BUCKETLOCK(ncp);
1611 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1612 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1614 if (*vlpp == vlp1 || *vlpp == vlp2) {
1618 if (*vlpp != NULL) {
1622 cache_sort_vnodes(&vlp1, &vlp2);
1627 if (!mtx_trylock(vlp1))
1633 cache_zap_locked(ncp);
1635 if (to_unlock != NULL)
1636 mtx_unlock(to_unlock);
1643 MPASS(*vlpp == NULL);
1649 * If trylocking failed we can get here. We know enough to take all needed locks
1650 * in the right order and re-lookup the entry.
1653 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1654 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1657 struct namecache *rncp;
1659 cache_assert_bucket_unlocked(ncp);
1661 cache_sort_vnodes(&dvlp, &vlp);
1662 cache_lock_vnodes(dvlp, vlp);
1664 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1665 if (rncp == ncp && rncp->nc_dvp == dvp &&
1666 rncp->nc_nlen == cnp->cn_namelen &&
1667 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1671 cache_zap_locked(rncp);
1673 cache_unlock_vnodes(dvlp, vlp);
1674 counter_u64_add(zap_bucket_relock_success, 1);
1679 cache_unlock_vnodes(dvlp, vlp);
1683 static int __noinline
1684 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1685 uint32_t hash, struct mtx *blp)
1687 struct mtx *dvlp, *vlp;
1690 cache_assert_bucket_locked(ncp);
1692 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1694 if (!(ncp->nc_flag & NCF_NEGATIVE))
1695 vlp = VP2VNODELOCK(ncp->nc_vp);
1696 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1697 cache_zap_locked(ncp);
1699 cache_unlock_vnodes(dvlp, vlp);
1705 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1708 static __noinline int
1709 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1711 struct namecache *ncp;
1713 struct mtx *dvlp, *dvlp2;
1717 if (cnp->cn_namelen == 2 &&
1718 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1719 dvlp = VP2VNODELOCK(dvp);
1723 ncp = dvp->v_cache_dd;
1728 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1731 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1732 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1734 MPASS(dvp->v_cache_dd == NULL);
1740 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1745 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1749 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1750 blp = HASH2BUCKETLOCK(hash);
1752 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1757 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1758 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1759 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1768 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1769 if (__predict_false(error != 0)) {
1773 counter_u64_add(numposzaps, 1);
1774 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1778 counter_u64_add(nummisszap, 1);
1779 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1783 static int __noinline
1784 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1785 struct timespec *tsp, int *ticksp)
1790 counter_u64_add(dothits, 1);
1791 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1798 * When we lookup "." we still can be asked to lock it
1801 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1802 if (ltype != VOP_ISLOCKED(*vpp)) {
1803 if (ltype == LK_EXCLUSIVE) {
1804 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1805 if (VN_IS_DOOMED((*vpp))) {
1806 /* forced unmount */
1812 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1817 static int __noinline
1818 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1819 struct timespec *tsp, int *ticksp)
1821 struct namecache_ts *ncp_ts;
1822 struct namecache *ncp;
1828 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1830 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1831 cache_remove_cnp(dvp, cnp);
1835 counter_u64_add(dotdothits, 1);
1837 dvlp = VP2VNODELOCK(dvp);
1839 ncp = dvp->v_cache_dd;
1841 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1845 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1846 if (ncp->nc_flag & NCF_NEGATIVE)
1853 goto negative_success;
1854 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1855 cache_out_ts(ncp, tsp, ticksp);
1856 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1857 NCF_DTS && tsp != NULL) {
1858 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1859 *tsp = ncp_ts->nc_dotdottime;
1863 ltype = VOP_ISLOCKED(dvp);
1865 vs = vget_prep(*vpp);
1867 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1868 vn_lock(dvp, ltype | LK_RETRY);
1869 if (VN_IS_DOOMED(dvp)) {
1881 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1882 if (cnp->cn_flags & ISLASTCN) {
1883 counter_u64_add(numnegzaps, 1);
1884 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1891 whiteout = (ncp->nc_flag & NCF_WHITE);
1892 cache_out_ts(ncp, tsp, ticksp);
1893 if (cache_neg_hit_prep(ncp))
1894 cache_neg_promote(ncp);
1896 cache_neg_hit_finish(ncp);
1899 cnp->cn_flags |= ISWHITEOUT;
1904 * Lookup a name in the name cache
1908 * - dvp: Parent directory in which to search.
1909 * - vpp: Return argument. Will contain desired vnode on cache hit.
1910 * - cnp: Parameters of the name search. The most interesting bits of
1911 * the cn_flags field have the following meanings:
1912 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1914 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1915 * - tsp: Return storage for cache timestamp. On a successful (positive
1916 * or negative) lookup, tsp will be filled with any timespec that
1917 * was stored when this cache entry was created. However, it will
1918 * be clear for "." entries.
1919 * - ticks: Return storage for alternate cache timestamp. On a successful
1920 * (positive or negative) lookup, it will contain the ticks value
1921 * that was current when the cache entry was created, unless cnp
1924 * Either both tsp and ticks have to be provided or neither of them.
1928 * - -1: A positive cache hit. vpp will contain the desired vnode.
1929 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1930 * to a forced unmount. vpp will not be modified. If the entry
1931 * is a whiteout, then the ISWHITEOUT flag will be set in
1933 * - 0: A cache miss. vpp will not be modified.
1937 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1938 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1939 * lock is not recursively acquired.
1941 static int __noinline
1942 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1943 struct timespec *tsp, int *ticksp)
1945 struct namecache *ncp;
1952 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1953 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1956 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1957 blp = HASH2BUCKETLOCK(hash);
1960 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1961 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1962 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1966 if (__predict_false(ncp == NULL)) {
1968 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
1969 counter_u64_add(nummiss, 1);
1973 if (ncp->nc_flag & NCF_NEGATIVE)
1974 goto negative_success;
1976 counter_u64_add(numposhits, 1);
1978 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1979 cache_out_ts(ncp, tsp, ticksp);
1981 vs = vget_prep(*vpp);
1983 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1991 * We don't get here with regular lookup apart from corner cases.
1993 if (__predict_true(cnp->cn_nameiop == CREATE)) {
1994 if (cnp->cn_flags & ISLASTCN) {
1995 counter_u64_add(numnegzaps, 1);
1996 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1997 if (__predict_false(error != 0)) {
2006 whiteout = (ncp->nc_flag & NCF_WHITE);
2007 cache_out_ts(ncp, tsp, ticksp);
2008 if (cache_neg_hit_prep(ncp))
2009 cache_neg_promote(ncp);
2011 cache_neg_hit_finish(ncp);
2014 cnp->cn_flags |= ISWHITEOUT;
2019 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2020 struct timespec *tsp, int *ticksp)
2022 struct namecache *ncp;
2026 bool whiteout, neg_promote;
2029 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2032 if (__predict_false(!doingcache)) {
2033 cnp->cn_flags &= ~MAKEENTRY;
2038 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2039 if (cnp->cn_namelen == 1)
2040 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2041 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2042 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2045 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2047 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2048 cache_remove_cnp(dvp, cnp);
2052 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2055 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2056 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2057 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2061 if (__predict_false(ncp == NULL)) {
2063 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2064 counter_u64_add(nummiss, 1);
2068 nc_flag = atomic_load_char(&ncp->nc_flag);
2069 if (nc_flag & NCF_NEGATIVE)
2070 goto negative_success;
2072 counter_u64_add(numposhits, 1);
2074 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2075 cache_out_ts(ncp, tsp, ticksp);
2077 if (!cache_ncp_canuse(ncp)) {
2082 vs = vget_prep_smr(*vpp);
2084 if (__predict_false(vs == VGET_NONE)) {
2088 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2095 if (cnp->cn_nameiop == CREATE) {
2096 if (cnp->cn_flags & ISLASTCN) {
2102 cache_out_ts(ncp, tsp, ticksp);
2103 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2104 neg_promote = cache_neg_hit_prep(ncp);
2105 if (!cache_ncp_canuse(ncp)) {
2106 cache_neg_hit_abort(ncp);
2112 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2115 cache_neg_hit_finish(ncp);
2119 cnp->cn_flags |= ISWHITEOUT;
2122 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2125 struct celockstate {
2129 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2130 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2133 cache_celockstate_init(struct celockstate *cel)
2136 bzero(cel, sizeof(*cel));
2140 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2143 struct mtx *vlp1, *vlp2;
2145 MPASS(cel->vlp[0] == NULL);
2146 MPASS(cel->vlp[1] == NULL);
2147 MPASS(cel->vlp[2] == NULL);
2149 MPASS(vp != NULL || dvp != NULL);
2151 vlp1 = VP2VNODELOCK(vp);
2152 vlp2 = VP2VNODELOCK(dvp);
2153 cache_sort_vnodes(&vlp1, &vlp2);
2164 cache_unlock_vnodes_cel(struct celockstate *cel)
2167 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2169 if (cel->vlp[0] != NULL)
2170 mtx_unlock(cel->vlp[0]);
2171 if (cel->vlp[1] != NULL)
2172 mtx_unlock(cel->vlp[1]);
2173 if (cel->vlp[2] != NULL)
2174 mtx_unlock(cel->vlp[2]);
2178 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2183 cache_assert_vlp_locked(cel->vlp[0]);
2184 cache_assert_vlp_locked(cel->vlp[1]);
2185 MPASS(cel->vlp[2] == NULL);
2188 vlp = VP2VNODELOCK(vp);
2191 if (vlp >= cel->vlp[1]) {
2194 if (mtx_trylock(vlp))
2196 cache_lock_vnodes_cel_3_failures++;
2197 cache_unlock_vnodes_cel(cel);
2198 if (vlp < cel->vlp[0]) {
2200 mtx_lock(cel->vlp[0]);
2201 mtx_lock(cel->vlp[1]);
2203 if (cel->vlp[0] != NULL)
2204 mtx_lock(cel->vlp[0]);
2206 mtx_lock(cel->vlp[1]);
2216 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2220 MPASS(cel->blp[0] == NULL);
2221 MPASS(cel->blp[1] == NULL);
2223 cache_sort_vnodes(&blp1, &blp2);
2234 cache_unlock_buckets_cel(struct celockstate *cel)
2237 if (cel->blp[0] != NULL)
2238 mtx_unlock(cel->blp[0]);
2239 mtx_unlock(cel->blp[1]);
2243 * Lock part of the cache affected by the insertion.
2245 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2246 * However, insertion can result in removal of an old entry. In this
2247 * case we have an additional vnode and bucketlock pair to lock.
2249 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2250 * preserving the locking order (smaller address first).
2253 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2256 struct namecache *ncp;
2257 struct mtx *blps[2];
2260 blps[0] = HASH2BUCKETLOCK(hash);
2263 cache_lock_vnodes_cel(cel, dvp, vp);
2264 if (vp == NULL || vp->v_type != VDIR)
2266 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2269 nc_flag = atomic_load_char(&ncp->nc_flag);
2270 if ((nc_flag & NCF_ISDOTDOT) == 0)
2272 MPASS(ncp->nc_dvp == vp);
2273 blps[1] = NCP2BUCKETLOCK(ncp);
2274 if ((nc_flag & NCF_NEGATIVE) != 0)
2276 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2279 * All vnodes got re-locked. Re-validate the state and if
2280 * nothing changed we are done. Otherwise restart.
2282 if (ncp == vp->v_cache_dd &&
2283 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2284 blps[1] == NCP2BUCKETLOCK(ncp) &&
2285 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2287 cache_unlock_vnodes_cel(cel);
2292 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2296 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2299 struct namecache *ncp;
2300 struct mtx *blps[2];
2303 blps[0] = HASH2BUCKETLOCK(hash);
2306 cache_lock_vnodes_cel(cel, dvp, vp);
2307 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2310 nc_flag = atomic_load_char(&ncp->nc_flag);
2311 if ((nc_flag & NCF_ISDOTDOT) == 0)
2313 MPASS(ncp->nc_dvp == dvp);
2314 blps[1] = NCP2BUCKETLOCK(ncp);
2315 if ((nc_flag & NCF_NEGATIVE) != 0)
2317 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2319 if (ncp == dvp->v_cache_dd &&
2320 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2321 blps[1] == NCP2BUCKETLOCK(ncp) &&
2322 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2324 cache_unlock_vnodes_cel(cel);
2329 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2333 cache_enter_unlock(struct celockstate *cel)
2336 cache_unlock_buckets_cel(cel);
2337 cache_unlock_vnodes_cel(cel);
2340 static void __noinline
2341 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2342 struct componentname *cnp)
2344 struct celockstate cel;
2345 struct namecache *ncp;
2349 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2351 len = cnp->cn_namelen;
2352 cache_celockstate_init(&cel);
2353 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2354 cache_enter_lock_dd(&cel, dvp, vp, hash);
2355 ncp = dvp->v_cache_dd;
2356 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2357 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2358 cache_zap_locked(ncp);
2362 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2363 cache_enter_unlock(&cel);
2369 * Add an entry to the cache.
2372 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2373 struct timespec *tsp, struct timespec *dtsp)
2375 struct celockstate cel;
2376 struct namecache *ncp, *n2, *ndd;
2377 struct namecache_ts *ncp_ts;
2378 struct nchashhead *ncpp;
2383 KASSERT(cnp->cn_namelen <= NAME_MAX,
2384 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2386 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2387 VNPASS(dvp->v_type != VNON, dvp);
2389 VNPASS(!VN_IS_DOOMED(vp), vp);
2390 VNPASS(vp->v_type != VNON, vp);
2392 if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
2394 ("%s: different vnodes for dot entry (%p; %p)\n", __func__,
2398 ("%s: same vnode for non-dot entry [%s] (%p)\n", __func__,
2399 cnp->cn_nameptr, dvp));
2403 if (__predict_false(!doingcache))
2408 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2409 if (cnp->cn_namelen == 1)
2411 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2412 cache_enter_dotdot_prep(dvp, vp, cnp);
2413 flag = NCF_ISDOTDOT;
2417 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2421 cache_celockstate_init(&cel);
2426 * Calculate the hash key and setup as much of the new
2427 * namecache entry as possible before acquiring the lock.
2429 ncp->nc_flag = flag | NCF_WIP;
2432 cache_neg_init(ncp);
2435 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2436 ncp_ts->nc_time = *tsp;
2437 ncp_ts->nc_ticks = ticks;
2438 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2440 ncp_ts->nc_dotdottime = *dtsp;
2441 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2444 len = ncp->nc_nlen = cnp->cn_namelen;
2445 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2446 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2447 ncp->nc_name[len] = '\0';
2448 cache_enter_lock(&cel, dvp, vp, hash);
2451 * See if this vnode or negative entry is already in the cache
2452 * with this name. This can happen with concurrent lookups of
2453 * the same path name.
2455 ncpp = NCHHASH(hash);
2456 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2457 if (n2->nc_dvp == dvp &&
2458 n2->nc_nlen == cnp->cn_namelen &&
2459 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2460 MPASS(cache_ncp_canuse(n2));
2461 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2463 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2464 __func__, NULL, vp, cnp->cn_nameptr));
2466 KASSERT(n2->nc_vp == vp,
2467 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2468 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2470 * Entries are supposed to be immutable unless in the
2471 * process of getting destroyed. Accommodating for
2472 * changing timestamps is possible but not worth it.
2473 * This should be harmless in terms of correctness, in
2474 * the worst case resulting in an earlier expiration.
2475 * Alternatively, the found entry can be replaced
2478 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2481 KASSERT((n2->nc_flag & NCF_TS) != 0,
2483 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2484 n2_ts->nc_time = ncp_ts->nc_time;
2485 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2487 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2488 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2492 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2494 goto out_unlock_free;
2498 if (flag == NCF_ISDOTDOT) {
2500 * See if we are trying to add .. entry, but some other lookup
2501 * has populated v_cache_dd pointer already.
2503 if (dvp->v_cache_dd != NULL)
2504 goto out_unlock_free;
2505 KASSERT(vp == NULL || vp->v_type == VDIR,
2506 ("wrong vnode type %p", vp));
2507 atomic_thread_fence_rel();
2508 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2512 if (flag != NCF_ISDOTDOT) {
2514 * For this case, the cache entry maps both the
2515 * directory name in it and the name ".." for the
2516 * directory's parent.
2518 if ((ndd = vp->v_cache_dd) != NULL) {
2519 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2520 cache_zap_locked(ndd);
2524 atomic_thread_fence_rel();
2525 atomic_store_ptr(&vp->v_cache_dd, ncp);
2526 } else if (vp->v_type != VDIR) {
2527 if (vp->v_cache_dd != NULL) {
2528 atomic_store_ptr(&vp->v_cache_dd, NULL);
2533 if (flag != NCF_ISDOTDOT) {
2534 if (LIST_EMPTY(&dvp->v_cache_src)) {
2535 cache_hold_vnode(dvp);
2537 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2541 * If the entry is "negative", we place it into the
2542 * "negative" cache queue, otherwise, we place it into the
2543 * destination vnode's cache entries queue.
2546 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2547 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2550 if (cnp->cn_flags & ISWHITEOUT)
2551 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2552 cache_neg_insert(ncp);
2553 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2558 * Insert the new namecache entry into the appropriate chain
2559 * within the cache entries table.
2561 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2563 atomic_thread_fence_rel();
2565 * Mark the entry as fully constructed.
2566 * It is immutable past this point until its removal.
2568 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2570 cache_enter_unlock(&cel);
2575 cache_enter_unlock(&cel);
2581 * A variant of the above accepting flags.
2583 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2585 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2586 * happens to match and it is doing it in an inefficient manner. It was added
2587 * to accommodate NFS which runs into a case where the target for a given name
2588 * may change from under it. Note this does nothing to solve the following
2589 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2590 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2593 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2594 struct timespec *tsp, struct timespec *dtsp, int flags)
2597 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2599 if (flags & VFS_CACHE_DROPOLD)
2600 cache_remove_cnp(dvp, cnp);
2601 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2605 cache_roundup_2(u_int val)
2609 for (res = 1; res <= val; res <<= 1)
2615 static struct nchashhead *
2616 nchinittbl(u_long elements, u_long *hashmask)
2618 struct nchashhead *hashtbl;
2621 hashsize = cache_roundup_2(elements) / 2;
2623 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2624 for (i = 0; i < hashsize; i++)
2625 CK_SLIST_INIT(&hashtbl[i]);
2626 *hashmask = hashsize - 1;
2631 ncfreetbl(struct nchashhead *hashtbl)
2634 free(hashtbl, M_VFSCACHE);
2638 * Name cache initialization, from vfs_init() when we are booting
2641 nchinit(void *dummy __unused)
2645 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2646 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2647 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2648 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2649 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2650 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2651 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2652 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2654 VFS_SMR_ZONE_SET(cache_zone_small);
2655 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2656 VFS_SMR_ZONE_SET(cache_zone_large);
2657 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2659 ncsize = desiredvnodes * ncsizefactor;
2660 cache_recalc_neg_min(ncnegminpct);
2661 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2662 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2663 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2665 if (ncbuckethash > nchash)
2666 ncbuckethash = nchash;
2667 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2669 for (i = 0; i < numbucketlocks; i++)
2670 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2671 ncvnodehash = ncbuckethash;
2672 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2674 for (i = 0; i < numvnodelocks; i++)
2675 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2677 for (i = 0; i < numneglists; i++) {
2678 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2679 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2680 TAILQ_INIT(&neglists[i].nl_list);
2681 TAILQ_INIT(&neglists[i].nl_hotlist);
2684 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2687 cache_vnode_init(struct vnode *vp)
2690 LIST_INIT(&vp->v_cache_src);
2691 TAILQ_INIT(&vp->v_cache_dst);
2692 vp->v_cache_dd = NULL;
2697 * Induce transient cache misses for lockless operation in cache_lookup() by
2698 * using a temporary hash table.
2700 * This will force a fs lookup.
2702 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2703 * to observe all CPUs not performing the lookup.
2706 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2709 MPASS(temphash < nchash);
2711 * Change the size. The new size is smaller and can safely be used
2712 * against the existing table. All lookups which now hash wrong will
2713 * result in a cache miss, which all callers are supposed to know how
2716 atomic_store_long(&nchash, temphash);
2717 atomic_thread_fence_rel();
2718 vfs_smr_synchronize();
2720 * At this point everyone sees the updated hash value, but they still
2721 * see the old table.
2723 atomic_store_ptr(&nchashtbl, temptbl);
2724 atomic_thread_fence_rel();
2725 vfs_smr_synchronize();
2727 * At this point everyone sees the updated table pointer and size pair.
2732 * Set the new hash table.
2734 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2735 * lockless operation in cache_lookup().
2738 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2741 MPASS(nchash < new_hash);
2743 * Change the pointer first. This wont result in out of bounds access
2744 * since the temporary table is guaranteed to be smaller.
2746 atomic_store_ptr(&nchashtbl, new_tbl);
2747 atomic_thread_fence_rel();
2748 vfs_smr_synchronize();
2750 * At this point everyone sees the updated pointer value, but they
2751 * still see the old size.
2753 atomic_store_long(&nchash, new_hash);
2754 atomic_thread_fence_rel();
2755 vfs_smr_synchronize();
2757 * At this point everyone sees the updated table pointer and size pair.
2762 cache_changesize(u_long newmaxvnodes)
2764 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2765 u_long new_nchash, old_nchash, temphash;
2766 struct namecache *ncp;
2771 newncsize = newmaxvnodes * ncsizefactor;
2772 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2773 if (newmaxvnodes < numbucketlocks)
2774 newmaxvnodes = numbucketlocks;
2776 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2777 /* If same hash table size, nothing to do */
2778 if (nchash == new_nchash) {
2779 ncfreetbl(new_nchashtbl);
2783 temptbl = nchinittbl(1, &temphash);
2786 * Move everything from the old hash table to the new table.
2787 * None of the namecache entries in the table can be removed
2788 * because to do so, they have to be removed from the hash table.
2790 cache_lock_all_vnodes();
2791 cache_lock_all_buckets();
2792 old_nchashtbl = nchashtbl;
2793 old_nchash = nchash;
2794 cache_changesize_set_temp(temptbl, temphash);
2795 for (i = 0; i <= old_nchash; i++) {
2796 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2797 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2799 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2800 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2804 cache_recalc_neg_min(ncnegminpct);
2805 cache_changesize_set_new(new_nchashtbl, new_nchash);
2806 cache_unlock_all_buckets();
2807 cache_unlock_all_vnodes();
2808 ncfreetbl(old_nchashtbl);
2813 * Remove all entries from and to a particular vnode.
2816 cache_purge_impl(struct vnode *vp)
2818 struct cache_freebatch batch;
2819 struct namecache *ncp;
2820 struct mtx *vlp, *vlp2;
2823 vlp = VP2VNODELOCK(vp);
2827 while (!LIST_EMPTY(&vp->v_cache_src)) {
2828 ncp = LIST_FIRST(&vp->v_cache_src);
2829 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2831 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2833 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2834 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2835 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2837 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2839 ncp = vp->v_cache_dd;
2841 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2842 ("lost dotdot link"));
2843 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2845 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2847 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2851 cache_free_batch(&batch);
2855 * Opportunistic check to see if there is anything to do.
2858 cache_has_entries(struct vnode *vp)
2861 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2862 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2868 cache_purge(struct vnode *vp)
2871 SDT_PROBE1(vfs, namecache, purge, done, vp);
2872 if (!cache_has_entries(vp))
2874 cache_purge_impl(vp);
2878 * Only to be used by vgone.
2881 cache_purge_vgone(struct vnode *vp)
2885 VNPASS(VN_IS_DOOMED(vp), vp);
2886 if (cache_has_entries(vp)) {
2887 cache_purge_impl(vp);
2892 * Serialize against a potential thread doing cache_purge.
2894 vlp = VP2VNODELOCK(vp);
2895 mtx_wait_unlocked(vlp);
2896 if (cache_has_entries(vp)) {
2897 cache_purge_impl(vp);
2904 * Remove all negative entries for a particular directory vnode.
2907 cache_purge_negative(struct vnode *vp)
2909 struct cache_freebatch batch;
2910 struct namecache *ncp, *nnp;
2913 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2914 if (LIST_EMPTY(&vp->v_cache_src))
2917 vlp = VP2VNODELOCK(vp);
2919 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2920 if (!(ncp->nc_flag & NCF_NEGATIVE))
2922 cache_zap_negative_locked_vnode_kl(ncp, vp);
2923 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2926 cache_free_batch(&batch);
2930 * Entry points for modifying VOP operations.
2933 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2934 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2937 ASSERT_VOP_IN_SEQC(fdvp);
2938 ASSERT_VOP_IN_SEQC(fvp);
2939 ASSERT_VOP_IN_SEQC(tdvp);
2941 ASSERT_VOP_IN_SEQC(tvp);
2946 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2947 ("%s: lingering negative entry", __func__));
2949 cache_remove_cnp(tdvp, tcnp);
2955 * Historically renaming was always purging all revelang entries,
2956 * but that's quite wasteful. In particular turns out that in many cases
2957 * the target file is immediately accessed after rename, inducing a cache
2960 * Recode this to reduce relocking and reuse the existing entry (if any)
2961 * instead of just removing it above and allocating a new one here.
2963 cache_enter(tdvp, fvp, tcnp);
2967 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2970 ASSERT_VOP_IN_SEQC(dvp);
2971 ASSERT_VOP_IN_SEQC(vp);
2977 * Validate that if an entry exists it matches.
2980 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2982 struct namecache *ncp;
2986 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2987 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2989 blp = HASH2BUCKETLOCK(hash);
2991 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2992 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2993 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2994 if (ncp->nc_vp != vp)
2995 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
2996 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3004 * Flush all entries referencing a particular filesystem.
3007 cache_purgevfs(struct mount *mp)
3009 struct vnode *vp, *mvp;
3010 size_t visited, purged;
3012 visited = purged = 0;
3014 * Somewhat wasteful iteration over all vnodes. Would be better to
3015 * support filtering and avoid the interlock to begin with.
3017 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3019 if (!cache_has_entries(vp)) {
3030 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3034 * Perform canonical checks and cache lookup and pass on to filesystem
3035 * through the vop_cachedlookup only if needed.
3039 vfs_cache_lookup(struct vop_lookup_args *ap)
3043 struct vnode **vpp = ap->a_vpp;
3044 struct componentname *cnp = ap->a_cnp;
3045 int flags = cnp->cn_flags;
3050 if (dvp->v_type != VDIR)
3053 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3054 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3057 error = vn_dir_check_exec(dvp, cnp);
3061 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3063 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3069 /* Implementation of the getcwd syscall. */
3071 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3077 buflen = uap->buflen;
3078 if (__predict_false(buflen < 2))
3080 if (buflen > MAXPATHLEN)
3081 buflen = MAXPATHLEN;
3083 buf = uma_zalloc(namei_zone, M_WAITOK);
3084 error = vn_getcwd(buf, &retbuf, &buflen);
3086 error = copyout(retbuf, uap->buf, buflen);
3087 uma_zfree(namei_zone, buf);
3092 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3098 pwd = pwd_get_smr();
3099 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3101 VFS_SMR_ASSERT_NOT_ENTERED();
3103 pwd = pwd_hold(curthread);
3104 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3110 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3117 * Canonicalize a path by walking it forward and back.
3120 * - Nothing guarantees the integrity of the entire chain. Consider the case
3121 * where the path "foo/bar/baz/qux" is passed, but "bar" is moved out of
3122 * "foo" into "quux" during the backwards walk. The result will be
3123 * "quux/bar/baz/qux", which could not have been obtained by an incremental
3124 * walk in userspace. Moreover, the path we return is inaccessible if the
3125 * calling thread lacks permission to traverse "quux".
3128 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3129 size_t size, int flags, enum uio_seg pathseg)
3131 struct nameidata nd;
3132 char *retbuf, *freebuf;
3137 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | WANTPARENT | AUDITVNODE1,
3138 pathseg, path, fd, &cap_fstat_rights);
3139 if ((error = namei(&nd)) != 0)
3141 error = vn_fullpath_hardlink(nd.ni_vp, nd.ni_dvp, nd.ni_cnd.cn_nameptr,
3142 nd.ni_cnd.cn_namelen, &retbuf, &freebuf, &size);
3144 error = copyout(retbuf, buf, size);
3145 free(freebuf, M_TEMP);
3152 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3155 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3156 uap->flags, UIO_USERSPACE));
3160 * Retrieve the full filesystem path that correspond to a vnode from the name
3161 * cache (if available)
3164 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3171 if (__predict_false(vp == NULL))
3174 buflen = MAXPATHLEN;
3175 buf = malloc(buflen, M_TEMP, M_WAITOK);
3177 pwd = pwd_get_smr();
3178 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3179 VFS_SMR_ASSERT_NOT_ENTERED();
3181 pwd = pwd_hold(curthread);
3182 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3193 * This function is similar to vn_fullpath, but it attempts to lookup the
3194 * pathname relative to the global root mount point. This is required for the
3195 * auditing sub-system, as audited pathnames must be absolute, relative to the
3196 * global root mount point.
3199 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3205 if (__predict_false(vp == NULL))
3207 buflen = MAXPATHLEN;
3208 buf = malloc(buflen, M_TEMP, M_WAITOK);
3210 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3211 VFS_SMR_ASSERT_NOT_ENTERED();
3213 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3222 static struct namecache *
3223 vn_dd_from_dst(struct vnode *vp)
3225 struct namecache *ncp;
3227 cache_assert_vnode_locked(vp);
3228 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3229 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3236 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3239 struct namecache *ncp;
3243 vlp = VP2VNODELOCK(*vp);
3245 ncp = (*vp)->v_cache_dd;
3246 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3247 KASSERT(ncp == vn_dd_from_dst(*vp),
3248 ("%s: mismatch for dd entry (%p != %p)", __func__,
3249 ncp, vn_dd_from_dst(*vp)));
3251 ncp = vn_dd_from_dst(*vp);
3254 if (*buflen < ncp->nc_nlen) {
3257 counter_u64_add(numfullpathfail4, 1);
3259 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3263 *buflen -= ncp->nc_nlen;
3264 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3265 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3274 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3277 vn_lock(*vp, LK_SHARED | LK_RETRY);
3278 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3281 counter_u64_add(numfullpathfail2, 1);
3282 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3287 if (VN_IS_DOOMED(dvp)) {
3288 /* forced unmount */
3291 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3295 * *vp has its use count incremented still.
3302 * Resolve a directory to a pathname.
3304 * The name of the directory can always be found in the namecache or fetched
3305 * from the filesystem. There is also guaranteed to be only one parent, meaning
3306 * we can just follow vnodes up until we find the root.
3308 * The vnode must be referenced.
3311 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3312 size_t *len, size_t addend)
3314 #ifdef KDTRACE_HOOKS
3315 struct vnode *startvp = vp;
3320 bool slash_prefixed;
3322 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3323 VNPASS(vp->v_usecount > 0, vp);
3327 slash_prefixed = true;
3332 slash_prefixed = false;
3337 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3338 counter_u64_add(numfullpathcalls, 1);
3339 while (vp != rdir && vp != rootvnode) {
3341 * The vp vnode must be already fully constructed,
3342 * since it is either found in namecache or obtained
3343 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3344 * without obtaining the vnode lock.
3346 if ((vp->v_vflag & VV_ROOT) != 0) {
3347 vn_lock(vp, LK_RETRY | LK_SHARED);
3350 * With the vnode locked, check for races with
3351 * unmount, forced or not. Note that we
3352 * already verified that vp is not equal to
3353 * the root vnode, which means that
3354 * mnt_vnodecovered can be NULL only for the
3357 if (VN_IS_DOOMED(vp) ||
3358 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3359 vp1->v_mountedhere != vp->v_mount) {
3362 SDT_PROBE3(vfs, namecache, fullpath, return,
3372 if (vp->v_type != VDIR) {
3374 counter_u64_add(numfullpathfail1, 1);
3376 SDT_PROBE3(vfs, namecache, fullpath, return,
3380 error = vn_vptocnp(&vp, buf, &buflen);
3386 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3390 buf[--buflen] = '/';
3391 slash_prefixed = true;
3395 if (!slash_prefixed) {
3398 counter_u64_add(numfullpathfail4, 1);
3399 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3403 buf[--buflen] = '/';
3405 counter_u64_add(numfullpathfound, 1);
3408 *retbuf = buf + buflen;
3409 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3416 * Resolve an arbitrary vnode to a pathname.
3419 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3420 * resolve to a different path than the one used to find it
3421 * - namecache is not mandatory, meaning names are not guaranteed to be added
3422 * (in which case resolving fails)
3424 static void __inline
3425 cache_rev_failed_impl(int *reason, int line)
3430 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3433 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3434 char **retbuf, size_t *buflen, size_t addend)
3436 #ifdef KDTRACE_HOOKS
3437 struct vnode *startvp = vp;
3441 struct namecache *ncp;
3445 #ifdef KDTRACE_HOOKS
3448 seqc_t vp_seqc, tvp_seqc;
3451 VFS_SMR_ASSERT_ENTERED();
3453 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3458 orig_buflen = *buflen;
3461 MPASS(*buflen >= 2);
3463 buf[*buflen] = '\0';
3466 if (vp == rdir || vp == rootvnode) {
3474 #ifdef KDTRACE_HOOKS
3478 ncp = NULL; /* for sdt probe down below */
3479 vp_seqc = vn_seqc_read_any(vp);
3480 if (seqc_in_modify(vp_seqc)) {
3481 cache_rev_failed(&reason);
3486 #ifdef KDTRACE_HOOKS
3489 if ((vp->v_vflag & VV_ROOT) != 0) {
3490 mp = atomic_load_ptr(&vp->v_mount);
3492 cache_rev_failed(&reason);
3495 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3496 tvp_seqc = vn_seqc_read_any(tvp);
3497 if (seqc_in_modify(tvp_seqc)) {
3498 cache_rev_failed(&reason);
3501 if (!vn_seqc_consistent(vp, vp_seqc)) {
3502 cache_rev_failed(&reason);
3509 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3511 cache_rev_failed(&reason);
3514 nc_flag = atomic_load_char(&ncp->nc_flag);
3515 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3516 cache_rev_failed(&reason);
3519 if (ncp->nc_nlen >= *buflen) {
3520 cache_rev_failed(&reason);
3524 *buflen -= ncp->nc_nlen;
3525 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3529 tvp_seqc = vn_seqc_read_any(tvp);
3530 if (seqc_in_modify(tvp_seqc)) {
3531 cache_rev_failed(&reason);
3534 if (!vn_seqc_consistent(vp, vp_seqc)) {
3535 cache_rev_failed(&reason);
3539 * Acquire fence provided by vn_seqc_read_any above.
3541 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3542 cache_rev_failed(&reason);
3545 if (!cache_ncp_canuse(ncp)) {
3546 cache_rev_failed(&reason);
3551 if (vp == rdir || vp == rootvnode)
3556 *retbuf = buf + *buflen;
3557 *buflen = orig_buflen - *buflen + addend;
3558 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3562 *buflen = orig_buflen;
3563 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3569 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3572 size_t orig_buflen, addend;
3578 orig_buflen = *buflen;
3582 if (vp->v_type != VDIR) {
3584 buf[*buflen] = '\0';
3585 error = vn_vptocnp(&vp, buf, buflen);
3594 addend = orig_buflen - *buflen;
3597 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3601 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3603 * Since the namecache does not track hardlinks, the caller is expected to
3604 * first look up the target vnode with WANTPARENT flag passed to namei to get
3607 * Then we have 2 cases:
3608 * - if the found vnode is a directory, the path can be constructed just by
3609 * following names up the chain
3610 * - otherwise we populate the buffer with the saved name and start resolving
3614 vn_fullpath_hardlink(struct vnode *vp, struct vnode *dvp,
3615 const char *hrdl_name, size_t hrdl_name_length,
3616 char **retbuf, char **freebuf, size_t *buflen)
3626 if (*buflen > MAXPATHLEN)
3627 *buflen = MAXPATHLEN;
3629 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3634 * Check for VBAD to work around the vp_crossmp bug in lookup().
3636 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3637 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3638 * If the type is VDIR (like in this very case) we can skip looking
3639 * at ni_dvp in the first place. However, since vnodes get passed here
3640 * unlocked the target may transition to doomed state (type == VBAD)
3641 * before we get to evaluate the condition. If this happens, we will
3642 * populate part of the buffer and descend to vn_fullpath_dir with
3643 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3645 * This should be atomic_load(&vp->v_type) but it is illegal to take
3646 * an address of a bit field, even if said field is sized to char.
3647 * Work around the problem by reading the value into a full-sized enum
3648 * and then re-reading it with atomic_load which will still prevent
3649 * the compiler from re-reading down the road.
3652 type = atomic_load_int(&type);
3658 addend = hrdl_name_length + 2;
3659 if (*buflen < addend) {
3664 tmpbuf = buf + *buflen;
3666 memcpy(&tmpbuf[1], hrdl_name, hrdl_name_length);
3667 tmpbuf[addend - 1] = '\0';
3672 pwd = pwd_get_smr();
3673 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3675 VFS_SMR_ASSERT_NOT_ENTERED();
3677 pwd = pwd_hold(curthread);
3679 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3695 vn_dir_dd_ino(struct vnode *vp)
3697 struct namecache *ncp;
3702 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3703 vlp = VP2VNODELOCK(vp);
3705 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3706 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3709 vs = vget_prep(ddvp);
3711 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3720 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3722 struct namecache *ncp;
3726 vlp = VP2VNODELOCK(vp);
3728 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3729 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3735 l = min(ncp->nc_nlen, buflen - 1);
3736 memcpy(buf, ncp->nc_name, l);
3743 * This function updates path string to vnode's full global path
3744 * and checks the size of the new path string against the pathlen argument.
3746 * Requires a locked, referenced vnode.
3747 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3749 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3750 * because it falls back to the ".." lookup if the namecache lookup fails.
3753 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3756 struct nameidata nd;
3761 ASSERT_VOP_ELOCKED(vp, __func__);
3763 /* Construct global filesystem path from vp. */
3765 error = vn_fullpath_global(vp, &rpath, &fbuf);
3772 if (strlen(rpath) >= pathlen) {
3774 error = ENAMETOOLONG;
3779 * Re-lookup the vnode by path to detect a possible rename.
3780 * As a side effect, the vnode is relocked.
3781 * If vnode was renamed, return ENOENT.
3783 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3793 strcpy(path, rpath);
3806 db_print_vpath(struct vnode *vp)
3809 while (vp != NULL) {
3810 db_printf("%p: ", vp);
3811 if (vp == rootvnode) {
3815 if (vp->v_vflag & VV_ROOT) {
3816 db_printf("<mount point>");
3817 vp = vp->v_mount->mnt_vnodecovered;
3819 struct namecache *ncp;
3823 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3826 for (i = 0; i < ncp->nc_nlen; i++)
3827 db_printf("%c", *ncn++);
3840 DB_SHOW_COMMAND(vpath, db_show_vpath)
3845 db_printf("usage: show vpath <struct vnode *>\n");
3849 vp = (struct vnode *)addr;
3855 static int cache_fast_lookup = 1;
3857 #define CACHE_FPL_FAILED -2020
3860 cache_fast_lookup_enabled_recalc(void)
3866 mac_on = mac_vnode_check_lookup_enabled();
3867 mac_on |= mac_vnode_check_readlink_enabled();
3872 lookup_flag = atomic_load_int(&cache_fast_lookup);
3873 if (lookup_flag && !mac_on) {
3874 atomic_store_char(&cache_fast_lookup_enabled, true);
3876 atomic_store_char(&cache_fast_lookup_enabled, false);
3881 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
3885 old = atomic_load_int(&cache_fast_lookup);
3886 error = sysctl_handle_int(oidp, arg1, arg2, req);
3887 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
3888 cache_fast_lookup_enabled_recalc();
3891 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
3892 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
3895 * Components of nameidata (or objects it can point to) which may
3896 * need restoring in case fast path lookup fails.
3898 struct nameidata_outer {
3903 struct nameidata_saved {
3911 struct cache_fpl_debug {
3917 struct nameidata *ndp;
3918 struct componentname *cnp;
3925 struct nameidata_saved snd;
3926 struct nameidata_outer snd_outer;
3928 enum cache_fpl_status status:8;
3933 struct cache_fpl_debug debug;
3937 static bool cache_fplookup_mp_supported(struct mount *mp);
3938 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
3939 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
3940 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
3941 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
3942 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
3943 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
3944 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
3945 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
3946 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
3949 cache_fpl_cleanup_cnp(struct componentname *cnp)
3952 uma_zfree(namei_zone, cnp->cn_pnbuf);
3953 cnp->cn_pnbuf = NULL;
3954 cnp->cn_nameptr = NULL;
3957 static struct vnode *
3958 cache_fpl_handle_root(struct cache_fpl *fpl)
3960 struct nameidata *ndp;
3961 struct componentname *cnp;
3966 MPASS(*(cnp->cn_nameptr) == '/');
3968 cache_fpl_pathlen_dec(fpl);
3970 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
3973 cache_fpl_pathlen_dec(fpl);
3974 } while (*(cnp->cn_nameptr) == '/');
3977 return (ndp->ni_rootdir);
3981 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
3984 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
3985 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
3989 cache_fpl_checkpoint(struct cache_fpl *fpl)
3993 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3994 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
3999 cache_fpl_restore_partial(struct cache_fpl *fpl)
4002 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4004 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4009 cache_fpl_restore_abort(struct cache_fpl *fpl)
4012 cache_fpl_restore_partial(fpl);
4014 * It is 0 on entry by API contract.
4016 fpl->ndp->ni_resflags = 0;
4017 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4018 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4022 #define cache_fpl_smr_assert_entered(fpl) ({ \
4023 struct cache_fpl *_fpl = (fpl); \
4024 MPASS(_fpl->in_smr == true); \
4025 VFS_SMR_ASSERT_ENTERED(); \
4027 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4028 struct cache_fpl *_fpl = (fpl); \
4029 MPASS(_fpl->in_smr == false); \
4030 VFS_SMR_ASSERT_NOT_ENTERED(); \
4033 cache_fpl_assert_status(struct cache_fpl *fpl)
4036 switch (fpl->status) {
4037 case CACHE_FPL_STATUS_UNSET:
4038 __assert_unreachable();
4040 case CACHE_FPL_STATUS_DESTROYED:
4041 case CACHE_FPL_STATUS_ABORTED:
4042 case CACHE_FPL_STATUS_PARTIAL:
4043 case CACHE_FPL_STATUS_HANDLED:
4048 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4049 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4050 #define cache_fpl_assert_status(fpl) do { } while (0)
4053 #define cache_fpl_smr_enter_initial(fpl) ({ \
4054 struct cache_fpl *_fpl = (fpl); \
4056 _fpl->in_smr = true; \
4059 #define cache_fpl_smr_enter(fpl) ({ \
4060 struct cache_fpl *_fpl = (fpl); \
4061 MPASS(_fpl->in_smr == false); \
4063 _fpl->in_smr = true; \
4066 #define cache_fpl_smr_exit(fpl) ({ \
4067 struct cache_fpl *_fpl = (fpl); \
4068 MPASS(_fpl->in_smr == true); \
4070 _fpl->in_smr = false; \
4074 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4077 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4078 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4079 ("%s: converting to abort from %d at %d, set at %d\n",
4080 __func__, fpl->status, line, fpl->line));
4082 cache_fpl_smr_assert_not_entered(fpl);
4083 fpl->status = CACHE_FPL_STATUS_ABORTED;
4085 return (CACHE_FPL_FAILED);
4088 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4090 static int __noinline
4091 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4093 struct nameidata *ndp;
4094 struct componentname *cnp;
4099 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4100 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4101 ("%s: converting to abort from %d at %d, set at %d\n",
4102 __func__, fpl->status, line, fpl->line));
4104 fpl->status = CACHE_FPL_STATUS_ABORTED;
4107 cache_fpl_smr_exit(fpl);
4108 cache_fpl_restore_abort(fpl);
4110 * Resolving symlinks overwrites data passed by the caller.
4113 if (ndp->ni_loopcnt > 0) {
4114 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4115 cache_fpl_cleanup_cnp(cnp);
4117 return (CACHE_FPL_FAILED);
4120 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4122 static int __noinline
4123 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4126 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4127 ("%s: setting to partial at %d, but already set to %d at %d\n",
4128 __func__, line, fpl->status, fpl->line));
4129 cache_fpl_smr_assert_entered(fpl);
4130 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4132 return (cache_fplookup_partial_setup(fpl));
4135 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4138 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4141 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4142 ("%s: setting to handled at %d, but already set to %d at %d\n",
4143 __func__, line, fpl->status, fpl->line));
4144 cache_fpl_smr_assert_not_entered(fpl);
4145 fpl->status = CACHE_FPL_STATUS_HANDLED;
4150 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4153 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4156 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4157 ("%s: setting to handled at %d, but already set to %d at %d\n",
4158 __func__, line, fpl->status, fpl->line));
4160 MPASS(error != CACHE_FPL_FAILED);
4161 cache_fpl_smr_assert_not_entered(fpl);
4162 fpl->status = CACHE_FPL_STATUS_HANDLED;
4169 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4172 cache_fpl_terminated(struct cache_fpl *fpl)
4175 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4178 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4179 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4180 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | SAVESTART | WILLBEDIR | \
4181 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | OPENREAD | \
4182 OPENWRITE | WANTIOCTLCAPS)
4184 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4185 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4187 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4188 "supported and internal flags overlap");
4191 cache_fpl_islastcn(struct nameidata *ndp)
4194 return (*ndp->ni_next == 0);
4198 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4201 MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4202 return (*(fpl->nulchar - 1) == '/');
4206 cache_fpl_isdotdot(struct componentname *cnp)
4209 if (cnp->cn_namelen == 2 &&
4210 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4216 cache_can_fplookup(struct cache_fpl *fpl)
4218 struct nameidata *ndp;
4219 struct componentname *cnp;
4226 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4227 cache_fpl_aborted_early(fpl);
4230 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4231 cache_fpl_aborted_early(fpl);
4234 if (IN_CAPABILITY_MODE(td)) {
4235 cache_fpl_aborted_early(fpl);
4238 if (AUDITING_TD(td)) {
4239 cache_fpl_aborted_early(fpl);
4242 if (ndp->ni_startdir != NULL) {
4243 cache_fpl_aborted_early(fpl);
4249 static int __noinline
4250 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4252 struct nameidata *ndp;
4253 struct componentname *cnp;
4260 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4261 if (__predict_false(error != 0)) {
4262 return (cache_fpl_aborted(fpl));
4264 fpl->fsearch = fsearch;
4265 if ((*vpp)->v_type != VDIR) {
4266 if (!((cnp->cn_flags & EMPTYPATH) != 0 && cnp->cn_pnbuf[0] == '\0')) {
4267 cache_fpl_smr_exit(fpl);
4268 return (cache_fpl_handled_error(fpl, ENOTDIR));
4274 static int __noinline
4275 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4278 struct componentname *cnp;
4284 cache_fpl_smr_exit(fpl);
4285 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4286 return (cache_fpl_handled_error(fpl, ENOENT));
4288 return (cache_fpl_aborted(fpl));
4292 * The target vnode is not supported, prepare for the slow path to take over.
4294 static int __noinline
4295 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4297 struct nameidata *ndp;
4298 struct componentname *cnp;
4308 dvp_seqc = fpl->dvp_seqc;
4310 if (!pwd_hold_smr(pwd)) {
4311 return (cache_fpl_aborted(fpl));
4315 * Note that seqc is checked before the vnode is locked, so by
4316 * the time regular lookup gets to it it may have moved.
4318 * Ultimately this does not affect correctness, any lookup errors
4319 * are userspace racing with itself. It is guaranteed that any
4320 * path which ultimately gets found could also have been found
4321 * by regular lookup going all the way in absence of concurrent
4324 dvs = vget_prep_smr(dvp);
4325 cache_fpl_smr_exit(fpl);
4326 if (__predict_false(dvs == VGET_NONE)) {
4328 return (cache_fpl_aborted(fpl));
4331 vget_finish_ref(dvp, dvs);
4332 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4335 return (cache_fpl_aborted(fpl));
4338 cache_fpl_restore_partial(fpl);
4340 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4341 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4342 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4346 ndp->ni_startdir = dvp;
4347 cnp->cn_flags |= MAKEENTRY;
4348 if (cache_fpl_islastcn(ndp))
4349 cnp->cn_flags |= ISLASTCN;
4350 if (cache_fpl_isdotdot(cnp))
4351 cnp->cn_flags |= ISDOTDOT;
4354 * Skip potential extra slashes parsing did not take care of.
4355 * cache_fplookup_skip_slashes explains the mechanism.
4357 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4360 cache_fpl_pathlen_dec(fpl);
4361 } while (*(cnp->cn_nameptr) == '/');
4364 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4366 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4367 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4368 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4369 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4376 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4378 struct componentname *cnp;
4385 tvp_seqc = fpl->tvp_seqc;
4387 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4388 lkflags = LK_SHARED;
4389 if ((cnp->cn_flags & LOCKSHARED) == 0)
4390 lkflags = LK_EXCLUSIVE;
4391 error = vget_finish(tvp, lkflags, tvs);
4392 if (__predict_false(error != 0)) {
4393 return (cache_fpl_aborted(fpl));
4396 vget_finish_ref(tvp, tvs);
4399 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4400 if ((cnp->cn_flags & LOCKLEAF) != 0)
4404 return (cache_fpl_aborted(fpl));
4407 return (cache_fpl_handled(fpl));
4411 * They want to possibly modify the state of the namecache.
4413 static int __noinline
4414 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4416 struct nameidata *ndp;
4417 struct componentname *cnp;
4419 struct vnode *dvp, *tvp;
4428 dvp_seqc = fpl->dvp_seqc;
4430 MPASS(*(cnp->cn_nameptr) != '/');
4431 MPASS(cache_fpl_islastcn(ndp));
4432 if ((cnp->cn_flags & LOCKPARENT) == 0)
4433 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4434 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4435 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4436 cnp->cn_nameiop == RENAME);
4437 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4438 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4440 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4441 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4445 * Regular lookup nulifies the slash, which we don't do here.
4446 * Don't take chances with filesystem routines seeing it for
4449 if (cache_fpl_istrailingslash(fpl)) {
4450 return (cache_fpl_partial(fpl));
4453 mp = atomic_load_ptr(&dvp->v_mount);
4454 if (__predict_false(mp == NULL)) {
4455 return (cache_fpl_aborted(fpl));
4458 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4459 cache_fpl_smr_exit(fpl);
4461 * Original code keeps not checking for CREATE which
4462 * might be a bug. For now let the old lookup decide.
4464 if (cnp->cn_nameiop == CREATE) {
4465 return (cache_fpl_aborted(fpl));
4467 return (cache_fpl_handled_error(fpl, EROFS));
4470 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4471 cache_fpl_smr_exit(fpl);
4472 return (cache_fpl_handled_error(fpl, EEXIST));
4476 * Secure access to dvp; check cache_fplookup_partial_setup for
4479 * XXX At least UFS requires its lookup routine to be called for
4480 * the last path component, which leads to some level of complication
4482 * - the target routine always locks the target vnode, but our caller
4483 * may not need it locked
4484 * - some of the VOP machinery asserts that the parent is locked, which
4485 * once more may be not required
4487 * TODO: add a flag for filesystems which don't need this.
4489 dvs = vget_prep_smr(dvp);
4490 cache_fpl_smr_exit(fpl);
4491 if (__predict_false(dvs == VGET_NONE)) {
4492 return (cache_fpl_aborted(fpl));
4495 vget_finish_ref(dvp, dvs);
4496 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4498 return (cache_fpl_aborted(fpl));
4501 error = vn_lock(dvp, LK_EXCLUSIVE);
4502 if (__predict_false(error != 0)) {
4504 return (cache_fpl_aborted(fpl));
4508 cnp->cn_flags |= ISLASTCN;
4510 cnp->cn_flags |= MAKEENTRY;
4511 if (cache_fpl_isdotdot(cnp))
4512 cnp->cn_flags |= ISDOTDOT;
4513 cnp->cn_lkflags = LK_EXCLUSIVE;
4514 error = VOP_LOOKUP(dvp, &tvp, cnp);
4522 return (cache_fpl_handled_error(fpl, error));
4525 return (cache_fpl_aborted(fpl));
4531 if ((cnp->cn_flags & SAVESTART) != 0) {
4532 ndp->ni_startdir = dvp;
4533 vrefact(ndp->ni_startdir);
4535 MPASS(error == EJUSTRETURN);
4536 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4539 return (cache_fpl_handled(fpl));
4543 * There are very hairy corner cases concerning various flag combinations
4544 * and locking state. In particular here we only hold one lock instead of
4547 * Skip the complexity as it is of no significance for normal workloads.
4549 if (__predict_false(tvp == dvp)) {
4552 return (cache_fpl_aborted(fpl));
4556 * If they want the symlink itself we are fine, but if they want to
4557 * follow it regular lookup has to be engaged.
4559 if (tvp->v_type == VLNK) {
4560 if ((cnp->cn_flags & FOLLOW) != 0) {
4563 return (cache_fpl_aborted(fpl));
4568 * Since we expect this to be the terminal vnode it should almost never
4571 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4574 return (cache_fpl_aborted(fpl));
4577 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4580 return (cache_fpl_handled_error(fpl, EEXIST));
4583 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4587 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4591 if ((cnp->cn_flags & SAVESTART) != 0) {
4592 ndp->ni_startdir = dvp;
4593 vrefact(ndp->ni_startdir);
4596 return (cache_fpl_handled(fpl));
4599 static int __noinline
4600 cache_fplookup_modifying(struct cache_fpl *fpl)
4602 struct nameidata *ndp;
4606 if (!cache_fpl_islastcn(ndp)) {
4607 return (cache_fpl_partial(fpl));
4609 return (cache_fplookup_final_modifying(fpl));
4612 static int __noinline
4613 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4615 struct componentname *cnp;
4616 enum vgetstate dvs, tvs;
4617 struct vnode *dvp, *tvp;
4623 dvp_seqc = fpl->dvp_seqc;
4626 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4629 * This is less efficient than it can be for simplicity.
4631 dvs = vget_prep_smr(dvp);
4632 if (__predict_false(dvs == VGET_NONE)) {
4633 return (cache_fpl_aborted(fpl));
4635 tvs = vget_prep_smr(tvp);
4636 if (__predict_false(tvs == VGET_NONE)) {
4637 cache_fpl_smr_exit(fpl);
4638 vget_abort(dvp, dvs);
4639 return (cache_fpl_aborted(fpl));
4642 cache_fpl_smr_exit(fpl);
4644 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4645 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4646 if (__predict_false(error != 0)) {
4647 vget_abort(tvp, tvs);
4648 return (cache_fpl_aborted(fpl));
4651 vget_finish_ref(dvp, dvs);
4654 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4655 vget_abort(tvp, tvs);
4656 if ((cnp->cn_flags & LOCKPARENT) != 0)
4660 return (cache_fpl_aborted(fpl));
4663 error = cache_fplookup_final_child(fpl, tvs);
4664 if (__predict_false(error != 0)) {
4665 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4666 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4667 if ((cnp->cn_flags & LOCKPARENT) != 0)
4674 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4679 cache_fplookup_final(struct cache_fpl *fpl)
4681 struct componentname *cnp;
4683 struct vnode *dvp, *tvp;
4688 dvp_seqc = fpl->dvp_seqc;
4691 MPASS(*(cnp->cn_nameptr) != '/');
4693 if (cnp->cn_nameiop != LOOKUP) {
4694 return (cache_fplookup_final_modifying(fpl));
4697 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4698 return (cache_fplookup_final_withparent(fpl));
4700 tvs = vget_prep_smr(tvp);
4701 if (__predict_false(tvs == VGET_NONE)) {
4702 return (cache_fpl_partial(fpl));
4705 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4706 cache_fpl_smr_exit(fpl);
4707 vget_abort(tvp, tvs);
4708 return (cache_fpl_aborted(fpl));
4711 cache_fpl_smr_exit(fpl);
4712 return (cache_fplookup_final_child(fpl, tvs));
4716 * Comment from locked lookup:
4717 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4718 * directory, e.g. like "/." or ".".
4720 static int __noinline
4721 cache_fplookup_degenerate(struct cache_fpl *fpl)
4723 struct componentname *cnp;
4731 fpl->tvp = fpl->dvp;
4732 fpl->tvp_seqc = fpl->dvp_seqc;
4738 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4740 ("%s: encountered non-slash; string [%s]\n", __func__,
4745 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4746 cache_fpl_smr_exit(fpl);
4747 return (cache_fpl_handled_error(fpl, EISDIR));
4750 MPASS((cnp->cn_flags & SAVESTART) == 0);
4752 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4753 return (cache_fplookup_final_withparent(fpl));
4756 dvs = vget_prep_smr(dvp);
4757 cache_fpl_smr_exit(fpl);
4758 if (__predict_false(dvs == VGET_NONE)) {
4759 return (cache_fpl_aborted(fpl));
4762 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4763 lkflags = LK_SHARED;
4764 if ((cnp->cn_flags & LOCKSHARED) == 0)
4765 lkflags = LK_EXCLUSIVE;
4766 error = vget_finish(dvp, lkflags, dvs);
4767 if (__predict_false(error != 0)) {
4768 return (cache_fpl_aborted(fpl));
4771 vget_finish_ref(dvp, dvs);
4773 return (cache_fpl_handled(fpl));
4776 static int __noinline
4777 cache_fplookup_emptypath(struct cache_fpl *fpl)
4779 struct nameidata *ndp;
4780 struct componentname *cnp;
4785 fpl->tvp = fpl->dvp;
4786 fpl->tvp_seqc = fpl->dvp_seqc;
4792 MPASS(*cnp->cn_pnbuf == '\0');
4794 if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
4795 cache_fpl_smr_exit(fpl);
4796 return (cache_fpl_handled_error(fpl, ENOENT));
4799 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
4801 tvs = vget_prep_smr(tvp);
4802 cache_fpl_smr_exit(fpl);
4803 if (__predict_false(tvs == VGET_NONE)) {
4804 return (cache_fpl_aborted(fpl));
4807 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4808 lkflags = LK_SHARED;
4809 if ((cnp->cn_flags & LOCKSHARED) == 0)
4810 lkflags = LK_EXCLUSIVE;
4811 error = vget_finish(tvp, lkflags, tvs);
4812 if (__predict_false(error != 0)) {
4813 return (cache_fpl_aborted(fpl));
4816 vget_finish_ref(tvp, tvs);
4819 ndp->ni_resflags |= NIRES_EMPTYPATH;
4820 return (cache_fpl_handled(fpl));
4823 static int __noinline
4824 cache_fplookup_noentry(struct cache_fpl *fpl)
4826 struct nameidata *ndp;
4827 struct componentname *cnp;
4829 struct vnode *dvp, *tvp;
4836 dvp_seqc = fpl->dvp_seqc;
4838 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4839 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4840 if (cnp->cn_nameiop == LOOKUP)
4841 MPASS((cnp->cn_flags & NOCACHE) == 0);
4842 MPASS(!cache_fpl_isdotdot(cnp));
4845 * Hack: delayed name len checking.
4847 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4848 cache_fpl_smr_exit(fpl);
4849 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
4852 if (cnp->cn_nameptr[0] == '/') {
4853 return (cache_fplookup_skip_slashes(fpl));
4856 if (cnp->cn_pnbuf[0] == '\0') {
4857 return (cache_fplookup_emptypath(fpl));
4860 if (cnp->cn_nameptr[0] == '\0') {
4861 if (fpl->tvp == NULL) {
4862 return (cache_fplookup_degenerate(fpl));
4864 return (cache_fplookup_trailingslash(fpl));
4867 if (cnp->cn_nameiop != LOOKUP) {
4869 return (cache_fplookup_modifying(fpl));
4872 MPASS((cnp->cn_flags & SAVESTART) == 0);
4875 * Only try to fill in the component if it is the last one,
4876 * otherwise not only there may be several to handle but the
4877 * walk may be complicated.
4879 if (!cache_fpl_islastcn(ndp)) {
4880 return (cache_fpl_partial(fpl));
4884 * Regular lookup nulifies the slash, which we don't do here.
4885 * Don't take chances with filesystem routines seeing it for
4888 if (cache_fpl_istrailingslash(fpl)) {
4889 return (cache_fpl_partial(fpl));
4893 * Secure access to dvp; check cache_fplookup_partial_setup for
4896 dvs = vget_prep_smr(dvp);
4897 cache_fpl_smr_exit(fpl);
4898 if (__predict_false(dvs == VGET_NONE)) {
4899 return (cache_fpl_aborted(fpl));
4902 vget_finish_ref(dvp, dvs);
4903 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4905 return (cache_fpl_aborted(fpl));
4908 error = vn_lock(dvp, LK_SHARED);
4909 if (__predict_false(error != 0)) {
4911 return (cache_fpl_aborted(fpl));
4916 * TODO: provide variants which don't require locking either vnode.
4918 cnp->cn_flags |= ISLASTCN | MAKEENTRY;
4919 cnp->cn_lkflags = LK_SHARED;
4920 if ((cnp->cn_flags & LOCKSHARED) == 0) {
4921 cnp->cn_lkflags = LK_EXCLUSIVE;
4923 error = VOP_LOOKUP(dvp, &tvp, cnp);
4931 return (cache_fpl_handled_error(fpl, error));
4934 return (cache_fpl_aborted(fpl));
4940 MPASS(error == EJUSTRETURN);
4941 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4943 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4946 return (cache_fpl_handled(fpl));
4949 if (tvp->v_type == VLNK) {
4950 if ((cnp->cn_flags & FOLLOW) != 0) {
4953 return (cache_fpl_aborted(fpl));
4957 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4960 return (cache_fpl_aborted(fpl));
4963 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4967 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4969 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4972 return (cache_fpl_handled(fpl));
4975 static int __noinline
4976 cache_fplookup_dot(struct cache_fpl *fpl)
4980 MPASS(!seqc_in_modify(fpl->dvp_seqc));
4982 * Just re-assign the value. seqc will be checked later for the first
4983 * non-dot path component in line and/or before deciding to return the
4986 fpl->tvp = fpl->dvp;
4987 fpl->tvp_seqc = fpl->dvp_seqc;
4989 counter_u64_add(dothits, 1);
4990 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
4993 if (cache_fplookup_is_mp(fpl)) {
4994 error = cache_fplookup_cross_mount(fpl);
4999 static int __noinline
5000 cache_fplookup_dotdot(struct cache_fpl *fpl)
5002 struct nameidata *ndp;
5003 struct componentname *cnp;
5004 struct namecache *ncp;
5013 MPASS(cache_fpl_isdotdot(cnp));
5016 * XXX this is racy the same way regular lookup is
5018 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5020 if (dvp == pr->pr_root)
5023 if (dvp == ndp->ni_rootdir ||
5024 dvp == ndp->ni_topdir ||
5028 fpl->tvp_seqc = vn_seqc_read_any(dvp);
5029 if (seqc_in_modify(fpl->tvp_seqc)) {
5030 return (cache_fpl_aborted(fpl));
5035 if ((dvp->v_vflag & VV_ROOT) != 0) {
5038 * The opposite of climb mount is needed here.
5040 return (cache_fpl_partial(fpl));
5043 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5045 return (cache_fpl_aborted(fpl));
5048 nc_flag = atomic_load_char(&ncp->nc_flag);
5049 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5050 if ((nc_flag & NCF_NEGATIVE) != 0)
5051 return (cache_fpl_aborted(fpl));
5052 fpl->tvp = ncp->nc_vp;
5054 fpl->tvp = ncp->nc_dvp;
5057 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5058 if (seqc_in_modify(fpl->tvp_seqc)) {
5059 return (cache_fpl_partial(fpl));
5063 * Acquire fence provided by vn_seqc_read_any above.
5065 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5066 return (cache_fpl_aborted(fpl));
5069 if (!cache_ncp_canuse(ncp)) {
5070 return (cache_fpl_aborted(fpl));
5073 counter_u64_add(dotdothits, 1);
5077 static int __noinline
5078 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5080 u_char nc_flag __diagused;
5084 nc_flag = atomic_load_char(&ncp->nc_flag);
5085 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5088 * If they want to create an entry we need to replace this one.
5090 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5092 return (cache_fplookup_modifying(fpl));
5094 neg_promote = cache_neg_hit_prep(ncp);
5095 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5096 cache_neg_hit_abort(ncp);
5097 return (cache_fpl_partial(fpl));
5100 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5102 cache_neg_hit_finish(ncp);
5103 cache_fpl_smr_exit(fpl);
5104 return (cache_fpl_handled_error(fpl, ENOENT));
5108 * Resolve a symlink. Called by filesystem-specific routines.
5111 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5114 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5116 struct nameidata *ndp;
5117 struct componentname *cnp;
5123 if (__predict_false(len == 0)) {
5127 if (__predict_false(len > MAXPATHLEN - 2)) {
5128 if (cache_fpl_istrailingslash(fpl)) {
5133 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5135 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5136 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5137 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5138 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5142 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5143 return (ENAMETOOLONG);
5146 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5151 if (ndp->ni_pathlen > 1) {
5152 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5154 if (cache_fpl_istrailingslash(fpl)) {
5156 cnp->cn_pnbuf[len] = '/';
5157 cnp->cn_pnbuf[len + 1] = '\0';
5159 cnp->cn_pnbuf[len] = '\0';
5162 bcopy(string, cnp->cn_pnbuf, len);
5164 ndp->ni_pathlen += adjust;
5165 cache_fpl_pathlen_add(fpl, adjust);
5166 cnp->cn_nameptr = cnp->cn_pnbuf;
5167 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5172 static int __noinline
5173 cache_fplookup_symlink(struct cache_fpl *fpl)
5176 struct nameidata *ndp;
5177 struct componentname *cnp;
5178 struct vnode *dvp, *tvp;
5186 if (cache_fpl_islastcn(ndp)) {
5187 if ((cnp->cn_flags & FOLLOW) == 0) {
5188 return (cache_fplookup_final(fpl));
5192 mp = atomic_load_ptr(&dvp->v_mount);
5193 if (__predict_false(mp == NULL)) {
5194 return (cache_fpl_aborted(fpl));
5198 * Note this check races against setting the flag just like regular
5201 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5202 cache_fpl_smr_exit(fpl);
5203 return (cache_fpl_handled_error(fpl, EACCES));
5206 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5207 if (__predict_false(error != 0)) {
5210 return (cache_fpl_partial(fpl));
5214 cache_fpl_smr_exit(fpl);
5215 return (cache_fpl_handled_error(fpl, error));
5217 return (cache_fpl_aborted(fpl));
5221 if (*(cnp->cn_nameptr) == '/') {
5222 fpl->dvp = cache_fpl_handle_root(fpl);
5223 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5224 if (seqc_in_modify(fpl->dvp_seqc)) {
5225 return (cache_fpl_aborted(fpl));
5228 * The main loop assumes that ->dvp points to a vnode belonging
5229 * to a filesystem which can do lockless lookup, but the absolute
5230 * symlink can be wandering off to one which does not.
5232 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5233 if (__predict_false(mp == NULL)) {
5234 return (cache_fpl_aborted(fpl));
5236 if (!cache_fplookup_mp_supported(mp)) {
5237 cache_fpl_checkpoint(fpl);
5238 return (cache_fpl_partial(fpl));
5245 cache_fplookup_next(struct cache_fpl *fpl)
5247 struct componentname *cnp;
5248 struct namecache *ncp;
5249 struct vnode *dvp, *tvp;
5258 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5259 if (cnp->cn_namelen == 1) {
5260 return (cache_fplookup_dot(fpl));
5262 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5263 return (cache_fplookup_dotdot(fpl));
5267 MPASS(!cache_fpl_isdotdot(cnp));
5269 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5270 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5271 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5275 if (__predict_false(ncp == NULL)) {
5276 return (cache_fplookup_noentry(fpl));
5279 tvp = atomic_load_ptr(&ncp->nc_vp);
5280 nc_flag = atomic_load_char(&ncp->nc_flag);
5281 if ((nc_flag & NCF_NEGATIVE) != 0) {
5282 return (cache_fplookup_neg(fpl, ncp, hash));
5285 if (!cache_ncp_canuse(ncp)) {
5286 return (cache_fpl_partial(fpl));
5290 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5291 if (seqc_in_modify(fpl->tvp_seqc)) {
5292 return (cache_fpl_partial(fpl));
5295 counter_u64_add(numposhits, 1);
5296 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5299 if (cache_fplookup_is_mp(fpl)) {
5300 error = cache_fplookup_cross_mount(fpl);
5306 cache_fplookup_mp_supported(struct mount *mp)
5310 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5316 * Walk up the mount stack (if any).
5318 * Correctness is provided in the following ways:
5319 * - all vnodes are protected from freeing with SMR
5320 * - struct mount objects are type stable making them always safe to access
5321 * - stability of the particular mount is provided by busying it
5322 * - relationship between the vnode which is mounted on and the mount is
5323 * verified with the vnode sequence counter after busying
5324 * - association between root vnode of the mount and the mount is protected
5327 * From that point on we can read the sequence counter of the root vnode
5328 * and get the next mount on the stack (if any) using the same protection.
5330 * By the end of successful walk we are guaranteed the reached state was
5331 * indeed present at least at some point which matches the regular lookup.
5333 static int __noinline
5334 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5336 struct mount *mp, *prev_mp;
5337 struct mount_pcpu *mpcpu, *prev_mpcpu;
5342 vp_seqc = fpl->tvp_seqc;
5344 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5345 mp = atomic_load_ptr(&vp->v_mountedhere);
5346 if (__predict_false(mp == NULL)) {
5352 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5353 if (prev_mp != NULL)
5354 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5355 return (cache_fpl_partial(fpl));
5357 if (prev_mp != NULL)
5358 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5359 if (!vn_seqc_consistent(vp, vp_seqc)) {
5360 vfs_op_thread_exit_crit(mp, mpcpu);
5361 return (cache_fpl_partial(fpl));
5363 if (!cache_fplookup_mp_supported(mp)) {
5364 vfs_op_thread_exit_crit(mp, mpcpu);
5365 return (cache_fpl_partial(fpl));
5367 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5369 vfs_op_thread_exit_crit(mp, mpcpu);
5370 return (cache_fpl_partial(fpl));
5372 vp_seqc = vn_seqc_read_any(vp);
5373 if (seqc_in_modify(vp_seqc)) {
5374 vfs_op_thread_exit_crit(mp, mpcpu);
5375 return (cache_fpl_partial(fpl));
5379 mp = atomic_load_ptr(&vp->v_mountedhere);
5384 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5386 fpl->tvp_seqc = vp_seqc;
5390 static int __noinline
5391 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5394 struct mount_pcpu *mpcpu;
5399 vp_seqc = fpl->tvp_seqc;
5401 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5402 mp = atomic_load_ptr(&vp->v_mountedhere);
5403 if (__predict_false(mp == NULL)) {
5407 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5408 return (cache_fpl_partial(fpl));
5410 if (!vn_seqc_consistent(vp, vp_seqc)) {
5411 vfs_op_thread_exit_crit(mp, mpcpu);
5412 return (cache_fpl_partial(fpl));
5414 if (!cache_fplookup_mp_supported(mp)) {
5415 vfs_op_thread_exit_crit(mp, mpcpu);
5416 return (cache_fpl_partial(fpl));
5418 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5419 if (__predict_false(vp == NULL)) {
5420 vfs_op_thread_exit_crit(mp, mpcpu);
5421 return (cache_fpl_partial(fpl));
5423 vp_seqc = vn_seqc_read_any(vp);
5424 vfs_op_thread_exit_crit(mp, mpcpu);
5425 if (seqc_in_modify(vp_seqc)) {
5426 return (cache_fpl_partial(fpl));
5428 mp = atomic_load_ptr(&vp->v_mountedhere);
5429 if (__predict_false(mp != NULL)) {
5431 * There are possibly more mount points on top.
5432 * Normally this does not happen so for simplicity just start
5435 return (cache_fplookup_climb_mount(fpl));
5439 fpl->tvp_seqc = vp_seqc;
5444 * Check if a vnode is mounted on.
5447 cache_fplookup_is_mp(struct cache_fpl *fpl)
5452 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5458 * The code was originally copy-pasted from regular lookup and despite
5459 * clean ups leaves performance on the table. Any modifications here
5460 * must take into account that in case off fallback the resulting
5461 * nameidata state has to be compatible with the original.
5465 * Debug ni_pathlen tracking.
5469 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5472 fpl->debug.ni_pathlen += n;
5473 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5474 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5478 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5481 fpl->debug.ni_pathlen -= n;
5482 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5483 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5487 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5490 cache_fpl_pathlen_add(fpl, 1);
5494 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5497 cache_fpl_pathlen_sub(fpl, 1);
5501 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5506 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5511 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5516 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5522 cache_fplookup_parse(struct cache_fpl *fpl)
5524 struct nameidata *ndp;
5525 struct componentname *cnp;
5535 * Find the end of this path component, it is either / or nul.
5537 * Store / as a temporary sentinel so that we only have one character
5538 * to test for. Pathnames tend to be short so this should not be
5539 * resulting in cache misses.
5541 * TODO: fix this to be word-sized.
5543 MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5544 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5545 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5546 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5547 fpl->nulchar, cnp->cn_pnbuf));
5548 KASSERT(*fpl->nulchar == '\0',
5549 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5551 hash = cache_get_hash_iter_start(dvp);
5552 *fpl->nulchar = '/';
5553 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5554 KASSERT(*cp != '\0',
5555 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5557 hash = cache_get_hash_iter(*cp, hash);
5560 *fpl->nulchar = '\0';
5561 fpl->hash = cache_get_hash_iter_finish(hash);
5563 cnp->cn_namelen = cp - cnp->cn_nameptr;
5564 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5568 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5569 * we are going to fail this lookup with ENAMETOOLONG (see below).
5571 if (cnp->cn_namelen <= NAME_MAX) {
5572 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5573 panic("%s: mismatched hash for [%s] len %ld", __func__,
5574 cnp->cn_nameptr, cnp->cn_namelen);
5580 * Hack: we have to check if the found path component's length exceeds
5581 * NAME_MAX. However, the condition is very rarely true and check can
5582 * be elided in the common case -- if an entry was found in the cache,
5583 * then it could not have been too long to begin with.
5589 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5591 struct nameidata *ndp;
5592 struct componentname *cnp;
5597 cnp->cn_nameptr = ndp->ni_next;
5598 KASSERT(*(cnp->cn_nameptr) == '/',
5599 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5600 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5602 cache_fpl_pathlen_dec(fpl);
5606 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5608 * Lockless lookup tries to elide checking for spurious slashes and should they
5609 * be present is guaranteed to fail to find an entry. In this case the caller
5610 * must check if the name starts with a slash and call this routine. It is
5611 * going to fast forward across the spurious slashes and set the state up for
5614 static int __noinline
5615 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5617 struct nameidata *ndp;
5618 struct componentname *cnp;
5623 MPASS(*(cnp->cn_nameptr) == '/');
5626 cache_fpl_pathlen_dec(fpl);
5627 } while (*(cnp->cn_nameptr) == '/');
5630 * Go back to one slash so that cache_fplookup_parse_advance has
5631 * something to skip.
5634 cache_fpl_pathlen_inc(fpl);
5637 * cache_fplookup_parse_advance starts from ndp->ni_next
5639 ndp->ni_next = cnp->cn_nameptr;
5642 * See cache_fplookup_dot.
5644 fpl->tvp = fpl->dvp;
5645 fpl->tvp_seqc = fpl->dvp_seqc;
5651 * Handle trailing slashes (e.g., "foo/").
5653 * If a trailing slash is found the terminal vnode must be a directory.
5654 * Regular lookup shortens the path by nulifying the first trailing slash and
5655 * sets the TRAILINGSLASH flag to denote this took place. There are several
5656 * checks on it performed later.
5658 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5659 * manner relying on an invariant that a non-directory vnode will get a miss.
5660 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5662 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5663 * and denotes this is the last path component, which avoids looping back.
5665 * Only plain lookups are supported for now to restrict corner cases to handle.
5667 static int __noinline
5668 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5673 struct nameidata *ndp;
5674 struct componentname *cnp;
5675 struct namecache *ncp;
5677 char *cn_nameptr_orig, *cn_nameptr_slash;
5684 tvp_seqc = fpl->tvp_seqc;
5686 MPASS(fpl->dvp == fpl->tvp);
5687 KASSERT(cache_fpl_istrailingslash(fpl),
5688 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5690 KASSERT(cnp->cn_nameptr[0] == '\0',
5691 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5693 KASSERT(cnp->cn_namelen == 0,
5694 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5696 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5698 if (cnp->cn_nameiop != LOOKUP) {
5699 return (cache_fpl_aborted(fpl));
5702 if (__predict_false(tvp->v_type != VDIR)) {
5703 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5704 return (cache_fpl_aborted(fpl));
5706 cache_fpl_smr_exit(fpl);
5707 return (cache_fpl_handled_error(fpl, ENOTDIR));
5711 * Denote the last component.
5713 ndp->ni_next = &cnp->cn_nameptr[0];
5714 MPASS(cache_fpl_islastcn(ndp));
5717 * Unwind trailing slashes.
5719 cn_nameptr_orig = cnp->cn_nameptr;
5720 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5722 if (cnp->cn_nameptr[0] != '/') {
5728 * Unwind to the beginning of the path component.
5730 * Note the path may or may not have started with a slash.
5732 cn_nameptr_slash = cnp->cn_nameptr;
5733 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5735 if (cnp->cn_nameptr[0] == '/') {
5739 if (cnp->cn_nameptr[0] == '/') {
5743 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5744 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5745 cache_fpl_checkpoint(fpl);
5748 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5749 if (ni_pathlen != fpl->debug.ni_pathlen) {
5750 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5751 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5752 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5757 * If this was a "./" lookup the parent directory is already correct.
5759 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5764 * Otherwise we need to look it up.
5767 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5768 if (__predict_false(ncp == NULL)) {
5769 return (cache_fpl_aborted(fpl));
5771 nc_flag = atomic_load_char(&ncp->nc_flag);
5772 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5773 return (cache_fpl_aborted(fpl));
5775 fpl->dvp = ncp->nc_dvp;
5776 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5777 if (seqc_in_modify(fpl->dvp_seqc)) {
5778 return (cache_fpl_aborted(fpl));
5784 * See the API contract for VOP_FPLOOKUP_VEXEC.
5786 static int __noinline
5787 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5789 struct componentname *cnp;
5795 dvp_seqc = fpl->dvp_seqc;
5798 * Hack: delayed empty path checking.
5800 if (cnp->cn_pnbuf[0] == '\0') {
5801 return (cache_fplookup_emptypath(fpl));
5805 * TODO: Due to ignoring trailing slashes lookup will perform a
5806 * permission check on the last dir when it should not be doing it. It
5807 * may fail, but said failure should be ignored. It is possible to fix
5808 * it up fully without resorting to regular lookup, but for now just
5811 if (cache_fpl_istrailingslash(fpl)) {
5812 return (cache_fpl_aborted(fpl));
5816 * Hack: delayed degenerate path checking.
5818 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5819 return (cache_fplookup_degenerate(fpl));
5823 * Hack: delayed name len checking.
5825 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5826 cache_fpl_smr_exit(fpl);
5827 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5831 * Hack: they may be looking up foo/bar, where foo is not a directory.
5832 * In such a case we need to return ENOTDIR, but we may happen to get
5833 * here with a different error.
5835 if (dvp->v_type != VDIR) {
5840 * Hack: handle O_SEARCH.
5842 * Open Group Base Specifications Issue 7, 2018 edition states:
5844 * If the access mode of the open file description associated with the
5845 * file descriptor is not O_SEARCH, the function shall check whether
5846 * directory searches are permitted using the current permissions of
5847 * the directory underlying the file descriptor. If the access mode is
5848 * O_SEARCH, the function shall not perform the check.
5851 * Regular lookup tests for the NOEXECCHECK flag for every path
5852 * component to decide whether to do the permission check. However,
5853 * since most lookups never have the flag (and when they do it is only
5854 * present for the first path component), lockless lookup only acts on
5855 * it if there is a permission problem. Here the flag is represented
5856 * with a boolean so that we don't have to clear it on the way out.
5858 * For simplicity this always aborts.
5859 * TODO: check if this is the first lookup and ignore the permission
5860 * problem. Note the flag has to survive fallback (if it happens to be
5864 return (cache_fpl_aborted(fpl));
5869 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5870 error = cache_fpl_aborted(fpl);
5872 cache_fpl_partial(fpl);
5876 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5877 error = cache_fpl_aborted(fpl);
5879 cache_fpl_smr_exit(fpl);
5880 cache_fpl_handled_error(fpl, error);
5888 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
5890 struct nameidata *ndp;
5891 struct componentname *cnp;
5898 cache_fpl_checkpoint(fpl);
5901 * The vnode at hand is almost always stable, skip checking for it.
5902 * Worst case this postpones the check towards the end of the iteration
5906 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
5908 mp = atomic_load_ptr(&dvp->v_mount);
5909 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
5910 return (cache_fpl_aborted(fpl));
5913 MPASS(fpl->tvp == NULL);
5916 cache_fplookup_parse(fpl);
5918 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
5919 if (__predict_false(error != 0)) {
5920 error = cache_fplookup_failed_vexec(fpl, error);
5924 error = cache_fplookup_next(fpl);
5925 if (__predict_false(cache_fpl_terminated(fpl))) {
5929 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
5931 if (fpl->tvp->v_type == VLNK) {
5932 error = cache_fplookup_symlink(fpl);
5933 if (cache_fpl_terminated(fpl)) {
5937 if (cache_fpl_islastcn(ndp)) {
5938 error = cache_fplookup_final(fpl);
5942 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
5943 error = cache_fpl_aborted(fpl);
5947 fpl->dvp = fpl->tvp;
5948 fpl->dvp_seqc = fpl->tvp_seqc;
5949 cache_fplookup_parse_advance(fpl);
5952 cache_fpl_checkpoint(fpl);
5959 * Fast path lookup protected with SMR and sequence counters.
5961 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
5963 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
5966 * Traditional vnode lookup conceptually looks like this:
5972 * vn_unlock(current);
5979 * Each jump to the next vnode is safe memory-wise and atomic with respect to
5980 * any modifications thanks to holding respective locks.
5982 * The same guarantee can be provided with a combination of safe memory
5983 * reclamation and sequence counters instead. If all operations which affect
5984 * the relationship between the current vnode and the one we are looking for
5985 * also modify the counter, we can verify whether all the conditions held as
5986 * we made the jump. This includes things like permissions, mount points etc.
5987 * Counter modification is provided by enclosing relevant places in
5988 * vn_seqc_write_begin()/end() calls.
5990 * Thus this translates to:
5993 * dvp_seqc = seqc_read_any(dvp);
5994 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
5998 * tvp_seqc = seqc_read_any(tvp);
5999 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6001 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6003 * dvp = tvp; // we know nothing of importance has changed
6004 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6008 * vget(); // secure the vnode
6009 * if (!seqc_consistent(tvp, tvp_seqc) // final check
6011 * // at this point we know nothing has changed for any parent<->child pair
6012 * // as they were crossed during the lookup, meaning we matched the guarantee
6013 * // of the locked variant
6016 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6017 * - they are called while within vfs_smr protection which they must never exit
6018 * - EAGAIN can be returned to denote checking could not be performed, it is
6019 * always valid to return it
6020 * - if the sequence counter has not changed the result must be valid
6021 * - if the sequence counter has changed both false positives and false negatives
6022 * are permitted (since the result will be rejected later)
6023 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6025 * Caveats to watch out for:
6026 * - vnodes are passed unlocked and unreferenced with nothing stopping
6027 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6028 * to use atomic_load_ptr to fetch it.
6029 * - the aforementioned object can also get freed, meaning absent other means it
6030 * should be protected with vfs_smr
6031 * - either safely checking permissions as they are modified or guaranteeing
6032 * their stability is left to the routine
6035 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6038 struct cache_fpl fpl;
6041 struct componentname *cnp;
6044 fpl.status = CACHE_FPL_STATUS_UNSET;
6047 fpl.cnp = cnp = &ndp->ni_cnd;
6048 MPASS(ndp->ni_lcf == 0);
6049 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6050 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6052 if ((cnp->cn_flags & SAVESTART) != 0) {
6053 MPASS(cnp->cn_nameiop != LOOKUP);
6055 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6057 if (__predict_false(!cache_can_fplookup(&fpl))) {
6058 *status = fpl.status;
6059 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6060 return (EOPNOTSUPP);
6063 cache_fpl_checkpoint_outer(&fpl);
6065 cache_fpl_smr_enter_initial(&fpl);
6067 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6069 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6070 fpl.fsearch = false;
6071 fpl.tvp = NULL; /* for degenerate path handling */
6073 pwd = pwd_get_smr();
6075 ndp->ni_rootdir = pwd->pwd_rdir;
6076 ndp->ni_topdir = pwd->pwd_jdir;
6078 if (cnp->cn_pnbuf[0] == '/') {
6079 dvp = cache_fpl_handle_root(&fpl);
6080 MPASS(ndp->ni_resflags == 0);
6081 ndp->ni_resflags = NIRES_ABS;
6083 if (ndp->ni_dirfd == AT_FDCWD) {
6084 dvp = pwd->pwd_cdir;
6086 error = cache_fplookup_dirfd(&fpl, &dvp);
6087 if (__predict_false(error != 0)) {
6093 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6094 error = cache_fplookup_impl(dvp, &fpl);
6096 cache_fpl_smr_assert_not_entered(&fpl);
6097 cache_fpl_assert_status(&fpl);
6098 *status = fpl.status;
6099 if (SDT_PROBES_ENABLED()) {
6100 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6101 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6102 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6106 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6107 MPASS(error != CACHE_FPL_FAILED);
6109 cache_fpl_cleanup_cnp(fpl.cnp);
6110 MPASS(fpl.dvp == NULL);
6111 MPASS(fpl.tvp == NULL);
6113 ndp->ni_dvp = fpl.dvp;
6114 ndp->ni_vp = fpl.tvp;