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>
39 #include "opt_ktrace.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/capsicum.h>
44 #include <sys/counter.h>
45 #include <sys/filedesc.h>
46 #include <sys/fnv_hash.h>
47 #include <sys/kernel.h>
50 #include <sys/malloc.h>
51 #include <sys/fcntl.h>
53 #include <sys/mount.h>
54 #include <sys/namei.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysproto.h>
63 #include <sys/vnode.h>
66 #include <sys/ktrace.h>
69 #include <machine/_inttypes.h>
72 #include <security/audit/audit.h>
73 #include <security/mac/mac_framework.h>
82 * High level overview of name caching in the VFS layer.
84 * Originally caching was implemented as part of UFS, later extracted to allow
85 * use by other filesystems. A decision was made to make it optional and
86 * completely detached from the rest of the kernel, which comes with limitations
87 * outlined near the end of this comment block.
89 * This fundamental choice needs to be revisited. In the meantime, the current
90 * state is described below. Significance of all notable routines is explained
91 * in comments placed above their implementation. Scattered thoroughout the
92 * file are TODO comments indicating shortcomings which can be fixed without
93 * reworking everything (most of the fixes will likely be reusable). Various
94 * details are omitted from this explanation to not clutter the overview, they
95 * have to be checked by reading the code and associated commentary.
97 * Keep in mind that it's individual path components which are cached, not full
98 * paths. That is, for a fully cached path "foo/bar/baz" there are 3 entries,
101 * I. Data organization
103 * Entries are described by "struct namecache" objects and stored in a hash
104 * table. See cache_get_hash for more information.
106 * "struct vnode" contains pointers to source entries (names which can be found
107 * when traversing through said vnode), destination entries (names of that
108 * vnode (see "Limitations" for a breakdown on the subject) and a pointer to
111 * The (directory vnode; name) tuple reliably determines the target entry if
114 * Since there are no small locks at this time (all are 32 bytes in size on
115 * LP64), the code works around the problem by introducing lock arrays to
116 * protect hash buckets and vnode lists.
118 * II. Filesystem integration
120 * Filesystems participating in name caching do the following:
121 * - set vop_lookup routine to vfs_cache_lookup
122 * - set vop_cachedlookup to whatever can perform the lookup if the above fails
123 * - if they support lockless lookup (see below), vop_fplookup_vexec and
124 * vop_fplookup_symlink are set along with the MNTK_FPLOOKUP flag on the
126 * - call cache_purge or cache_vop_* routines to eliminate stale entries as
128 * - call cache_enter to add entries depending on the MAKEENTRY flag
130 * With the above in mind, there are 2 entry points when doing lookups:
131 * - ... -> namei -> cache_fplookup -- this is the default
132 * - ... -> VOP_LOOKUP -> vfs_cache_lookup -- normally only called by namei
133 * should the above fail
135 * Example code flow how an entry is added:
136 * ... -> namei -> cache_fplookup -> cache_fplookup_noentry -> VOP_LOOKUP ->
137 * vfs_cache_lookup -> VOP_CACHEDLOOKUP -> ufs_lookup_ino -> cache_enter
139 * III. Performance considerations
141 * For lockless case forward lookup avoids any writes to shared areas apart
142 * from the terminal path component. In other words non-modifying lookups of
143 * different files don't suffer any scalability problems in the namecache.
144 * Looking up the same file is limited by VFS and goes beyond the scope of this
147 * At least on amd64 the single-threaded bottleneck for long paths is hashing
148 * (see cache_get_hash). There are cases where the code issues acquire fence
149 * multiple times, they can be combined on architectures which suffer from it.
151 * For locked case each encountered vnode has to be referenced and locked in
152 * order to be handed out to the caller (normally that's namei). This
153 * introduces significant hit single-threaded and serialization multi-threaded.
155 * Reverse lookup (e.g., "getcwd") fully scales provided it is fully cached --
156 * avoids any writes to shared areas to any components.
158 * Unrelated insertions are partially serialized on updating the global entry
159 * counter and possibly serialized on colliding bucket or vnode locks.
163 * Note not everything has an explicit dtrace probe nor it should have, thus
164 * some of the one-liners below depend on implementation details.
168 * # Check what lookups failed to be handled in a lockless manner. Column 1 is
169 * # line number, column 2 is status code (see cache_fpl_status)
170 * dtrace -n 'vfs:fplookup:lookup:done { @[arg1, arg2] = count(); }'
172 * # Lengths of names added by binary name
173 * dtrace -n 'fbt::cache_enter_time:entry { @[execname] = quantize(args[2]->cn_namelen); }'
175 * # Same as above but only those which exceed 64 characters
176 * dtrace -n 'fbt::cache_enter_time:entry /args[2]->cn_namelen > 64/ { @[execname] = quantize(args[2]->cn_namelen); }'
178 * # Who is performing lookups with spurious slashes (e.g., "foo//bar") and what
180 * dtrace -n 'fbt::cache_fplookup_skip_slashes:entry { @[execname, stringof(args[0]->cnp->cn_pnbuf)] = count(); }'
182 * V. Limitations and implementation defects
184 * - since it is possible there is no entry for an open file, tools like
185 * "procstat" may fail to resolve fd -> vnode -> path to anything
186 * - even if a filesystem adds an entry, it may get purged (e.g., due to memory
187 * shortage) in which case the above problem applies
188 * - hardlinks are not tracked, thus if a vnode is reachable in more than one
189 * way, resolving a name may return a different path than the one used to
190 * open it (even if said path is still valid)
191 * - by default entries are not added for newly created files
192 * - adding an entry may need to evict negative entry first, which happens in 2
193 * distinct places (evicting on lookup, adding in a later VOP) making it
194 * impossible to simply reuse it
195 * - there is a simple scheme to evict negative entries as the cache is approaching
196 * its capacity, but it is very unclear if doing so is a good idea to begin with
197 * - vnodes are subject to being recycled even if target inode is left in memory,
198 * which loses the name cache entries when it perhaps should not. in case of tmpfs
199 * names get duplicated -- kept by filesystem itself and namecache separately
200 * - struct namecache has a fixed size and comes in 2 variants, often wasting
201 * space. now hard to replace with malloc due to dependence on SMR, which
202 * requires UMA zones to opt in
203 * - lack of better integration with the kernel also turns nullfs into a layered
204 * filesystem instead of something which can take advantage of caching
206 * Appendix A: where is the time lost, expanding on paragraph III
208 * While some care went into optimizing lookups, there is still plenty of
209 * performance left on the table, most notably from single-threaded standpoint.
210 * Below is a woefully incomplete list of changes which can help. Ideas are
211 * mostly sketched out, no claim is made all kinks or prerequisites are laid
214 * Note there is performance lost all over VFS.
216 * === SMR-only lookup
218 * For commonly used ops like stat(2), when the terminal vnode *is* cached,
219 * lockless lookup could refrain from refing/locking the found vnode and
220 * instead return while within the SMR section. Then a call to, say,
221 * vop_stat_smr could do the work (or fail with EAGAIN), finally the result
222 * would be validated with seqc not changing. This would be faster
223 * single-threaded as it dodges atomics and would provide full scalability for
224 * multicore uses. This would *not* work for open(2) or other calls which need
225 * the vnode to hang around for the long haul, but would work for aforementioned
226 * stat(2) but also access(2), readlink(2), realpathat(2) and probably more.
228 * === hotpatching for sdt probes
230 * They result in *tons* of branches all over with rather regrettable codegen
231 * at times. Removing sdt probes altogether gives over 2% boost in lookup rate.
232 * Reworking the code to patch itself at runtime with asm goto would solve it.
233 * asm goto is fully supported by gcc and clang.
237 * On all architectures it operates one byte at a time, while it could be
238 * word-sized instead thanks to the Mycroft trick.
240 * API itself is rather pessimal for path lookup, accepting arbitrary sizes and
241 * *optionally* filling in the length parameter.
243 * Instead a new routine (copyinpath?) could be introduced, demanding a buffer
244 * size which is a multiply of the word (and never zero), with the length
245 * always returned. On top of it the routine could be allowed to transform the
246 * buffer in arbitrary ways, most notably writing past the found length (not to
247 * be confused with writing past buffer size) -- this would allow word-sized
248 * movs while checking for '\0' later.
250 * === detour through namei
252 * Currently one suffers being called from namei, which then has to check if
253 * things worked out locklessly. Instead the lockless lookup could be the
254 * actual entry point which calls what is currently namei as a fallback.
256 * === avoidable branches in cache_can_fplookup
258 * The cache_fast_lookup_enabled flag check could be hotpatchable (in fact if
259 * this is off, none of fplookup code should execute).
261 * Both audit and capsicum branches can be combined into one, but it requires
262 * paying off a lot of tech debt first.
264 * ni_startdir could be indicated with a flag in cn_flags, eliminating the
269 * Crossing a mount requires checking if perhaps something is mounted on top.
270 * Instead, an additional entry could be added to struct mount with a pointer
271 * to the final mount on the stack. This would be recalculated on each
276 * It could become part of the API contract to *always* have a rootvnode set in
277 * mnt_rootvnode. Such vnodes are annotated with VV_ROOT and vnlru would have
278 * to be modified to always skip them.
281 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
284 SDT_PROVIDER_DECLARE(vfs);
285 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
287 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
289 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
291 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
293 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
294 "struct namecache *", "int", "int");
295 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
296 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
297 "char *", "struct vnode *");
298 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
299 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
300 "struct vnode *", "char *");
301 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
303 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
304 "struct vnode *", "char *");
305 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
307 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
308 "struct componentname *");
309 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
310 "struct componentname *");
311 SDT_PROBE_DEFINE3(vfs, namecache, purge, done, "struct vnode *", "size_t", "size_t");
312 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
313 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
314 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
315 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
317 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
319 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
321 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
323 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
324 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
325 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
327 static char __read_frequently cache_fast_lookup_enabled = true;
330 * This structure describes the elements in the cache of recent
331 * names looked up by namei.
337 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
338 "the state must fit in a union with a pointer without growing it");
341 LIST_ENTRY(namecache) nc_src; /* source vnode list */
342 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
343 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
344 struct vnode *nc_dvp; /* vnode of parent of name */
346 struct vnode *nu_vp; /* vnode the name refers to */
347 struct negstate nu_neg;/* negative entry state */
349 u_char nc_flag; /* flag bits */
350 u_char nc_nlen; /* length of name */
351 char nc_name[]; /* segment name + nul */
355 * struct namecache_ts repeats struct namecache layout up to the
357 * struct namecache_ts is used in place of struct namecache when time(s) need
358 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
359 * both a non-dotdot directory name plus dotdot for the directory's
362 * See below for alignment requirement.
364 struct namecache_ts {
365 struct timespec nc_time; /* timespec provided by fs */
366 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
367 int nc_ticks; /* ticks value when entry was added */
369 struct namecache nc_nc;
372 TAILQ_HEAD(cache_freebatch, namecache);
375 * At least mips n32 performs 64-bit accesses to timespec as found
376 * in namecache_ts and requires them to be aligned. Since others
377 * may be in the same spot suffer a little bit and enforce the
378 * alignment for everyone. Note this is a nop for 64-bit platforms.
380 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
383 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
384 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
385 * smaller and the value was bumped to retain the total size, but it
386 * was never re-evaluated for suitability. A simple test counting
387 * lengths during package building shows that the value of 45 covers
388 * about 86% of all added entries, reaching 99% at 65.
390 * Regardless of the above, use of dedicated zones instead of malloc may be
391 * inducing additional waste. This may be hard to address as said zones are
392 * tied to VFS SMR. Even if retaining them, the current split should be
396 #define CACHE_PATH_CUTOFF 45
397 #define CACHE_LARGE_PAD 6
399 #define CACHE_PATH_CUTOFF 41
400 #define CACHE_LARGE_PAD 2
403 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
404 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
405 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
406 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
408 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
409 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
410 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
411 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
413 #define nc_vp n_un.nu_vp
414 #define nc_neg n_un.nu_neg
417 * Flags in namecache.nc_flag
419 #define NCF_WHITE 0x01
420 #define NCF_ISDOTDOT 0x02
423 #define NCF_DVDROP 0x10
424 #define NCF_NEGATIVE 0x20
425 #define NCF_INVALID 0x40
429 * Flags in negstate.neg_flag
433 static bool cache_neg_evict_cond(u_long lnumcache);
436 * Mark an entry as invalid.
438 * This is called before it starts getting deconstructed.
441 cache_ncp_invalidate(struct namecache *ncp)
444 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
445 ("%s: entry %p already invalid", __func__, ncp));
446 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
447 atomic_thread_fence_rel();
451 * Check whether the entry can be safely used.
453 * All places which elide locks are supposed to call this after they are
454 * done with reading from an entry.
456 #define cache_ncp_canuse(ncp) ({ \
457 struct namecache *_ncp = (ncp); \
460 atomic_thread_fence_acq(); \
461 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
462 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0); \
466 * Like the above but also checks NCF_WHITE.
468 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
469 struct namecache *_ncp = (ncp); \
472 atomic_thread_fence_acq(); \
473 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
474 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
479 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
480 "Name cache parameters");
482 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
483 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RD, &ncsize, 0,
484 "Total namecache capacity");
486 u_int ncsizefactor = 2;
487 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
488 "Size factor for namecache");
490 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
491 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
492 "Ratio of negative namecache entries");
495 * Negative entry % of namecache capacity above which automatic eviction is allowed.
497 * Check cache_neg_evict_cond for details.
499 static u_int ncnegminpct = 3;
501 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
502 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
503 "Negative entry count above which automatic eviction is allowed");
506 * Structures associated with name caching.
508 #define NCHHASH(hash) \
509 (&nchashtbl[(hash) & nchash])
510 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
511 static u_long __read_mostly nchash; /* size of hash table */
512 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
513 "Size of namecache hash table");
514 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
515 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
517 struct nchstats nchstats; /* cache effectiveness statistics */
519 static u_int __exclusive_cache_line neg_cycle;
522 #define numneglists (ncneghash + 1)
525 struct mtx nl_evict_lock;
526 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
527 TAILQ_HEAD(, namecache) nl_list;
528 TAILQ_HEAD(, namecache) nl_hotlist;
530 } __aligned(CACHE_LINE_SIZE);
532 static struct neglist neglists[numneglists];
534 static inline struct neglist *
535 NCP2NEGLIST(struct namecache *ncp)
538 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
541 static inline struct negstate *
542 NCP2NEGSTATE(struct namecache *ncp)
545 MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
546 return (&ncp->nc_neg);
549 #define numbucketlocks (ncbuckethash + 1)
550 static u_int __read_mostly ncbuckethash;
551 static struct mtx_padalign __read_mostly *bucketlocks;
552 #define HASH2BUCKETLOCK(hash) \
553 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
555 #define numvnodelocks (ncvnodehash + 1)
556 static u_int __read_mostly ncvnodehash;
557 static struct mtx __read_mostly *vnodelocks;
558 static inline struct mtx *
559 VP2VNODELOCK(struct vnode *vp)
562 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
566 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
568 struct namecache_ts *ncp_ts;
570 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
571 (tsp == NULL && ticksp == NULL),
577 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
578 *tsp = ncp_ts->nc_time;
579 *ticksp = ncp_ts->nc_ticks;
583 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
584 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
585 "VFS namecache enabled");
588 /* Export size information to userland */
589 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
590 sizeof(struct namecache), "sizeof(struct namecache)");
593 * The new name cache statistics
595 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
596 "Name cache statistics");
598 #define STATNODE_ULONG(name, varname, descr) \
599 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
600 #define STATNODE_COUNTER(name, varname, descr) \
601 static COUNTER_U64_DEFINE_EARLY(varname); \
602 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
604 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
605 STATNODE_ULONG(count, numcache, "Number of cache entries");
606 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
607 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
608 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
609 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
610 STATNODE_COUNTER(poszaps, numposzaps,
611 "Number of cache hits (positive) we do not want to cache");
612 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
613 STATNODE_COUNTER(negzaps, numnegzaps,
614 "Number of cache hits (negative) we do not want to cache");
615 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
616 /* These count for vn_getcwd(), too. */
617 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
618 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
619 "Number of fullpath search errors (VOP_VPTOCNP failures)");
620 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
621 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
622 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
625 * Debug or developer statistics.
627 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
628 "Name cache debugging");
629 #define DEBUGNODE_ULONG(name, varname, descr) \
630 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
631 static u_long zap_bucket_relock_success;
632 DEBUGNODE_ULONG(zap_bucket_relock_success, zap_bucket_relock_success,
633 "Number of successful removals after relocking");
634 static u_long zap_bucket_fail;
635 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
636 static u_long zap_bucket_fail2;
637 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
638 static u_long cache_lock_vnodes_cel_3_failures;
639 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
640 "Number of times 3-way vnode locking failed");
642 static void cache_zap_locked(struct namecache *ncp);
643 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
644 char **retbuf, size_t *buflen, size_t addend);
645 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
646 char **retbuf, size_t *buflen);
647 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
648 char **retbuf, size_t *len, size_t addend);
650 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
653 cache_assert_vlp_locked(struct mtx *vlp)
657 mtx_assert(vlp, MA_OWNED);
661 cache_assert_vnode_locked(struct vnode *vp)
665 vlp = VP2VNODELOCK(vp);
666 cache_assert_vlp_locked(vlp);
670 * Directory vnodes with entries are held for two reasons:
671 * 1. make them less of a target for reclamation in vnlru
672 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
674 * It will be feasible to stop doing it altogether if all filesystems start
675 * supporting lockless lookup.
678 cache_hold_vnode(struct vnode *vp)
681 cache_assert_vnode_locked(vp);
682 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
684 counter_u64_add(numcachehv, 1);
688 cache_drop_vnode(struct vnode *vp)
692 * Called after all locks are dropped, meaning we can't assert
693 * on the state of v_cache_src.
696 counter_u64_add(numcachehv, -1);
702 static uma_zone_t __read_mostly cache_zone_small;
703 static uma_zone_t __read_mostly cache_zone_small_ts;
704 static uma_zone_t __read_mostly cache_zone_large;
705 static uma_zone_t __read_mostly cache_zone_large_ts;
708 cache_symlink_alloc(size_t size, int flags)
711 if (size < CACHE_ZONE_SMALL_SIZE) {
712 return (uma_zalloc_smr(cache_zone_small, flags));
714 if (size < CACHE_ZONE_LARGE_SIZE) {
715 return (uma_zalloc_smr(cache_zone_large, flags));
717 counter_u64_add(symlinktoobig, 1);
718 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
723 cache_symlink_free(char *string, size_t size)
726 MPASS(string != NULL);
727 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
728 ("%s: size %zu too big", __func__, size));
730 if (size < CACHE_ZONE_SMALL_SIZE) {
731 uma_zfree_smr(cache_zone_small, string);
734 if (size < CACHE_ZONE_LARGE_SIZE) {
735 uma_zfree_smr(cache_zone_large, string);
738 __assert_unreachable();
741 static struct namecache *
742 cache_alloc_uma(int len, bool ts)
744 struct namecache_ts *ncp_ts;
745 struct namecache *ncp;
747 if (__predict_false(ts)) {
748 if (len <= CACHE_PATH_CUTOFF)
749 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
751 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
752 ncp = &ncp_ts->nc_nc;
754 if (len <= CACHE_PATH_CUTOFF)
755 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
757 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
763 cache_free_uma(struct namecache *ncp)
765 struct namecache_ts *ncp_ts;
767 if (__predict_false(ncp->nc_flag & NCF_TS)) {
768 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
769 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
770 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
772 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
774 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
775 uma_zfree_smr(cache_zone_small, ncp);
777 uma_zfree_smr(cache_zone_large, ncp);
781 static struct namecache *
782 cache_alloc(int len, bool ts)
787 * Avoid blowout in namecache entries.
790 * 1. filesystems may end up trying to add an already existing entry
791 * (for example this can happen after a cache miss during concurrent
792 * lookup), in which case we will call cache_neg_evict despite not
794 * 2. the routine may fail to free anything and no provisions are made
795 * to make it try harder (see the inside for failure modes)
796 * 3. it only ever looks at negative entries.
798 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
799 if (cache_neg_evict_cond(lnumcache)) {
800 lnumcache = atomic_load_long(&numcache);
802 if (__predict_false(lnumcache >= ncsize)) {
803 atomic_subtract_long(&numcache, 1);
804 counter_u64_add(numdrops, 1);
807 return (cache_alloc_uma(len, ts));
811 cache_free(struct namecache *ncp)
815 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
816 cache_drop_vnode(ncp->nc_dvp);
819 atomic_subtract_long(&numcache, 1);
823 cache_free_batch(struct cache_freebatch *batch)
825 struct namecache *ncp, *nnp;
829 if (TAILQ_EMPTY(batch))
831 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
832 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
833 cache_drop_vnode(ncp->nc_dvp);
838 atomic_subtract_long(&numcache, i);
840 SDT_PROBE1(vfs, namecache, purge, batch, i);
846 * The code was made to use FNV in 2001 and this choice needs to be revisited.
848 * Short summary of the difficulty:
849 * The longest name which can be inserted is NAME_MAX characters in length (or
850 * 255 at the time of writing this comment), while majority of names used in
851 * practice are significantly shorter (mostly below 10). More importantly
852 * majority of lookups performed find names are even shorter than that.
854 * This poses a problem where hashes which do better than FNV past word size
855 * (or so) tend to come with additional overhead when finalizing the result,
856 * making them noticeably slower for the most commonly used range.
858 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
860 * When looking it up the most time consuming part by a large margin (at least
861 * on amd64) is hashing. Replacing FNV with something which pessimizes short
862 * input would make the slowest part stand out even more.
866 * TODO: With the value stored we can do better than computing the hash based
870 cache_prehash(struct vnode *vp)
873 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
877 cache_get_hash(char *name, u_char len, struct vnode *dvp)
880 return (fnv_32_buf(name, len, dvp->v_nchash));
884 cache_get_hash_iter_start(struct vnode *dvp)
887 return (dvp->v_nchash);
891 cache_get_hash_iter(char c, uint32_t hash)
894 return (fnv_32_buf(&c, 1, hash));
898 cache_get_hash_iter_finish(uint32_t hash)
904 static inline struct nchashhead *
905 NCP2BUCKET(struct namecache *ncp)
909 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
910 return (NCHHASH(hash));
913 static inline struct mtx *
914 NCP2BUCKETLOCK(struct namecache *ncp)
918 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
919 return (HASH2BUCKETLOCK(hash));
924 cache_assert_bucket_locked(struct namecache *ncp)
928 blp = NCP2BUCKETLOCK(ncp);
929 mtx_assert(blp, MA_OWNED);
933 cache_assert_bucket_unlocked(struct namecache *ncp)
937 blp = NCP2BUCKETLOCK(ncp);
938 mtx_assert(blp, MA_NOTOWNED);
941 #define cache_assert_bucket_locked(x) do { } while (0)
942 #define cache_assert_bucket_unlocked(x) do { } while (0)
945 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
947 _cache_sort_vnodes(void **p1, void **p2)
951 MPASS(*p1 != NULL || *p2 != NULL);
961 cache_lock_all_buckets(void)
965 for (i = 0; i < numbucketlocks; i++)
966 mtx_lock(&bucketlocks[i]);
970 cache_unlock_all_buckets(void)
974 for (i = 0; i < numbucketlocks; i++)
975 mtx_unlock(&bucketlocks[i]);
979 cache_lock_all_vnodes(void)
983 for (i = 0; i < numvnodelocks; i++)
984 mtx_lock(&vnodelocks[i]);
988 cache_unlock_all_vnodes(void)
992 for (i = 0; i < numvnodelocks; i++)
993 mtx_unlock(&vnodelocks[i]);
997 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
1000 cache_sort_vnodes(&vlp1, &vlp2);
1003 if (!mtx_trylock(vlp1))
1006 if (!mtx_trylock(vlp2)) {
1016 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
1019 MPASS(vlp1 != NULL || vlp2 != NULL);
1020 MPASS(vlp1 <= vlp2);
1029 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
1032 MPASS(vlp1 != NULL || vlp2 != NULL);
1041 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
1043 struct nchstats snap;
1045 if (req->oldptr == NULL)
1046 return (SYSCTL_OUT(req, 0, sizeof(snap)));
1049 snap.ncs_goodhits = counter_u64_fetch(numposhits);
1050 snap.ncs_neghits = counter_u64_fetch(numneghits);
1051 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
1052 counter_u64_fetch(numnegzaps);
1053 snap.ncs_miss = counter_u64_fetch(nummisszap) +
1054 counter_u64_fetch(nummiss);
1056 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
1058 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
1059 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
1060 "VFS cache effectiveness statistics");
1063 cache_recalc_neg_min(void)
1066 neg_min = (ncsize * ncnegminpct) / 100;
1070 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1076 error = sysctl_handle_int(oidp, &val, 0, req);
1077 if (error != 0 || req->newptr == NULL)
1080 if (val == ncnegminpct)
1082 if (val < 0 || val > 99)
1085 cache_recalc_neg_min();
1089 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1090 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1091 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1095 * Grab an atomic snapshot of the name cache hash chain lengths
1097 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1098 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1099 "hash table stats");
1102 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1104 struct nchashhead *ncpp;
1105 struct namecache *ncp;
1106 int i, error, n_nchash, *cntbuf;
1109 n_nchash = nchash + 1; /* nchash is max index, not count */
1110 if (req->oldptr == NULL)
1111 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1112 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1113 cache_lock_all_buckets();
1114 if (n_nchash != nchash + 1) {
1115 cache_unlock_all_buckets();
1116 free(cntbuf, M_TEMP);
1119 /* Scan hash tables counting entries */
1120 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1121 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1123 cache_unlock_all_buckets();
1124 for (error = 0, i = 0; i < n_nchash; i++)
1125 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1127 free(cntbuf, M_TEMP);
1130 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1131 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1132 "nchash chain lengths");
1135 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1138 struct nchashhead *ncpp;
1139 struct namecache *ncp;
1141 int count, maxlength, used, pct;
1144 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1146 cache_lock_all_buckets();
1147 n_nchash = nchash + 1; /* nchash is max index, not count */
1151 /* Scan hash tables for applicable entries */
1152 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1154 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1159 if (maxlength < count)
1162 n_nchash = nchash + 1;
1163 cache_unlock_all_buckets();
1164 pct = (used * 100) / (n_nchash / 100);
1165 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1168 error = SYSCTL_OUT(req, &used, sizeof(used));
1171 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1174 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1179 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1180 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1181 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1185 * Negative entries management
1187 * Various workloads create plenty of negative entries and barely use them
1188 * afterwards. Moreover malicious users can keep performing bogus lookups
1189 * adding even more entries. For example "make tinderbox" as of writing this
1190 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1193 * As such, a rather aggressive eviction method is needed. The currently
1194 * employed method is a placeholder.
1196 * Entries are split over numneglists separate lists, each of which is further
1197 * split into hot and cold entries. Entries get promoted after getting a hit.
1198 * Eviction happens on addition of new entry.
1200 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1201 "Name cache negative entry statistics");
1203 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1204 "Number of negative cache entries");
1206 static COUNTER_U64_DEFINE_EARLY(neg_created);
1207 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1208 "Number of created negative entries");
1210 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1211 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1212 "Number of evicted negative entries");
1214 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1215 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1216 &neg_evict_skipped_empty,
1217 "Number of times evicting failed due to lack of entries");
1219 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1220 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1221 &neg_evict_skipped_missed,
1222 "Number of times evicting failed due to target entry disappearing");
1224 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1225 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1226 &neg_evict_skipped_contended,
1227 "Number of times evicting failed due to contention");
1229 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1230 "Number of cache hits (negative)");
1233 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1238 for (i = 0; i < numneglists; i++)
1239 out += neglists[i].nl_hotnum;
1241 return (SYSCTL_OUT(req, &out, sizeof(out)));
1243 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1244 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1245 "Number of hot negative entries");
1248 cache_neg_init(struct namecache *ncp)
1250 struct negstate *ns;
1252 ncp->nc_flag |= NCF_NEGATIVE;
1253 ns = NCP2NEGSTATE(ncp);
1256 counter_u64_add(neg_created, 1);
1259 #define CACHE_NEG_PROMOTION_THRESH 2
1262 cache_neg_hit_prep(struct namecache *ncp)
1264 struct negstate *ns;
1267 ns = NCP2NEGSTATE(ncp);
1268 n = atomic_load_char(&ns->neg_hit);
1270 if (n >= CACHE_NEG_PROMOTION_THRESH)
1272 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1275 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1279 * Nothing to do here but it is provided for completeness as some
1280 * cache_neg_hit_prep callers may end up returning without even
1281 * trying to promote.
1283 #define cache_neg_hit_abort(ncp) do { } while (0)
1286 cache_neg_hit_finish(struct namecache *ncp)
1289 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1290 counter_u64_add(numneghits, 1);
1294 * Move a negative entry to the hot list.
1297 cache_neg_promote_locked(struct namecache *ncp)
1300 struct negstate *ns;
1302 ns = NCP2NEGSTATE(ncp);
1303 nl = NCP2NEGLIST(ncp);
1304 mtx_assert(&nl->nl_lock, MA_OWNED);
1305 if ((ns->neg_flag & NEG_HOT) == 0) {
1306 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1307 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1309 ns->neg_flag |= NEG_HOT;
1314 * Move a hot negative entry to the cold list.
1317 cache_neg_demote_locked(struct namecache *ncp)
1320 struct negstate *ns;
1322 ns = NCP2NEGSTATE(ncp);
1323 nl = NCP2NEGLIST(ncp);
1324 mtx_assert(&nl->nl_lock, MA_OWNED);
1325 MPASS(ns->neg_flag & NEG_HOT);
1326 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1327 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1329 ns->neg_flag &= ~NEG_HOT;
1330 atomic_store_char(&ns->neg_hit, 0);
1334 * Move a negative entry to the hot list if it matches the lookup.
1336 * We have to take locks, but they may be contended and in the worst
1337 * case we may need to go off CPU. We don't want to spin within the
1338 * smr section and we can't block with it. Exiting the section means
1339 * the found entry could have been evicted. We are going to look it
1343 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1344 struct namecache *oncp, uint32_t hash)
1346 struct namecache *ncp;
1350 nl = NCP2NEGLIST(oncp);
1352 mtx_lock(&nl->nl_lock);
1354 * For hash iteration.
1359 * Avoid all surprises by only succeeding if we got the same entry and
1360 * bailing completely otherwise.
1361 * XXX There are no provisions to keep the vnode around, meaning we may
1362 * end up promoting a negative entry for a *new* vnode and returning
1363 * ENOENT on its account. This is the error we want to return anyway
1364 * and promotion is harmless.
1366 * In particular at this point there can be a new ncp which matches the
1367 * search but hashes to a different neglist.
1369 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1375 * No match to begin with.
1377 if (__predict_false(ncp == NULL)) {
1382 * The newly found entry may be something different...
1384 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1385 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1390 * ... and not even negative.
1392 nc_flag = atomic_load_char(&ncp->nc_flag);
1393 if ((nc_flag & NCF_NEGATIVE) == 0) {
1397 if (!cache_ncp_canuse(ncp)) {
1401 cache_neg_promote_locked(ncp);
1402 cache_neg_hit_finish(ncp);
1404 mtx_unlock(&nl->nl_lock);
1408 mtx_unlock(&nl->nl_lock);
1413 cache_neg_promote(struct namecache *ncp)
1417 nl = NCP2NEGLIST(ncp);
1418 mtx_lock(&nl->nl_lock);
1419 cache_neg_promote_locked(ncp);
1420 mtx_unlock(&nl->nl_lock);
1424 cache_neg_insert(struct namecache *ncp)
1428 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1429 cache_assert_bucket_locked(ncp);
1430 nl = NCP2NEGLIST(ncp);
1431 mtx_lock(&nl->nl_lock);
1432 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1433 mtx_unlock(&nl->nl_lock);
1434 atomic_add_long(&numneg, 1);
1438 cache_neg_remove(struct namecache *ncp)
1441 struct negstate *ns;
1443 cache_assert_bucket_locked(ncp);
1444 nl = NCP2NEGLIST(ncp);
1445 ns = NCP2NEGSTATE(ncp);
1446 mtx_lock(&nl->nl_lock);
1447 if ((ns->neg_flag & NEG_HOT) != 0) {
1448 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1451 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1453 mtx_unlock(&nl->nl_lock);
1454 atomic_subtract_long(&numneg, 1);
1457 static struct neglist *
1458 cache_neg_evict_select_list(void)
1463 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1464 nl = &neglists[c % numneglists];
1465 if (!mtx_trylock(&nl->nl_evict_lock)) {
1466 counter_u64_add(neg_evict_skipped_contended, 1);
1472 static struct namecache *
1473 cache_neg_evict_select_entry(struct neglist *nl)
1475 struct namecache *ncp, *lncp;
1476 struct negstate *ns, *lns;
1479 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1480 mtx_assert(&nl->nl_lock, MA_OWNED);
1481 ncp = TAILQ_FIRST(&nl->nl_list);
1485 lns = NCP2NEGSTATE(lncp);
1486 for (i = 1; i < 4; i++) {
1487 ncp = TAILQ_NEXT(ncp, nc_dst);
1490 ns = NCP2NEGSTATE(ncp);
1491 if (ns->neg_hit < lns->neg_hit) {
1500 cache_neg_evict(void)
1502 struct namecache *ncp, *ncp2;
1511 nl = cache_neg_evict_select_list();
1516 mtx_lock(&nl->nl_lock);
1517 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1519 cache_neg_demote_locked(ncp);
1521 ncp = cache_neg_evict_select_entry(nl);
1523 counter_u64_add(neg_evict_skipped_empty, 1);
1524 mtx_unlock(&nl->nl_lock);
1525 mtx_unlock(&nl->nl_evict_lock);
1528 nlen = ncp->nc_nlen;
1530 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1531 dvlp = VP2VNODELOCK(dvp);
1532 blp = HASH2BUCKETLOCK(hash);
1533 mtx_unlock(&nl->nl_lock);
1534 mtx_unlock(&nl->nl_evict_lock);
1538 * Note that since all locks were dropped above, the entry may be
1539 * gone or reallocated to be something else.
1541 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1542 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1543 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1547 counter_u64_add(neg_evict_skipped_missed, 1);
1551 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1552 MPASS(blp == NCP2BUCKETLOCK(ncp));
1553 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1555 cache_zap_locked(ncp);
1556 counter_u64_add(neg_evicted, 1);
1567 * Maybe evict a negative entry to create more room.
1569 * The ncnegfactor parameter limits what fraction of the total count
1570 * can comprise of negative entries. However, if the cache is just
1571 * warming up this leads to excessive evictions. As such, ncnegminpct
1572 * (recomputed to neg_min) dictates whether the above should be
1575 * Try evicting if the cache is close to full capacity regardless of
1576 * other considerations.
1579 cache_neg_evict_cond(u_long lnumcache)
1583 if (ncsize - 1000 < lnumcache)
1585 lnumneg = atomic_load_long(&numneg);
1586 if (lnumneg < neg_min)
1588 if (lnumneg * ncnegfactor < lnumcache)
1591 return (cache_neg_evict());
1595 * cache_zap_locked():
1597 * Removes a namecache entry from cache, whether it contains an actual
1598 * pointer to a vnode or if it is just a negative cache entry.
1601 cache_zap_locked(struct namecache *ncp)
1603 struct nchashhead *ncpp;
1604 struct vnode *dvp, *vp;
1609 if (!(ncp->nc_flag & NCF_NEGATIVE))
1610 cache_assert_vnode_locked(vp);
1611 cache_assert_vnode_locked(dvp);
1612 cache_assert_bucket_locked(ncp);
1614 cache_ncp_invalidate(ncp);
1616 ncpp = NCP2BUCKET(ncp);
1617 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1618 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1619 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1620 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1621 if (ncp == vp->v_cache_dd) {
1622 atomic_store_ptr(&vp->v_cache_dd, NULL);
1625 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1626 cache_neg_remove(ncp);
1628 if (ncp->nc_flag & NCF_ISDOTDOT) {
1629 if (ncp == dvp->v_cache_dd) {
1630 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1633 LIST_REMOVE(ncp, nc_src);
1634 if (LIST_EMPTY(&dvp->v_cache_src)) {
1635 ncp->nc_flag |= NCF_DVDROP;
1641 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1645 MPASS(ncp->nc_dvp == vp);
1646 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1647 cache_assert_vnode_locked(vp);
1649 blp = NCP2BUCKETLOCK(ncp);
1651 cache_zap_locked(ncp);
1656 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1659 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1662 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1663 cache_assert_vnode_locked(vp);
1665 if (ncp->nc_flag & NCF_NEGATIVE) {
1666 if (*vlpp != NULL) {
1670 cache_zap_negative_locked_vnode_kl(ncp, vp);
1674 pvlp = VP2VNODELOCK(vp);
1675 blp = NCP2BUCKETLOCK(ncp);
1676 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1677 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1679 if (*vlpp == vlp1 || *vlpp == vlp2) {
1683 if (*vlpp != NULL) {
1687 cache_sort_vnodes(&vlp1, &vlp2);
1692 if (!mtx_trylock(vlp1))
1698 cache_zap_locked(ncp);
1700 if (to_unlock != NULL)
1701 mtx_unlock(to_unlock);
1708 MPASS(*vlpp == NULL);
1714 * If trylocking failed we can get here. We know enough to take all needed locks
1715 * in the right order and re-lookup the entry.
1718 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1719 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1722 struct namecache *rncp;
1725 cache_assert_bucket_unlocked(ncp);
1727 cache_sort_vnodes(&dvlp, &vlp);
1728 cache_lock_vnodes(dvlp, vlp);
1730 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1731 if (rncp == ncp && rncp->nc_dvp == dvp &&
1732 rncp->nc_nlen == cnp->cn_namelen &&
1733 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1740 if (!(ncp->nc_flag & NCF_NEGATIVE))
1741 rvlp = VP2VNODELOCK(rncp->nc_vp);
1747 cache_zap_locked(rncp);
1749 cache_unlock_vnodes(dvlp, vlp);
1750 atomic_add_long(&zap_bucket_relock_success, 1);
1755 cache_unlock_vnodes(dvlp, vlp);
1759 static int __noinline
1760 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1761 uint32_t hash, struct mtx *blp)
1763 struct mtx *dvlp, *vlp;
1766 cache_assert_bucket_locked(ncp);
1768 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1770 if (!(ncp->nc_flag & NCF_NEGATIVE))
1771 vlp = VP2VNODELOCK(ncp->nc_vp);
1772 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1773 cache_zap_locked(ncp);
1775 cache_unlock_vnodes(dvlp, vlp);
1781 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1784 static __noinline int
1785 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1787 struct namecache *ncp;
1789 struct mtx *dvlp, *dvlp2;
1793 if (cnp->cn_namelen == 2 &&
1794 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1795 dvlp = VP2VNODELOCK(dvp);
1799 ncp = dvp->v_cache_dd;
1804 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1807 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1808 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1810 MPASS(dvp->v_cache_dd == NULL);
1816 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1821 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1826 * XXX note that access here is completely unlocked with no provisions
1827 * to keep the hash allocated. If one is sufficiently unlucky a
1828 * parallel cache resize can reallocate the hash, unmap backing pages
1829 * and cause the empty check below to fault.
1831 * Fixing this has epsilon priority, but can be done with no overhead
1832 * for this codepath with sufficient effort.
1834 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1835 blp = HASH2BUCKETLOCK(hash);
1837 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1842 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1843 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1844 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1853 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1854 if (__predict_false(error != 0)) {
1855 atomic_add_long(&zap_bucket_fail, 1);
1858 counter_u64_add(numposzaps, 1);
1859 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1863 counter_u64_add(nummisszap, 1);
1864 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1868 static int __noinline
1869 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1870 struct timespec *tsp, int *ticksp)
1875 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1882 * When we lookup "." we still can be asked to lock it
1885 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1886 if (ltype != VOP_ISLOCKED(*vpp)) {
1887 if (ltype == LK_EXCLUSIVE) {
1888 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1889 if (VN_IS_DOOMED((*vpp))) {
1890 /* forced unmount */
1896 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1901 static int __noinline
1902 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1903 struct timespec *tsp, int *ticksp)
1905 struct namecache_ts *ncp_ts;
1906 struct namecache *ncp;
1912 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1914 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1915 cache_remove_cnp(dvp, cnp);
1920 dvlp = VP2VNODELOCK(dvp);
1922 ncp = dvp->v_cache_dd;
1924 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1928 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1929 if (ncp->nc_flag & NCF_NEGATIVE)
1936 goto negative_success;
1937 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1938 cache_out_ts(ncp, tsp, ticksp);
1939 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1940 NCF_DTS && tsp != NULL) {
1941 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1942 *tsp = ncp_ts->nc_dotdottime;
1946 ltype = VOP_ISLOCKED(dvp);
1948 vs = vget_prep(*vpp);
1950 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1951 vn_lock(dvp, ltype | LK_RETRY);
1952 if (VN_IS_DOOMED(dvp)) {
1964 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1965 if (cnp->cn_flags & ISLASTCN) {
1966 counter_u64_add(numnegzaps, 1);
1967 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1974 whiteout = (ncp->nc_flag & NCF_WHITE);
1975 cache_out_ts(ncp, tsp, ticksp);
1976 if (cache_neg_hit_prep(ncp))
1977 cache_neg_promote(ncp);
1979 cache_neg_hit_finish(ncp);
1982 cnp->cn_flags |= ISWHITEOUT;
1987 * Lookup a name in the name cache
1991 * - dvp: Parent directory in which to search.
1992 * - vpp: Return argument. Will contain desired vnode on cache hit.
1993 * - cnp: Parameters of the name search. The most interesting bits of
1994 * the cn_flags field have the following meanings:
1995 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1997 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1998 * - tsp: Return storage for cache timestamp. On a successful (positive
1999 * or negative) lookup, tsp will be filled with any timespec that
2000 * was stored when this cache entry was created. However, it will
2001 * be clear for "." entries.
2002 * - ticks: Return storage for alternate cache timestamp. On a successful
2003 * (positive or negative) lookup, it will contain the ticks value
2004 * that was current when the cache entry was created, unless cnp
2007 * Either both tsp and ticks have to be provided or neither of them.
2011 * - -1: A positive cache hit. vpp will contain the desired vnode.
2012 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
2013 * to a forced unmount. vpp will not be modified. If the entry
2014 * is a whiteout, then the ISWHITEOUT flag will be set in
2016 * - 0: A cache miss. vpp will not be modified.
2020 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
2021 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
2022 * lock is not recursively acquired.
2024 static int __noinline
2025 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2026 struct timespec *tsp, int *ticksp)
2028 struct namecache *ncp;
2035 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2036 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
2039 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2040 blp = HASH2BUCKETLOCK(hash);
2043 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2044 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2045 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2049 if (__predict_false(ncp == NULL)) {
2051 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2052 counter_u64_add(nummiss, 1);
2056 if (ncp->nc_flag & NCF_NEGATIVE)
2057 goto negative_success;
2059 counter_u64_add(numposhits, 1);
2061 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2062 cache_out_ts(ncp, tsp, ticksp);
2064 vs = vget_prep(*vpp);
2066 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2074 * We don't get here with regular lookup apart from corner cases.
2076 if (__predict_true(cnp->cn_nameiop == CREATE)) {
2077 if (cnp->cn_flags & ISLASTCN) {
2078 counter_u64_add(numnegzaps, 1);
2079 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2080 if (__predict_false(error != 0)) {
2081 atomic_add_long(&zap_bucket_fail2, 1);
2089 whiteout = (ncp->nc_flag & NCF_WHITE);
2090 cache_out_ts(ncp, tsp, ticksp);
2091 if (cache_neg_hit_prep(ncp))
2092 cache_neg_promote(ncp);
2094 cache_neg_hit_finish(ncp);
2097 cnp->cn_flags |= ISWHITEOUT;
2102 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2103 struct timespec *tsp, int *ticksp)
2105 struct namecache *ncp;
2109 bool whiteout, neg_promote;
2112 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2115 if (__predict_false(!doingcache)) {
2116 cnp->cn_flags &= ~MAKEENTRY;
2121 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2122 if (cnp->cn_namelen == 1)
2123 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2124 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2125 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2128 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2130 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2131 cache_remove_cnp(dvp, cnp);
2135 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2138 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2139 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2140 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2144 if (__predict_false(ncp == NULL)) {
2146 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2147 counter_u64_add(nummiss, 1);
2151 nc_flag = atomic_load_char(&ncp->nc_flag);
2152 if (nc_flag & NCF_NEGATIVE)
2153 goto negative_success;
2155 counter_u64_add(numposhits, 1);
2157 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2158 cache_out_ts(ncp, tsp, ticksp);
2160 if (!cache_ncp_canuse(ncp)) {
2165 vs = vget_prep_smr(*vpp);
2167 if (__predict_false(vs == VGET_NONE)) {
2171 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2178 if (cnp->cn_nameiop == CREATE) {
2179 if (cnp->cn_flags & ISLASTCN) {
2185 cache_out_ts(ncp, tsp, ticksp);
2186 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2187 neg_promote = cache_neg_hit_prep(ncp);
2188 if (!cache_ncp_canuse(ncp)) {
2189 cache_neg_hit_abort(ncp);
2195 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2198 cache_neg_hit_finish(ncp);
2202 cnp->cn_flags |= ISWHITEOUT;
2205 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2208 struct celockstate {
2212 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2213 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2216 cache_celockstate_init(struct celockstate *cel)
2219 bzero(cel, sizeof(*cel));
2223 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2226 struct mtx *vlp1, *vlp2;
2228 MPASS(cel->vlp[0] == NULL);
2229 MPASS(cel->vlp[1] == NULL);
2230 MPASS(cel->vlp[2] == NULL);
2232 MPASS(vp != NULL || dvp != NULL);
2234 vlp1 = VP2VNODELOCK(vp);
2235 vlp2 = VP2VNODELOCK(dvp);
2236 cache_sort_vnodes(&vlp1, &vlp2);
2247 cache_unlock_vnodes_cel(struct celockstate *cel)
2250 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2252 if (cel->vlp[0] != NULL)
2253 mtx_unlock(cel->vlp[0]);
2254 if (cel->vlp[1] != NULL)
2255 mtx_unlock(cel->vlp[1]);
2256 if (cel->vlp[2] != NULL)
2257 mtx_unlock(cel->vlp[2]);
2261 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2266 cache_assert_vlp_locked(cel->vlp[0]);
2267 cache_assert_vlp_locked(cel->vlp[1]);
2268 MPASS(cel->vlp[2] == NULL);
2271 vlp = VP2VNODELOCK(vp);
2274 if (vlp >= cel->vlp[1]) {
2277 if (mtx_trylock(vlp))
2279 cache_unlock_vnodes_cel(cel);
2280 atomic_add_long(&cache_lock_vnodes_cel_3_failures, 1);
2281 if (vlp < cel->vlp[0]) {
2283 mtx_lock(cel->vlp[0]);
2284 mtx_lock(cel->vlp[1]);
2286 if (cel->vlp[0] != NULL)
2287 mtx_lock(cel->vlp[0]);
2289 mtx_lock(cel->vlp[1]);
2299 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2303 MPASS(cel->blp[0] == NULL);
2304 MPASS(cel->blp[1] == NULL);
2306 cache_sort_vnodes(&blp1, &blp2);
2317 cache_unlock_buckets_cel(struct celockstate *cel)
2320 if (cel->blp[0] != NULL)
2321 mtx_unlock(cel->blp[0]);
2322 mtx_unlock(cel->blp[1]);
2326 * Lock part of the cache affected by the insertion.
2328 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2329 * However, insertion can result in removal of an old entry. In this
2330 * case we have an additional vnode and bucketlock pair to lock.
2332 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2333 * preserving the locking order (smaller address first).
2336 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2339 struct namecache *ncp;
2340 struct mtx *blps[2];
2343 blps[0] = HASH2BUCKETLOCK(hash);
2346 cache_lock_vnodes_cel(cel, dvp, vp);
2347 if (vp == NULL || vp->v_type != VDIR)
2349 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2352 nc_flag = atomic_load_char(&ncp->nc_flag);
2353 if ((nc_flag & NCF_ISDOTDOT) == 0)
2355 MPASS(ncp->nc_dvp == vp);
2356 blps[1] = NCP2BUCKETLOCK(ncp);
2357 if ((nc_flag & NCF_NEGATIVE) != 0)
2359 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2362 * All vnodes got re-locked. Re-validate the state and if
2363 * nothing changed we are done. Otherwise restart.
2365 if (ncp == vp->v_cache_dd &&
2366 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2367 blps[1] == NCP2BUCKETLOCK(ncp) &&
2368 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2370 cache_unlock_vnodes_cel(cel);
2375 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2379 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2382 struct namecache *ncp;
2383 struct mtx *blps[2];
2386 blps[0] = HASH2BUCKETLOCK(hash);
2389 cache_lock_vnodes_cel(cel, dvp, vp);
2390 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2393 nc_flag = atomic_load_char(&ncp->nc_flag);
2394 if ((nc_flag & NCF_ISDOTDOT) == 0)
2396 MPASS(ncp->nc_dvp == dvp);
2397 blps[1] = NCP2BUCKETLOCK(ncp);
2398 if ((nc_flag & NCF_NEGATIVE) != 0)
2400 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2402 if (ncp == dvp->v_cache_dd &&
2403 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2404 blps[1] == NCP2BUCKETLOCK(ncp) &&
2405 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2407 cache_unlock_vnodes_cel(cel);
2412 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2416 cache_enter_unlock(struct celockstate *cel)
2419 cache_unlock_buckets_cel(cel);
2420 cache_unlock_vnodes_cel(cel);
2423 static void __noinline
2424 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2425 struct componentname *cnp)
2427 struct celockstate cel;
2428 struct namecache *ncp;
2432 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2434 len = cnp->cn_namelen;
2435 cache_celockstate_init(&cel);
2436 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2437 cache_enter_lock_dd(&cel, dvp, vp, hash);
2438 ncp = dvp->v_cache_dd;
2439 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2440 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2441 cache_zap_locked(ncp);
2445 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2446 cache_enter_unlock(&cel);
2452 * Add an entry to the cache.
2455 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2456 struct timespec *tsp, struct timespec *dtsp)
2458 struct celockstate cel;
2459 struct namecache *ncp, *n2, *ndd;
2460 struct namecache_ts *ncp_ts;
2461 struct nchashhead *ncpp;
2466 KASSERT(cnp->cn_namelen <= NAME_MAX,
2467 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2469 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2470 VNPASS(dvp->v_type != VNON, dvp);
2472 VNPASS(!VN_IS_DOOMED(vp), vp);
2473 VNPASS(vp->v_type != VNON, vp);
2475 if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
2477 ("%s: different vnodes for dot entry (%p; %p)\n", __func__,
2481 ("%s: same vnode for non-dot entry [%s] (%p)\n", __func__,
2482 cnp->cn_nameptr, dvp));
2486 if (__predict_false(!doingcache))
2491 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2492 if (cnp->cn_namelen == 1)
2494 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2495 cache_enter_dotdot_prep(dvp, vp, cnp);
2496 flag = NCF_ISDOTDOT;
2500 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2504 cache_celockstate_init(&cel);
2509 * Calculate the hash key and setup as much of the new
2510 * namecache entry as possible before acquiring the lock.
2512 ncp->nc_flag = flag | NCF_WIP;
2515 cache_neg_init(ncp);
2518 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2519 ncp_ts->nc_time = *tsp;
2520 ncp_ts->nc_ticks = ticks;
2521 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2523 ncp_ts->nc_dotdottime = *dtsp;
2524 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2527 len = ncp->nc_nlen = cnp->cn_namelen;
2528 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2529 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2530 ncp->nc_name[len] = '\0';
2531 cache_enter_lock(&cel, dvp, vp, hash);
2534 * See if this vnode or negative entry is already in the cache
2535 * with this name. This can happen with concurrent lookups of
2536 * the same path name.
2538 ncpp = NCHHASH(hash);
2539 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2540 if (n2->nc_dvp == dvp &&
2541 n2->nc_nlen == cnp->cn_namelen &&
2542 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2543 MPASS(cache_ncp_canuse(n2));
2544 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2546 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2547 __func__, NULL, vp, cnp->cn_nameptr));
2549 KASSERT(n2->nc_vp == vp,
2550 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2551 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2553 * Entries are supposed to be immutable unless in the
2554 * process of getting destroyed. Accommodating for
2555 * changing timestamps is possible but not worth it.
2556 * This should be harmless in terms of correctness, in
2557 * the worst case resulting in an earlier expiration.
2558 * Alternatively, the found entry can be replaced
2561 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2564 KASSERT((n2->nc_flag & NCF_TS) != 0,
2566 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2567 n2_ts->nc_time = ncp_ts->nc_time;
2568 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2570 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2571 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2575 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2577 goto out_unlock_free;
2581 if (flag == NCF_ISDOTDOT) {
2583 * See if we are trying to add .. entry, but some other lookup
2584 * has populated v_cache_dd pointer already.
2586 if (dvp->v_cache_dd != NULL)
2587 goto out_unlock_free;
2588 KASSERT(vp == NULL || vp->v_type == VDIR,
2589 ("wrong vnode type %p", vp));
2590 atomic_thread_fence_rel();
2591 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2595 if (flag != NCF_ISDOTDOT) {
2597 * For this case, the cache entry maps both the
2598 * directory name in it and the name ".." for the
2599 * directory's parent.
2601 if ((ndd = vp->v_cache_dd) != NULL) {
2602 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2603 cache_zap_locked(ndd);
2607 atomic_thread_fence_rel();
2608 atomic_store_ptr(&vp->v_cache_dd, ncp);
2609 } else if (vp->v_type != VDIR) {
2610 if (vp->v_cache_dd != NULL) {
2611 atomic_store_ptr(&vp->v_cache_dd, NULL);
2616 if (flag != NCF_ISDOTDOT) {
2617 if (LIST_EMPTY(&dvp->v_cache_src)) {
2618 cache_hold_vnode(dvp);
2620 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2624 * If the entry is "negative", we place it into the
2625 * "negative" cache queue, otherwise, we place it into the
2626 * destination vnode's cache entries queue.
2629 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2630 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2633 if (cnp->cn_flags & ISWHITEOUT)
2634 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2635 cache_neg_insert(ncp);
2636 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2641 * Insert the new namecache entry into the appropriate chain
2642 * within the cache entries table.
2644 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2646 atomic_thread_fence_rel();
2648 * Mark the entry as fully constructed.
2649 * It is immutable past this point until its removal.
2651 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2653 cache_enter_unlock(&cel);
2658 cache_enter_unlock(&cel);
2664 * A variant of the above accepting flags.
2666 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2668 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2669 * happens to match and it is doing it in an inefficient manner. It was added
2670 * to accommodate NFS which runs into a case where the target for a given name
2671 * may change from under it. Note this does nothing to solve the following
2672 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2673 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2676 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2677 struct timespec *tsp, struct timespec *dtsp, int flags)
2680 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2682 if (flags & VFS_CACHE_DROPOLD)
2683 cache_remove_cnp(dvp, cnp);
2684 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2688 cache_roundup_2(u_long val)
2692 for (res = 1; res <= val; res <<= 1)
2698 static struct nchashhead *
2699 nchinittbl(u_long elements, u_long *hashmask)
2701 struct nchashhead *hashtbl;
2704 hashsize = cache_roundup_2(elements) / 2;
2706 hashtbl = malloc(hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2707 for (i = 0; i < hashsize; i++)
2708 CK_SLIST_INIT(&hashtbl[i]);
2709 *hashmask = hashsize - 1;
2714 ncfreetbl(struct nchashhead *hashtbl)
2717 free(hashtbl, M_VFSCACHE);
2721 * Name cache initialization, from vfs_init() when we are booting
2724 nchinit(void *dummy __unused)
2728 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2729 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2730 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2731 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2732 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2733 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2734 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2735 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2737 VFS_SMR_ZONE_SET(cache_zone_small);
2738 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2739 VFS_SMR_ZONE_SET(cache_zone_large);
2740 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2742 ncsize = desiredvnodes * ncsizefactor;
2743 cache_recalc_neg_min();
2744 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2745 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2746 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2748 if (ncbuckethash > nchash)
2749 ncbuckethash = nchash;
2750 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2752 for (i = 0; i < numbucketlocks; i++)
2753 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2754 ncvnodehash = ncbuckethash;
2755 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2757 for (i = 0; i < numvnodelocks; i++)
2758 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2760 for (i = 0; i < numneglists; i++) {
2761 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2762 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2763 TAILQ_INIT(&neglists[i].nl_list);
2764 TAILQ_INIT(&neglists[i].nl_hotlist);
2767 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2770 cache_vnode_init(struct vnode *vp)
2773 LIST_INIT(&vp->v_cache_src);
2774 TAILQ_INIT(&vp->v_cache_dst);
2775 vp->v_cache_dd = NULL;
2780 * Induce transient cache misses for lockless operation in cache_lookup() by
2781 * using a temporary hash table.
2783 * This will force a fs lookup.
2785 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2786 * to observe all CPUs not performing the lookup.
2789 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2792 MPASS(temphash < nchash);
2794 * Change the size. The new size is smaller and can safely be used
2795 * against the existing table. All lookups which now hash wrong will
2796 * result in a cache miss, which all callers are supposed to know how
2799 atomic_store_long(&nchash, temphash);
2800 atomic_thread_fence_rel();
2801 vfs_smr_synchronize();
2803 * At this point everyone sees the updated hash value, but they still
2804 * see the old table.
2806 atomic_store_ptr(&nchashtbl, temptbl);
2807 atomic_thread_fence_rel();
2808 vfs_smr_synchronize();
2810 * At this point everyone sees the updated table pointer and size pair.
2815 * Set the new hash table.
2817 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2818 * lockless operation in cache_lookup().
2821 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2824 MPASS(nchash < new_hash);
2826 * Change the pointer first. This wont result in out of bounds access
2827 * since the temporary table is guaranteed to be smaller.
2829 atomic_store_ptr(&nchashtbl, new_tbl);
2830 atomic_thread_fence_rel();
2831 vfs_smr_synchronize();
2833 * At this point everyone sees the updated pointer value, but they
2834 * still see the old size.
2836 atomic_store_long(&nchash, new_hash);
2837 atomic_thread_fence_rel();
2838 vfs_smr_synchronize();
2840 * At this point everyone sees the updated table pointer and size pair.
2845 cache_changesize(u_long newmaxvnodes)
2847 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2848 u_long new_nchash, old_nchash, temphash;
2849 struct namecache *ncp;
2854 newncsize = newmaxvnodes * ncsizefactor;
2855 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2856 if (newmaxvnodes < numbucketlocks)
2857 newmaxvnodes = numbucketlocks;
2859 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2860 /* If same hash table size, nothing to do */
2861 if (nchash == new_nchash) {
2862 ncfreetbl(new_nchashtbl);
2866 temptbl = nchinittbl(1, &temphash);
2869 * Move everything from the old hash table to the new table.
2870 * None of the namecache entries in the table can be removed
2871 * because to do so, they have to be removed from the hash table.
2873 cache_lock_all_vnodes();
2874 cache_lock_all_buckets();
2875 old_nchashtbl = nchashtbl;
2876 old_nchash = nchash;
2877 cache_changesize_set_temp(temptbl, temphash);
2878 for (i = 0; i <= old_nchash; i++) {
2879 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2880 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2882 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2883 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2887 cache_recalc_neg_min();
2888 cache_changesize_set_new(new_nchashtbl, new_nchash);
2889 cache_unlock_all_buckets();
2890 cache_unlock_all_vnodes();
2891 ncfreetbl(old_nchashtbl);
2896 * Remove all entries from and to a particular vnode.
2899 cache_purge_impl(struct vnode *vp)
2901 struct cache_freebatch batch;
2902 struct namecache *ncp;
2903 struct mtx *vlp, *vlp2;
2906 vlp = VP2VNODELOCK(vp);
2910 while (!LIST_EMPTY(&vp->v_cache_src)) {
2911 ncp = LIST_FIRST(&vp->v_cache_src);
2912 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2914 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2916 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2917 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2918 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2920 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2922 ncp = vp->v_cache_dd;
2924 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2925 ("lost dotdot link"));
2926 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2928 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2930 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2934 cache_free_batch(&batch);
2938 * Opportunistic check to see if there is anything to do.
2941 cache_has_entries(struct vnode *vp)
2944 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2945 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2951 cache_purge(struct vnode *vp)
2954 SDT_PROBE1(vfs, namecache, purge, done, vp);
2955 if (!cache_has_entries(vp))
2957 cache_purge_impl(vp);
2961 * Only to be used by vgone.
2964 cache_purge_vgone(struct vnode *vp)
2968 VNPASS(VN_IS_DOOMED(vp), vp);
2969 if (cache_has_entries(vp)) {
2970 cache_purge_impl(vp);
2975 * Serialize against a potential thread doing cache_purge.
2977 vlp = VP2VNODELOCK(vp);
2978 mtx_wait_unlocked(vlp);
2979 if (cache_has_entries(vp)) {
2980 cache_purge_impl(vp);
2987 * Remove all negative entries for a particular directory vnode.
2990 cache_purge_negative(struct vnode *vp)
2992 struct cache_freebatch batch;
2993 struct namecache *ncp, *nnp;
2996 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2997 if (LIST_EMPTY(&vp->v_cache_src))
3000 vlp = VP2VNODELOCK(vp);
3002 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
3003 if (!(ncp->nc_flag & NCF_NEGATIVE))
3005 cache_zap_negative_locked_vnode_kl(ncp, vp);
3006 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
3009 cache_free_batch(&batch);
3013 * Entry points for modifying VOP operations.
3016 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
3017 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
3020 ASSERT_VOP_IN_SEQC(fdvp);
3021 ASSERT_VOP_IN_SEQC(fvp);
3022 ASSERT_VOP_IN_SEQC(tdvp);
3024 ASSERT_VOP_IN_SEQC(tvp);
3029 KASSERT(!cache_remove_cnp(tdvp, tcnp),
3030 ("%s: lingering negative entry", __func__));
3032 cache_remove_cnp(tdvp, tcnp);
3038 * Historically renaming was always purging all revelang entries,
3039 * but that's quite wasteful. In particular turns out that in many cases
3040 * the target file is immediately accessed after rename, inducing a cache
3043 * Recode this to reduce relocking and reuse the existing entry (if any)
3044 * instead of just removing it above and allocating a new one here.
3046 cache_enter(tdvp, fvp, tcnp);
3050 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
3053 ASSERT_VOP_IN_SEQC(dvp);
3054 ASSERT_VOP_IN_SEQC(vp);
3060 * Validate that if an entry exists it matches.
3063 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
3065 struct namecache *ncp;
3069 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
3070 if (CK_SLIST_EMPTY(NCHHASH(hash)))
3072 blp = HASH2BUCKETLOCK(hash);
3074 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3075 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3076 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
3077 if (ncp->nc_vp != vp)
3078 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
3079 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3086 cache_assert_no_entries(struct vnode *vp)
3089 VNPASS(TAILQ_EMPTY(&vp->v_cache_dst), vp);
3090 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
3091 VNPASS(vp->v_cache_dd == NULL, vp);
3096 * Flush all entries referencing a particular filesystem.
3099 cache_purgevfs(struct mount *mp)
3101 struct vnode *vp, *mvp;
3102 size_t visited __sdt_used, purged __sdt_used;
3104 visited = purged = 0;
3106 * Somewhat wasteful iteration over all vnodes. Would be better to
3107 * support filtering and avoid the interlock to begin with.
3109 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3111 if (!cache_has_entries(vp)) {
3122 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3126 * Perform canonical checks and cache lookup and pass on to filesystem
3127 * through the vop_cachedlookup only if needed.
3131 vfs_cache_lookup(struct vop_lookup_args *ap)
3135 struct vnode **vpp = ap->a_vpp;
3136 struct componentname *cnp = ap->a_cnp;
3137 int flags = cnp->cn_flags;
3142 if (dvp->v_type != VDIR)
3145 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3146 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3149 error = vn_dir_check_exec(dvp, cnp);
3153 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3155 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3161 /* Implementation of the getcwd syscall. */
3163 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3169 buflen = uap->buflen;
3170 if (__predict_false(buflen < 2))
3172 if (buflen > MAXPATHLEN)
3173 buflen = MAXPATHLEN;
3175 buf = uma_zalloc(namei_zone, M_WAITOK);
3176 error = vn_getcwd(buf, &retbuf, &buflen);
3178 error = copyout(retbuf, uap->buf, buflen);
3179 uma_zfree(namei_zone, buf);
3184 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3190 pwd = pwd_get_smr();
3191 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3193 VFS_SMR_ASSERT_NOT_ENTERED();
3195 pwd = pwd_hold(curthread);
3196 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3202 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3209 * Canonicalize a path by walking it forward and back.
3212 * - Nothing guarantees the integrity of the entire chain. Consider the case
3213 * where the path "foo/bar/baz/qux" is passed, but "bar" is moved out of
3214 * "foo" into "quux" during the backwards walk. The result will be
3215 * "quux/bar/baz/qux", which could not have been obtained by an incremental
3216 * walk in userspace. Moreover, the path we return is inaccessible if the
3217 * calling thread lacks permission to traverse "quux".
3220 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3221 size_t size, int flags, enum uio_seg pathseg)
3223 struct nameidata nd;
3224 char *retbuf, *freebuf;
3229 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | WANTPARENT | AUDITVNODE1,
3230 pathseg, path, fd, &cap_fstat_rights);
3231 if ((error = namei(&nd)) != 0)
3234 if (nd.ni_vp->v_type == VREG && nd.ni_dvp->v_type != VDIR &&
3235 (nd.ni_vp->v_vflag & VV_ROOT) != 0) {
3237 * This happens if vp is a file mount. The call to
3238 * vn_fullpath_hardlink can panic if path resolution can't be
3239 * handled without the directory.
3241 * To resolve this, we find the vnode which was mounted on -
3242 * this should have a unique global path since we disallow
3243 * mounting on linked files.
3245 struct vnode *covered_vp;
3246 error = vn_lock(nd.ni_vp, LK_SHARED);
3249 covered_vp = nd.ni_vp->v_mount->mnt_vnodecovered;
3251 VOP_UNLOCK(nd.ni_vp);
3252 error = vn_fullpath(covered_vp, &retbuf, &freebuf);
3255 error = vn_fullpath_hardlink(nd.ni_vp, nd.ni_dvp, nd.ni_cnd.cn_nameptr,
3256 nd.ni_cnd.cn_namelen, &retbuf, &freebuf, &size);
3259 error = copyout(retbuf, buf, size);
3260 free(freebuf, M_TEMP);
3270 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3273 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3274 uap->flags, UIO_USERSPACE));
3278 * Retrieve the full filesystem path that correspond to a vnode from the name
3279 * cache (if available)
3282 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3289 if (__predict_false(vp == NULL))
3292 buflen = MAXPATHLEN;
3293 buf = malloc(buflen, M_TEMP, M_WAITOK);
3295 pwd = pwd_get_smr();
3296 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3297 VFS_SMR_ASSERT_NOT_ENTERED();
3299 pwd = pwd_hold(curthread);
3300 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3311 * This function is similar to vn_fullpath, but it attempts to lookup the
3312 * pathname relative to the global root mount point. This is required for the
3313 * auditing sub-system, as audited pathnames must be absolute, relative to the
3314 * global root mount point.
3317 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3323 if (__predict_false(vp == NULL))
3325 buflen = MAXPATHLEN;
3326 buf = malloc(buflen, M_TEMP, M_WAITOK);
3328 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3329 VFS_SMR_ASSERT_NOT_ENTERED();
3331 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3340 static struct namecache *
3341 vn_dd_from_dst(struct vnode *vp)
3343 struct namecache *ncp;
3345 cache_assert_vnode_locked(vp);
3346 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3347 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3354 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3357 struct namecache *ncp;
3361 vlp = VP2VNODELOCK(*vp);
3363 ncp = (*vp)->v_cache_dd;
3364 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3365 KASSERT(ncp == vn_dd_from_dst(*vp),
3366 ("%s: mismatch for dd entry (%p != %p)", __func__,
3367 ncp, vn_dd_from_dst(*vp)));
3369 ncp = vn_dd_from_dst(*vp);
3372 if (*buflen < ncp->nc_nlen) {
3375 counter_u64_add(numfullpathfail4, 1);
3377 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3381 *buflen -= ncp->nc_nlen;
3382 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3383 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3392 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3395 vn_lock(*vp, LK_SHARED | LK_RETRY);
3396 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3399 counter_u64_add(numfullpathfail2, 1);
3400 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3405 if (VN_IS_DOOMED(dvp)) {
3406 /* forced unmount */
3409 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3413 * *vp has its use count incremented still.
3420 * Resolve a directory to a pathname.
3422 * The name of the directory can always be found in the namecache or fetched
3423 * from the filesystem. There is also guaranteed to be only one parent, meaning
3424 * we can just follow vnodes up until we find the root.
3426 * The vnode must be referenced.
3429 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3430 size_t *len, size_t addend)
3432 #ifdef KDTRACE_HOOKS
3433 struct vnode *startvp = vp;
3438 bool slash_prefixed;
3440 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3441 VNPASS(vp->v_usecount > 0, vp);
3445 slash_prefixed = true;
3450 slash_prefixed = false;
3455 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3456 counter_u64_add(numfullpathcalls, 1);
3457 while (vp != rdir && vp != rootvnode) {
3459 * The vp vnode must be already fully constructed,
3460 * since it is either found in namecache or obtained
3461 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3462 * without obtaining the vnode lock.
3464 if ((vp->v_vflag & VV_ROOT) != 0) {
3465 vn_lock(vp, LK_RETRY | LK_SHARED);
3468 * With the vnode locked, check for races with
3469 * unmount, forced or not. Note that we
3470 * already verified that vp is not equal to
3471 * the root vnode, which means that
3472 * mnt_vnodecovered can be NULL only for the
3475 if (VN_IS_DOOMED(vp) ||
3476 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3477 vp1->v_mountedhere != vp->v_mount) {
3480 SDT_PROBE3(vfs, namecache, fullpath, return,
3490 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3491 error = vn_vptocnp(&vp, buf, &buflen);
3497 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3501 buf[--buflen] = '/';
3502 slash_prefixed = true;
3506 if (!slash_prefixed) {
3509 counter_u64_add(numfullpathfail4, 1);
3510 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3514 buf[--buflen] = '/';
3516 counter_u64_add(numfullpathfound, 1);
3519 *retbuf = buf + buflen;
3520 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3527 * Resolve an arbitrary vnode to a pathname.
3530 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3531 * resolve to a different path than the one used to find it
3532 * - namecache is not mandatory, meaning names are not guaranteed to be added
3533 * (in which case resolving fails)
3535 static void __inline
3536 cache_rev_failed_impl(int *reason, int line)
3541 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3544 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3545 char **retbuf, size_t *buflen, size_t addend)
3547 #ifdef KDTRACE_HOOKS
3548 struct vnode *startvp = vp;
3552 struct namecache *ncp;
3556 #ifdef KDTRACE_HOOKS
3559 seqc_t vp_seqc, tvp_seqc;
3562 VFS_SMR_ASSERT_ENTERED();
3564 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3569 orig_buflen = *buflen;
3572 MPASS(*buflen >= 2);
3574 buf[*buflen] = '\0';
3577 if (vp == rdir || vp == rootvnode) {
3585 #ifdef KDTRACE_HOOKS
3589 ncp = NULL; /* for sdt probe down below */
3590 vp_seqc = vn_seqc_read_any(vp);
3591 if (seqc_in_modify(vp_seqc)) {
3592 cache_rev_failed(&reason);
3597 #ifdef KDTRACE_HOOKS
3600 if ((vp->v_vflag & VV_ROOT) != 0) {
3601 mp = atomic_load_ptr(&vp->v_mount);
3603 cache_rev_failed(&reason);
3606 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3607 tvp_seqc = vn_seqc_read_any(tvp);
3608 if (seqc_in_modify(tvp_seqc)) {
3609 cache_rev_failed(&reason);
3612 if (!vn_seqc_consistent(vp, vp_seqc)) {
3613 cache_rev_failed(&reason);
3620 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3622 cache_rev_failed(&reason);
3625 nc_flag = atomic_load_char(&ncp->nc_flag);
3626 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3627 cache_rev_failed(&reason);
3630 if (ncp->nc_nlen >= *buflen) {
3631 cache_rev_failed(&reason);
3635 *buflen -= ncp->nc_nlen;
3636 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3640 tvp_seqc = vn_seqc_read_any(tvp);
3641 if (seqc_in_modify(tvp_seqc)) {
3642 cache_rev_failed(&reason);
3645 if (!vn_seqc_consistent(vp, vp_seqc)) {
3646 cache_rev_failed(&reason);
3650 * Acquire fence provided by vn_seqc_read_any above.
3652 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3653 cache_rev_failed(&reason);
3656 if (!cache_ncp_canuse(ncp)) {
3657 cache_rev_failed(&reason);
3662 if (vp == rdir || vp == rootvnode)
3667 *retbuf = buf + *buflen;
3668 *buflen = orig_buflen - *buflen + addend;
3669 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3673 *buflen = orig_buflen;
3674 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3680 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3683 size_t orig_buflen, addend;
3689 orig_buflen = *buflen;
3693 if (vp->v_type != VDIR) {
3695 buf[*buflen] = '\0';
3696 error = vn_vptocnp(&vp, buf, buflen);
3705 addend = orig_buflen - *buflen;
3708 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3712 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3714 * Since the namecache does not track hardlinks, the caller is expected to
3715 * first look up the target vnode with WANTPARENT flag passed to namei to get
3718 * Then we have 2 cases:
3719 * - if the found vnode is a directory, the path can be constructed just by
3720 * following names up the chain
3721 * - otherwise we populate the buffer with the saved name and start resolving
3725 vn_fullpath_hardlink(struct vnode *vp, struct vnode *dvp,
3726 const char *hrdl_name, size_t hrdl_name_length,
3727 char **retbuf, char **freebuf, size_t *buflen)
3733 __enum_uint8(vtype) type;
3737 if (*buflen > MAXPATHLEN)
3738 *buflen = MAXPATHLEN;
3740 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3745 * Check for VBAD to work around the vp_crossmp bug in lookup().
3747 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3748 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3749 * If the type is VDIR (like in this very case) we can skip looking
3750 * at ni_dvp in the first place. However, since vnodes get passed here
3751 * unlocked the target may transition to doomed state (type == VBAD)
3752 * before we get to evaluate the condition. If this happens, we will
3753 * populate part of the buffer and descend to vn_fullpath_dir with
3754 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3756 type = atomic_load_8(&vp->v_type);
3762 addend = hrdl_name_length + 2;
3763 if (*buflen < addend) {
3768 tmpbuf = buf + *buflen;
3770 memcpy(&tmpbuf[1], hrdl_name, hrdl_name_length);
3771 tmpbuf[addend - 1] = '\0';
3776 pwd = pwd_get_smr();
3777 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3779 VFS_SMR_ASSERT_NOT_ENTERED();
3781 pwd = pwd_hold(curthread);
3783 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3799 vn_dir_dd_ino(struct vnode *vp)
3801 struct namecache *ncp;
3806 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3807 vlp = VP2VNODELOCK(vp);
3809 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3810 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3813 vs = vget_prep(ddvp);
3815 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3824 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3826 struct namecache *ncp;
3830 vlp = VP2VNODELOCK(vp);
3832 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3833 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3839 l = min(ncp->nc_nlen, buflen - 1);
3840 memcpy(buf, ncp->nc_name, l);
3847 * This function updates path string to vnode's full global path
3848 * and checks the size of the new path string against the pathlen argument.
3850 * Requires a locked, referenced vnode.
3851 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3853 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3854 * because it falls back to the ".." lookup if the namecache lookup fails.
3857 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3860 struct nameidata nd;
3865 ASSERT_VOP_ELOCKED(vp, __func__);
3867 /* Construct global filesystem path from vp. */
3869 error = vn_fullpath_global(vp, &rpath, &fbuf);
3876 if (strlen(rpath) >= pathlen) {
3878 error = ENAMETOOLONG;
3883 * Re-lookup the vnode by path to detect a possible rename.
3884 * As a side effect, the vnode is relocked.
3885 * If vnode was renamed, return ENOENT.
3887 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3897 strcpy(path, rpath);
3909 * This is similar to vn_path_to_global_path but allows for regular
3910 * files which may not be present in the cache.
3912 * Requires a locked, referenced vnode.
3913 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3916 vn_path_to_global_path_hardlink(struct thread *td, struct vnode *vp,
3917 struct vnode *dvp, char *path, u_int pathlen, const char *leaf_name,
3920 struct nameidata nd;
3926 ASSERT_VOP_ELOCKED(vp, __func__);
3929 * Construct global filesystem path from dvp, vp and leaf
3934 error = vn_fullpath_hardlink(vp, dvp, leaf_name, leaf_length,
3935 &rpath, &fbuf, &len);
3942 if (strlen(rpath) >= pathlen) {
3944 error = ENAMETOOLONG;
3949 * Re-lookup the vnode by path to detect a possible rename.
3950 * As a side effect, the vnode is relocked.
3951 * If vnode was renamed, return ENOENT.
3953 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3963 strcpy(path, rpath);
3976 db_print_vpath(struct vnode *vp)
3979 while (vp != NULL) {
3980 db_printf("%p: ", vp);
3981 if (vp == rootvnode) {
3985 if (vp->v_vflag & VV_ROOT) {
3986 db_printf("<mount point>");
3987 vp = vp->v_mount->mnt_vnodecovered;
3989 struct namecache *ncp;
3993 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3996 for (i = 0; i < ncp->nc_nlen; i++)
3997 db_printf("%c", *ncn++);
4010 DB_SHOW_COMMAND(vpath, db_show_vpath)
4015 db_printf("usage: show vpath <struct vnode *>\n");
4019 vp = (struct vnode *)addr;
4025 static int cache_fast_lookup = 1;
4027 #define CACHE_FPL_FAILED -2020
4030 cache_vop_bad_vexec(struct vop_fplookup_vexec_args *v)
4032 vn_printf(v->a_vp, "no proper vop_fplookup_vexec\n");
4033 panic("no proper vop_fplookup_vexec");
4037 cache_vop_bad_symlink(struct vop_fplookup_symlink_args *v)
4039 vn_printf(v->a_vp, "no proper vop_fplookup_symlink\n");
4040 panic("no proper vop_fplookup_symlink");
4044 cache_vop_vector_register(struct vop_vector *v)
4049 if (v->vop_fplookup_vexec != NULL) {
4052 if (v->vop_fplookup_symlink != NULL) {
4061 v->vop_fplookup_vexec = cache_vop_bad_vexec;
4062 v->vop_fplookup_symlink = cache_vop_bad_symlink;
4066 printf("%s: invalid vop vector %p -- either all or none fplookup vops "
4067 "need to be provided", __func__, v);
4068 if (v->vop_fplookup_vexec == NULL) {
4069 printf("%s: missing vop_fplookup_vexec\n", __func__);
4071 if (v->vop_fplookup_symlink == NULL) {
4072 printf("%s: missing vop_fplookup_symlink\n", __func__);
4074 panic("bad vop vector %p", v);
4079 cache_validate_vop_vector(struct mount *mp, struct vop_vector *vops)
4084 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4087 if (vops->vop_fplookup_vexec == NULL ||
4088 vops->vop_fplookup_vexec == cache_vop_bad_vexec)
4089 panic("bad vop_fplookup_vexec on vector %p for filesystem %s",
4090 vops, mp->mnt_vfc->vfc_name);
4092 if (vops->vop_fplookup_symlink == NULL ||
4093 vops->vop_fplookup_symlink == cache_vop_bad_symlink)
4094 panic("bad vop_fplookup_symlink on vector %p for filesystem %s",
4095 vops, mp->mnt_vfc->vfc_name);
4100 cache_fast_lookup_enabled_recalc(void)
4106 mac_on = mac_vnode_check_lookup_enabled();
4107 mac_on |= mac_vnode_check_readlink_enabled();
4112 lookup_flag = atomic_load_int(&cache_fast_lookup);
4113 if (lookup_flag && !mac_on) {
4114 atomic_store_char(&cache_fast_lookup_enabled, true);
4116 atomic_store_char(&cache_fast_lookup_enabled, false);
4121 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
4125 old = atomic_load_int(&cache_fast_lookup);
4126 error = sysctl_handle_int(oidp, arg1, arg2, req);
4127 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
4128 cache_fast_lookup_enabled_recalc();
4131 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
4132 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
4135 * Components of nameidata (or objects it can point to) which may
4136 * need restoring in case fast path lookup fails.
4138 struct nameidata_outer {
4143 struct nameidata_saved {
4151 struct cache_fpl_debug {
4157 struct nameidata *ndp;
4158 struct componentname *cnp;
4165 struct nameidata_saved snd;
4166 struct nameidata_outer snd_outer;
4168 enum cache_fpl_status status:8;
4173 struct cache_fpl_debug debug;
4177 static bool cache_fplookup_mp_supported(struct mount *mp);
4178 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
4179 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
4180 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
4181 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
4182 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
4183 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
4184 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
4185 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
4186 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
4189 cache_fpl_cleanup_cnp(struct componentname *cnp)
4192 uma_zfree(namei_zone, cnp->cn_pnbuf);
4193 cnp->cn_pnbuf = NULL;
4194 cnp->cn_nameptr = NULL;
4197 static struct vnode *
4198 cache_fpl_handle_root(struct cache_fpl *fpl)
4200 struct nameidata *ndp;
4201 struct componentname *cnp;
4206 MPASS(*(cnp->cn_nameptr) == '/');
4208 cache_fpl_pathlen_dec(fpl);
4210 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4213 cache_fpl_pathlen_dec(fpl);
4214 } while (*(cnp->cn_nameptr) == '/');
4217 return (ndp->ni_rootdir);
4221 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
4224 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
4225 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
4229 cache_fpl_checkpoint(struct cache_fpl *fpl)
4233 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
4234 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4239 cache_fpl_restore_partial(struct cache_fpl *fpl)
4242 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4244 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4249 cache_fpl_restore_abort(struct cache_fpl *fpl)
4252 cache_fpl_restore_partial(fpl);
4254 * It is 0 on entry by API contract.
4256 fpl->ndp->ni_resflags = 0;
4257 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4258 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4262 #define cache_fpl_smr_assert_entered(fpl) ({ \
4263 struct cache_fpl *_fpl = (fpl); \
4264 MPASS(_fpl->in_smr == true); \
4265 VFS_SMR_ASSERT_ENTERED(); \
4267 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4268 struct cache_fpl *_fpl = (fpl); \
4269 MPASS(_fpl->in_smr == false); \
4270 VFS_SMR_ASSERT_NOT_ENTERED(); \
4273 cache_fpl_assert_status(struct cache_fpl *fpl)
4276 switch (fpl->status) {
4277 case CACHE_FPL_STATUS_UNSET:
4278 __assert_unreachable();
4280 case CACHE_FPL_STATUS_DESTROYED:
4281 case CACHE_FPL_STATUS_ABORTED:
4282 case CACHE_FPL_STATUS_PARTIAL:
4283 case CACHE_FPL_STATUS_HANDLED:
4288 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4289 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4290 #define cache_fpl_assert_status(fpl) do { } while (0)
4293 #define cache_fpl_smr_enter_initial(fpl) ({ \
4294 struct cache_fpl *_fpl = (fpl); \
4296 _fpl->in_smr = true; \
4299 #define cache_fpl_smr_enter(fpl) ({ \
4300 struct cache_fpl *_fpl = (fpl); \
4301 MPASS(_fpl->in_smr == false); \
4303 _fpl->in_smr = true; \
4306 #define cache_fpl_smr_exit(fpl) ({ \
4307 struct cache_fpl *_fpl = (fpl); \
4308 MPASS(_fpl->in_smr == true); \
4310 _fpl->in_smr = false; \
4314 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4317 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4318 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4319 ("%s: converting to abort from %d at %d, set at %d\n",
4320 __func__, fpl->status, line, fpl->line));
4322 cache_fpl_smr_assert_not_entered(fpl);
4323 fpl->status = CACHE_FPL_STATUS_ABORTED;
4325 return (CACHE_FPL_FAILED);
4328 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4330 static int __noinline
4331 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4333 struct nameidata *ndp;
4334 struct componentname *cnp;
4339 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4340 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4341 ("%s: converting to abort from %d at %d, set at %d\n",
4342 __func__, fpl->status, line, fpl->line));
4344 fpl->status = CACHE_FPL_STATUS_ABORTED;
4347 cache_fpl_smr_exit(fpl);
4348 cache_fpl_restore_abort(fpl);
4350 * Resolving symlinks overwrites data passed by the caller.
4353 if (ndp->ni_loopcnt > 0) {
4354 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4355 cache_fpl_cleanup_cnp(cnp);
4357 return (CACHE_FPL_FAILED);
4360 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4362 static int __noinline
4363 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4366 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4367 ("%s: setting to partial at %d, but already set to %d at %d\n",
4368 __func__, line, fpl->status, fpl->line));
4369 cache_fpl_smr_assert_entered(fpl);
4370 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4372 return (cache_fplookup_partial_setup(fpl));
4375 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4378 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4381 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4382 ("%s: setting to handled at %d, but already set to %d at %d\n",
4383 __func__, line, fpl->status, fpl->line));
4384 cache_fpl_smr_assert_not_entered(fpl);
4385 fpl->status = CACHE_FPL_STATUS_HANDLED;
4390 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4393 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4396 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4397 ("%s: setting to handled at %d, but already set to %d at %d\n",
4398 __func__, line, fpl->status, fpl->line));
4400 MPASS(error != CACHE_FPL_FAILED);
4401 cache_fpl_smr_assert_not_entered(fpl);
4402 fpl->status = CACHE_FPL_STATUS_HANDLED;
4409 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4412 cache_fpl_terminated(struct cache_fpl *fpl)
4415 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4418 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4419 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4420 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | ISRESTARTED | WILLBEDIR | \
4421 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | OPENREAD | \
4422 OPENWRITE | WANTIOCTLCAPS)
4424 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4425 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4427 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4428 "supported and internal flags overlap");
4431 cache_fpl_islastcn(struct nameidata *ndp)
4434 return (*ndp->ni_next == 0);
4438 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4441 MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4442 return (*(fpl->nulchar - 1) == '/');
4446 cache_fpl_isdotdot(struct componentname *cnp)
4449 if (cnp->cn_namelen == 2 &&
4450 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4456 cache_can_fplookup(struct cache_fpl *fpl)
4458 struct nameidata *ndp;
4459 struct componentname *cnp;
4466 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4467 cache_fpl_aborted_early(fpl);
4470 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4471 cache_fpl_aborted_early(fpl);
4474 if (IN_CAPABILITY_MODE(td)) {
4475 cache_fpl_aborted_early(fpl);
4478 if (AUDITING_TD(td)) {
4479 cache_fpl_aborted_early(fpl);
4482 if (ndp->ni_startdir != NULL) {
4483 cache_fpl_aborted_early(fpl);
4489 static int __noinline
4490 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4492 struct nameidata *ndp;
4493 struct componentname *cnp;
4500 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4501 if (__predict_false(error != 0)) {
4502 return (cache_fpl_aborted(fpl));
4504 fpl->fsearch = fsearch;
4505 if ((*vpp)->v_type != VDIR) {
4506 if (!((cnp->cn_flags & EMPTYPATH) != 0 && cnp->cn_pnbuf[0] == '\0')) {
4507 cache_fpl_smr_exit(fpl);
4508 return (cache_fpl_handled_error(fpl, ENOTDIR));
4514 static int __noinline
4515 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4518 struct componentname *cnp;
4524 cache_fpl_smr_exit(fpl);
4525 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4526 return (cache_fpl_handled_error(fpl, ENOENT));
4528 return (cache_fpl_aborted(fpl));
4532 * The target vnode is not supported, prepare for the slow path to take over.
4534 static int __noinline
4535 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4537 struct nameidata *ndp;
4538 struct componentname *cnp;
4548 dvp_seqc = fpl->dvp_seqc;
4550 if (!pwd_hold_smr(pwd)) {
4551 return (cache_fpl_aborted(fpl));
4555 * Note that seqc is checked before the vnode is locked, so by
4556 * the time regular lookup gets to it it may have moved.
4558 * Ultimately this does not affect correctness, any lookup errors
4559 * are userspace racing with itself. It is guaranteed that any
4560 * path which ultimately gets found could also have been found
4561 * by regular lookup going all the way in absence of concurrent
4564 dvs = vget_prep_smr(dvp);
4565 cache_fpl_smr_exit(fpl);
4566 if (__predict_false(dvs == VGET_NONE)) {
4568 return (cache_fpl_aborted(fpl));
4571 vget_finish_ref(dvp, dvs);
4572 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4575 return (cache_fpl_aborted(fpl));
4578 cache_fpl_restore_partial(fpl);
4580 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4581 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4582 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4586 ndp->ni_startdir = dvp;
4587 cnp->cn_flags |= MAKEENTRY;
4588 if (cache_fpl_islastcn(ndp))
4589 cnp->cn_flags |= ISLASTCN;
4590 if (cache_fpl_isdotdot(cnp))
4591 cnp->cn_flags |= ISDOTDOT;
4594 * Skip potential extra slashes parsing did not take care of.
4595 * cache_fplookup_skip_slashes explains the mechanism.
4597 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4600 cache_fpl_pathlen_dec(fpl);
4601 } while (*(cnp->cn_nameptr) == '/');
4604 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4606 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4607 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4608 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4609 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4616 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4618 struct componentname *cnp;
4625 tvp_seqc = fpl->tvp_seqc;
4627 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4628 lkflags = LK_SHARED;
4629 if ((cnp->cn_flags & LOCKSHARED) == 0)
4630 lkflags = LK_EXCLUSIVE;
4631 error = vget_finish(tvp, lkflags, tvs);
4632 if (__predict_false(error != 0)) {
4633 return (cache_fpl_aborted(fpl));
4636 vget_finish_ref(tvp, tvs);
4639 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4640 if ((cnp->cn_flags & LOCKLEAF) != 0)
4644 return (cache_fpl_aborted(fpl));
4647 return (cache_fpl_handled(fpl));
4651 * They want to possibly modify the state of the namecache.
4653 static int __noinline
4654 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4656 struct nameidata *ndp __diagused;
4657 struct componentname *cnp;
4659 struct vnode *dvp, *tvp;
4668 dvp_seqc = fpl->dvp_seqc;
4670 MPASS(*(cnp->cn_nameptr) != '/');
4671 MPASS(cache_fpl_islastcn(ndp));
4672 if ((cnp->cn_flags & LOCKPARENT) == 0)
4673 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4674 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4675 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4676 cnp->cn_nameiop == RENAME);
4677 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4678 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4680 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4681 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4685 * Regular lookup nulifies the slash, which we don't do here.
4686 * Don't take chances with filesystem routines seeing it for
4689 if (cache_fpl_istrailingslash(fpl)) {
4690 return (cache_fpl_partial(fpl));
4693 mp = atomic_load_ptr(&dvp->v_mount);
4694 if (__predict_false(mp == NULL)) {
4695 return (cache_fpl_aborted(fpl));
4698 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4699 cache_fpl_smr_exit(fpl);
4701 * Original code keeps not checking for CREATE which
4702 * might be a bug. For now let the old lookup decide.
4704 if (cnp->cn_nameiop == CREATE) {
4705 return (cache_fpl_aborted(fpl));
4707 return (cache_fpl_handled_error(fpl, EROFS));
4710 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4711 cache_fpl_smr_exit(fpl);
4712 return (cache_fpl_handled_error(fpl, EEXIST));
4716 * Secure access to dvp; check cache_fplookup_partial_setup for
4719 * XXX At least UFS requires its lookup routine to be called for
4720 * the last path component, which leads to some level of complication
4722 * - the target routine always locks the target vnode, but our caller
4723 * may not need it locked
4724 * - some of the VOP machinery asserts that the parent is locked, which
4725 * once more may be not required
4727 * TODO: add a flag for filesystems which don't need this.
4729 dvs = vget_prep_smr(dvp);
4730 cache_fpl_smr_exit(fpl);
4731 if (__predict_false(dvs == VGET_NONE)) {
4732 return (cache_fpl_aborted(fpl));
4735 vget_finish_ref(dvp, dvs);
4736 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4738 return (cache_fpl_aborted(fpl));
4741 error = vn_lock(dvp, LK_EXCLUSIVE);
4742 if (__predict_false(error != 0)) {
4744 return (cache_fpl_aborted(fpl));
4748 cnp->cn_flags |= ISLASTCN;
4750 cnp->cn_flags |= MAKEENTRY;
4751 if (cache_fpl_isdotdot(cnp))
4752 cnp->cn_flags |= ISDOTDOT;
4753 cnp->cn_lkflags = LK_EXCLUSIVE;
4754 error = VOP_LOOKUP(dvp, &tvp, cnp);
4762 return (cache_fpl_handled_error(fpl, error));
4765 return (cache_fpl_aborted(fpl));
4771 MPASS(error == EJUSTRETURN);
4772 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4775 return (cache_fpl_handled(fpl));
4779 * There are very hairy corner cases concerning various flag combinations
4780 * and locking state. In particular here we only hold one lock instead of
4783 * Skip the complexity as it is of no significance for normal workloads.
4785 if (__predict_false(tvp == dvp)) {
4788 return (cache_fpl_aborted(fpl));
4792 * If they want the symlink itself we are fine, but if they want to
4793 * follow it regular lookup has to be engaged.
4795 if (tvp->v_type == VLNK) {
4796 if ((cnp->cn_flags & FOLLOW) != 0) {
4799 return (cache_fpl_aborted(fpl));
4804 * Since we expect this to be the terminal vnode it should almost never
4807 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4810 return (cache_fpl_aborted(fpl));
4813 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4816 return (cache_fpl_handled_error(fpl, EEXIST));
4819 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4823 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4827 return (cache_fpl_handled(fpl));
4830 static int __noinline
4831 cache_fplookup_modifying(struct cache_fpl *fpl)
4833 struct nameidata *ndp;
4837 if (!cache_fpl_islastcn(ndp)) {
4838 return (cache_fpl_partial(fpl));
4840 return (cache_fplookup_final_modifying(fpl));
4843 static int __noinline
4844 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4846 struct componentname *cnp;
4847 enum vgetstate dvs, tvs;
4848 struct vnode *dvp, *tvp;
4854 dvp_seqc = fpl->dvp_seqc;
4857 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4860 * This is less efficient than it can be for simplicity.
4862 dvs = vget_prep_smr(dvp);
4863 if (__predict_false(dvs == VGET_NONE)) {
4864 return (cache_fpl_aborted(fpl));
4866 tvs = vget_prep_smr(tvp);
4867 if (__predict_false(tvs == VGET_NONE)) {
4868 cache_fpl_smr_exit(fpl);
4869 vget_abort(dvp, dvs);
4870 return (cache_fpl_aborted(fpl));
4873 cache_fpl_smr_exit(fpl);
4875 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4876 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4877 if (__predict_false(error != 0)) {
4878 vget_abort(tvp, tvs);
4879 return (cache_fpl_aborted(fpl));
4882 vget_finish_ref(dvp, dvs);
4885 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4886 vget_abort(tvp, tvs);
4887 if ((cnp->cn_flags & LOCKPARENT) != 0)
4891 return (cache_fpl_aborted(fpl));
4894 error = cache_fplookup_final_child(fpl, tvs);
4895 if (__predict_false(error != 0)) {
4896 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4897 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4898 if ((cnp->cn_flags & LOCKPARENT) != 0)
4905 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4910 cache_fplookup_final(struct cache_fpl *fpl)
4912 struct componentname *cnp;
4914 struct vnode *dvp, *tvp;
4919 dvp_seqc = fpl->dvp_seqc;
4922 MPASS(*(cnp->cn_nameptr) != '/');
4924 if (cnp->cn_nameiop != LOOKUP) {
4925 return (cache_fplookup_final_modifying(fpl));
4928 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4929 return (cache_fplookup_final_withparent(fpl));
4931 tvs = vget_prep_smr(tvp);
4932 if (__predict_false(tvs == VGET_NONE)) {
4933 return (cache_fpl_partial(fpl));
4936 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4937 cache_fpl_smr_exit(fpl);
4938 vget_abort(tvp, tvs);
4939 return (cache_fpl_aborted(fpl));
4942 cache_fpl_smr_exit(fpl);
4943 return (cache_fplookup_final_child(fpl, tvs));
4947 * Comment from locked lookup:
4948 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4949 * directory, e.g. like "/." or ".".
4951 static int __noinline
4952 cache_fplookup_degenerate(struct cache_fpl *fpl)
4954 struct componentname *cnp;
4962 fpl->tvp = fpl->dvp;
4963 fpl->tvp_seqc = fpl->dvp_seqc;
4969 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4971 ("%s: encountered non-slash; string [%s]\n", __func__,
4976 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4977 cache_fpl_smr_exit(fpl);
4978 return (cache_fpl_handled_error(fpl, EISDIR));
4981 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4982 return (cache_fplookup_final_withparent(fpl));
4985 dvs = vget_prep_smr(dvp);
4986 cache_fpl_smr_exit(fpl);
4987 if (__predict_false(dvs == VGET_NONE)) {
4988 return (cache_fpl_aborted(fpl));
4991 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4992 lkflags = LK_SHARED;
4993 if ((cnp->cn_flags & LOCKSHARED) == 0)
4994 lkflags = LK_EXCLUSIVE;
4995 error = vget_finish(dvp, lkflags, dvs);
4996 if (__predict_false(error != 0)) {
4997 return (cache_fpl_aborted(fpl));
5000 vget_finish_ref(dvp, dvs);
5002 return (cache_fpl_handled(fpl));
5005 static int __noinline
5006 cache_fplookup_emptypath(struct cache_fpl *fpl)
5008 struct nameidata *ndp;
5009 struct componentname *cnp;
5014 fpl->tvp = fpl->dvp;
5015 fpl->tvp_seqc = fpl->dvp_seqc;
5021 MPASS(*cnp->cn_pnbuf == '\0');
5023 if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
5024 cache_fpl_smr_exit(fpl);
5025 return (cache_fpl_handled_error(fpl, ENOENT));
5028 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
5030 tvs = vget_prep_smr(tvp);
5031 cache_fpl_smr_exit(fpl);
5032 if (__predict_false(tvs == VGET_NONE)) {
5033 return (cache_fpl_aborted(fpl));
5036 if ((cnp->cn_flags & LOCKLEAF) != 0) {
5037 lkflags = LK_SHARED;
5038 if ((cnp->cn_flags & LOCKSHARED) == 0)
5039 lkflags = LK_EXCLUSIVE;
5040 error = vget_finish(tvp, lkflags, tvs);
5041 if (__predict_false(error != 0)) {
5042 return (cache_fpl_aborted(fpl));
5045 vget_finish_ref(tvp, tvs);
5048 ndp->ni_resflags |= NIRES_EMPTYPATH;
5049 return (cache_fpl_handled(fpl));
5052 static int __noinline
5053 cache_fplookup_noentry(struct cache_fpl *fpl)
5055 struct nameidata *ndp;
5056 struct componentname *cnp;
5058 struct vnode *dvp, *tvp;
5065 dvp_seqc = fpl->dvp_seqc;
5067 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
5068 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
5069 if (cnp->cn_nameiop == LOOKUP)
5070 MPASS((cnp->cn_flags & NOCACHE) == 0);
5071 MPASS(!cache_fpl_isdotdot(cnp));
5074 * Hack: delayed name len checking.
5076 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5077 cache_fpl_smr_exit(fpl);
5078 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5081 if (cnp->cn_nameptr[0] == '/') {
5082 return (cache_fplookup_skip_slashes(fpl));
5085 if (cnp->cn_pnbuf[0] == '\0') {
5086 return (cache_fplookup_emptypath(fpl));
5089 if (cnp->cn_nameptr[0] == '\0') {
5090 if (fpl->tvp == NULL) {
5091 return (cache_fplookup_degenerate(fpl));
5093 return (cache_fplookup_trailingslash(fpl));
5096 if (cnp->cn_nameiop != LOOKUP) {
5098 return (cache_fplookup_modifying(fpl));
5102 * Only try to fill in the component if it is the last one,
5103 * otherwise not only there may be several to handle but the
5104 * walk may be complicated.
5106 if (!cache_fpl_islastcn(ndp)) {
5107 return (cache_fpl_partial(fpl));
5111 * Regular lookup nulifies the slash, which we don't do here.
5112 * Don't take chances with filesystem routines seeing it for
5115 if (cache_fpl_istrailingslash(fpl)) {
5116 return (cache_fpl_partial(fpl));
5120 * Secure access to dvp; check cache_fplookup_partial_setup for
5123 dvs = vget_prep_smr(dvp);
5124 cache_fpl_smr_exit(fpl);
5125 if (__predict_false(dvs == VGET_NONE)) {
5126 return (cache_fpl_aborted(fpl));
5129 vget_finish_ref(dvp, dvs);
5130 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5132 return (cache_fpl_aborted(fpl));
5135 error = vn_lock(dvp, LK_SHARED);
5136 if (__predict_false(error != 0)) {
5138 return (cache_fpl_aborted(fpl));
5143 * TODO: provide variants which don't require locking either vnode.
5145 cnp->cn_flags |= ISLASTCN | MAKEENTRY;
5146 cnp->cn_lkflags = LK_SHARED;
5147 if ((cnp->cn_flags & LOCKSHARED) == 0) {
5148 cnp->cn_lkflags = LK_EXCLUSIVE;
5150 error = VOP_LOOKUP(dvp, &tvp, cnp);
5158 return (cache_fpl_handled_error(fpl, error));
5161 return (cache_fpl_aborted(fpl));
5167 MPASS(error == EJUSTRETURN);
5168 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5170 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5173 return (cache_fpl_handled(fpl));
5176 if (tvp->v_type == VLNK) {
5177 if ((cnp->cn_flags & FOLLOW) != 0) {
5180 return (cache_fpl_aborted(fpl));
5184 if (__predict_false(cache_fplookup_is_mp(fpl))) {
5187 return (cache_fpl_aborted(fpl));
5190 if ((cnp->cn_flags & LOCKLEAF) == 0) {
5194 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5196 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5199 return (cache_fpl_handled(fpl));
5202 static int __noinline
5203 cache_fplookup_dot(struct cache_fpl *fpl)
5207 MPASS(!seqc_in_modify(fpl->dvp_seqc));
5209 if (__predict_false(fpl->dvp->v_type != VDIR)) {
5210 cache_fpl_smr_exit(fpl);
5211 return (cache_fpl_handled_error(fpl, ENOTDIR));
5215 * Just re-assign the value. seqc will be checked later for the first
5216 * non-dot path component in line and/or before deciding to return the
5219 fpl->tvp = fpl->dvp;
5220 fpl->tvp_seqc = fpl->dvp_seqc;
5222 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
5225 if (cache_fplookup_is_mp(fpl)) {
5226 error = cache_fplookup_cross_mount(fpl);
5231 static int __noinline
5232 cache_fplookup_dotdot(struct cache_fpl *fpl)
5234 struct nameidata *ndp;
5235 struct componentname *cnp;
5236 struct namecache *ncp;
5245 MPASS(cache_fpl_isdotdot(cnp));
5248 * XXX this is racy the same way regular lookup is
5250 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5252 if (dvp == pr->pr_root)
5255 if (dvp == ndp->ni_rootdir ||
5256 dvp == ndp->ni_topdir ||
5260 fpl->tvp_seqc = vn_seqc_read_any(dvp);
5261 if (seqc_in_modify(fpl->tvp_seqc)) {
5262 return (cache_fpl_aborted(fpl));
5267 if ((dvp->v_vflag & VV_ROOT) != 0) {
5270 * The opposite of climb mount is needed here.
5272 return (cache_fpl_partial(fpl));
5275 if (__predict_false(dvp->v_type != VDIR)) {
5276 cache_fpl_smr_exit(fpl);
5277 return (cache_fpl_handled_error(fpl, ENOTDIR));
5280 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5282 return (cache_fpl_aborted(fpl));
5285 nc_flag = atomic_load_char(&ncp->nc_flag);
5286 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5287 if ((nc_flag & NCF_NEGATIVE) != 0)
5288 return (cache_fpl_aborted(fpl));
5289 fpl->tvp = ncp->nc_vp;
5291 fpl->tvp = ncp->nc_dvp;
5294 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5295 if (seqc_in_modify(fpl->tvp_seqc)) {
5296 return (cache_fpl_partial(fpl));
5300 * Acquire fence provided by vn_seqc_read_any above.
5302 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5303 return (cache_fpl_aborted(fpl));
5306 if (!cache_ncp_canuse(ncp)) {
5307 return (cache_fpl_aborted(fpl));
5313 static int __noinline
5314 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5316 u_char nc_flag __diagused;
5320 nc_flag = atomic_load_char(&ncp->nc_flag);
5321 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5324 * If they want to create an entry we need to replace this one.
5326 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5328 return (cache_fplookup_modifying(fpl));
5330 neg_promote = cache_neg_hit_prep(ncp);
5331 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5332 cache_neg_hit_abort(ncp);
5333 return (cache_fpl_partial(fpl));
5336 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5338 cache_neg_hit_finish(ncp);
5339 cache_fpl_smr_exit(fpl);
5340 return (cache_fpl_handled_error(fpl, ENOENT));
5344 * Resolve a symlink. Called by filesystem-specific routines.
5347 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5350 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5352 struct nameidata *ndp;
5353 struct componentname *cnp;
5359 if (__predict_false(len == 0)) {
5363 if (__predict_false(len > MAXPATHLEN - 2)) {
5364 if (cache_fpl_istrailingslash(fpl)) {
5369 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5371 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5372 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5373 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5374 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5378 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5379 return (ENAMETOOLONG);
5382 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5387 if (ndp->ni_pathlen > 1) {
5388 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5390 if (cache_fpl_istrailingslash(fpl)) {
5392 cnp->cn_pnbuf[len] = '/';
5393 cnp->cn_pnbuf[len + 1] = '\0';
5395 cnp->cn_pnbuf[len] = '\0';
5398 bcopy(string, cnp->cn_pnbuf, len);
5400 ndp->ni_pathlen += adjust;
5401 cache_fpl_pathlen_add(fpl, adjust);
5402 cnp->cn_nameptr = cnp->cn_pnbuf;
5403 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5408 static int __noinline
5409 cache_fplookup_symlink(struct cache_fpl *fpl)
5412 struct nameidata *ndp;
5413 struct componentname *cnp;
5414 struct vnode *dvp, *tvp;
5422 if (cache_fpl_islastcn(ndp)) {
5423 if ((cnp->cn_flags & FOLLOW) == 0) {
5424 return (cache_fplookup_final(fpl));
5428 mp = atomic_load_ptr(&dvp->v_mount);
5429 if (__predict_false(mp == NULL)) {
5430 return (cache_fpl_aborted(fpl));
5434 * Note this check races against setting the flag just like regular
5437 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5438 cache_fpl_smr_exit(fpl);
5439 return (cache_fpl_handled_error(fpl, EACCES));
5442 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5443 if (__predict_false(error != 0)) {
5446 return (cache_fpl_partial(fpl));
5450 cache_fpl_smr_exit(fpl);
5451 return (cache_fpl_handled_error(fpl, error));
5453 return (cache_fpl_aborted(fpl));
5457 if (*(cnp->cn_nameptr) == '/') {
5458 fpl->dvp = cache_fpl_handle_root(fpl);
5459 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5460 if (seqc_in_modify(fpl->dvp_seqc)) {
5461 return (cache_fpl_aborted(fpl));
5464 * The main loop assumes that ->dvp points to a vnode belonging
5465 * to a filesystem which can do lockless lookup, but the absolute
5466 * symlink can be wandering off to one which does not.
5468 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5469 if (__predict_false(mp == NULL)) {
5470 return (cache_fpl_aborted(fpl));
5472 if (!cache_fplookup_mp_supported(mp)) {
5473 cache_fpl_checkpoint(fpl);
5474 return (cache_fpl_partial(fpl));
5481 cache_fplookup_next(struct cache_fpl *fpl)
5483 struct componentname *cnp;
5484 struct namecache *ncp;
5485 struct vnode *dvp, *tvp;
5494 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5495 if (cnp->cn_namelen == 1) {
5496 return (cache_fplookup_dot(fpl));
5498 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5499 return (cache_fplookup_dotdot(fpl));
5503 MPASS(!cache_fpl_isdotdot(cnp));
5505 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5506 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5507 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5511 if (__predict_false(ncp == NULL)) {
5512 return (cache_fplookup_noentry(fpl));
5515 tvp = atomic_load_ptr(&ncp->nc_vp);
5516 nc_flag = atomic_load_char(&ncp->nc_flag);
5517 if ((nc_flag & NCF_NEGATIVE) != 0) {
5518 return (cache_fplookup_neg(fpl, ncp, hash));
5521 if (!cache_ncp_canuse(ncp)) {
5522 return (cache_fpl_partial(fpl));
5526 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5527 if (seqc_in_modify(fpl->tvp_seqc)) {
5528 return (cache_fpl_partial(fpl));
5531 counter_u64_add(numposhits, 1);
5532 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5535 if (cache_fplookup_is_mp(fpl)) {
5536 error = cache_fplookup_cross_mount(fpl);
5542 cache_fplookup_mp_supported(struct mount *mp)
5546 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5552 * Walk up the mount stack (if any).
5554 * Correctness is provided in the following ways:
5555 * - all vnodes are protected from freeing with SMR
5556 * - struct mount objects are type stable making them always safe to access
5557 * - stability of the particular mount is provided by busying it
5558 * - relationship between the vnode which is mounted on and the mount is
5559 * verified with the vnode sequence counter after busying
5560 * - association between root vnode of the mount and the mount is protected
5563 * From that point on we can read the sequence counter of the root vnode
5564 * and get the next mount on the stack (if any) using the same protection.
5566 * By the end of successful walk we are guaranteed the reached state was
5567 * indeed present at least at some point which matches the regular lookup.
5569 static int __noinline
5570 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5572 struct mount *mp, *prev_mp;
5573 struct mount_pcpu *mpcpu, *prev_mpcpu;
5578 vp_seqc = fpl->tvp_seqc;
5580 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5581 mp = atomic_load_ptr(&vp->v_mountedhere);
5582 if (__predict_false(mp == NULL)) {
5588 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5589 if (prev_mp != NULL)
5590 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5591 return (cache_fpl_partial(fpl));
5593 if (prev_mp != NULL)
5594 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5595 if (!vn_seqc_consistent(vp, vp_seqc)) {
5596 vfs_op_thread_exit_crit(mp, mpcpu);
5597 return (cache_fpl_partial(fpl));
5599 if (!cache_fplookup_mp_supported(mp)) {
5600 vfs_op_thread_exit_crit(mp, mpcpu);
5601 return (cache_fpl_partial(fpl));
5603 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5605 vfs_op_thread_exit_crit(mp, mpcpu);
5606 return (cache_fpl_partial(fpl));
5608 vp_seqc = vn_seqc_read_any(vp);
5609 if (seqc_in_modify(vp_seqc)) {
5610 vfs_op_thread_exit_crit(mp, mpcpu);
5611 return (cache_fpl_partial(fpl));
5615 mp = atomic_load_ptr(&vp->v_mountedhere);
5620 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5622 fpl->tvp_seqc = vp_seqc;
5626 static int __noinline
5627 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5630 struct mount_pcpu *mpcpu;
5635 vp_seqc = fpl->tvp_seqc;
5637 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5638 mp = atomic_load_ptr(&vp->v_mountedhere);
5639 if (__predict_false(mp == NULL)) {
5643 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5644 return (cache_fpl_partial(fpl));
5646 if (!vn_seqc_consistent(vp, vp_seqc)) {
5647 vfs_op_thread_exit_crit(mp, mpcpu);
5648 return (cache_fpl_partial(fpl));
5650 if (!cache_fplookup_mp_supported(mp)) {
5651 vfs_op_thread_exit_crit(mp, mpcpu);
5652 return (cache_fpl_partial(fpl));
5654 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5655 if (__predict_false(vp == NULL)) {
5656 vfs_op_thread_exit_crit(mp, mpcpu);
5657 return (cache_fpl_partial(fpl));
5659 vp_seqc = vn_seqc_read_any(vp);
5660 vfs_op_thread_exit_crit(mp, mpcpu);
5661 if (seqc_in_modify(vp_seqc)) {
5662 return (cache_fpl_partial(fpl));
5664 mp = atomic_load_ptr(&vp->v_mountedhere);
5665 if (__predict_false(mp != NULL)) {
5667 * There are possibly more mount points on top.
5668 * Normally this does not happen so for simplicity just start
5671 return (cache_fplookup_climb_mount(fpl));
5675 fpl->tvp_seqc = vp_seqc;
5680 * Check if a vnode is mounted on.
5683 cache_fplookup_is_mp(struct cache_fpl *fpl)
5688 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5694 * The code was originally copy-pasted from regular lookup and despite
5695 * clean ups leaves performance on the table. Any modifications here
5696 * must take into account that in case off fallback the resulting
5697 * nameidata state has to be compatible with the original.
5701 * Debug ni_pathlen tracking.
5705 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5708 fpl->debug.ni_pathlen += n;
5709 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5710 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5714 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5717 fpl->debug.ni_pathlen -= n;
5718 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5719 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5723 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5726 cache_fpl_pathlen_add(fpl, 1);
5730 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5733 cache_fpl_pathlen_sub(fpl, 1);
5737 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5742 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5747 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5752 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5758 cache_fplookup_parse(struct cache_fpl *fpl)
5760 struct nameidata *ndp;
5761 struct componentname *cnp;
5771 * Find the end of this path component, it is either / or nul.
5773 * Store / as a temporary sentinel so that we only have one character
5774 * to test for. Pathnames tend to be short so this should not be
5775 * resulting in cache misses.
5777 * TODO: fix this to be word-sized.
5779 MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5780 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5781 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5782 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5783 fpl->nulchar, cnp->cn_pnbuf));
5784 KASSERT(*fpl->nulchar == '\0',
5785 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5787 hash = cache_get_hash_iter_start(dvp);
5788 *fpl->nulchar = '/';
5789 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5790 KASSERT(*cp != '\0',
5791 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5793 hash = cache_get_hash_iter(*cp, hash);
5796 *fpl->nulchar = '\0';
5797 fpl->hash = cache_get_hash_iter_finish(hash);
5799 cnp->cn_namelen = cp - cnp->cn_nameptr;
5800 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5804 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5805 * we are going to fail this lookup with ENAMETOOLONG (see below).
5807 if (cnp->cn_namelen <= NAME_MAX) {
5808 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5809 panic("%s: mismatched hash for [%s] len %ld", __func__,
5810 cnp->cn_nameptr, cnp->cn_namelen);
5816 * Hack: we have to check if the found path component's length exceeds
5817 * NAME_MAX. However, the condition is very rarely true and check can
5818 * be elided in the common case -- if an entry was found in the cache,
5819 * then it could not have been too long to begin with.
5825 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5827 struct nameidata *ndp;
5828 struct componentname *cnp;
5833 cnp->cn_nameptr = ndp->ni_next;
5834 KASSERT(*(cnp->cn_nameptr) == '/',
5835 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5836 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5838 cache_fpl_pathlen_dec(fpl);
5842 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5844 * Lockless lookup tries to elide checking for spurious slashes and should they
5845 * be present is guaranteed to fail to find an entry. In this case the caller
5846 * must check if the name starts with a slash and call this routine. It is
5847 * going to fast forward across the spurious slashes and set the state up for
5850 static int __noinline
5851 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5853 struct nameidata *ndp;
5854 struct componentname *cnp;
5859 MPASS(*(cnp->cn_nameptr) == '/');
5862 cache_fpl_pathlen_dec(fpl);
5863 } while (*(cnp->cn_nameptr) == '/');
5866 * Go back to one slash so that cache_fplookup_parse_advance has
5867 * something to skip.
5870 cache_fpl_pathlen_inc(fpl);
5873 * cache_fplookup_parse_advance starts from ndp->ni_next
5875 ndp->ni_next = cnp->cn_nameptr;
5878 * See cache_fplookup_dot.
5880 fpl->tvp = fpl->dvp;
5881 fpl->tvp_seqc = fpl->dvp_seqc;
5887 * Handle trailing slashes (e.g., "foo/").
5889 * If a trailing slash is found the terminal vnode must be a directory.
5890 * Regular lookup shortens the path by nulifying the first trailing slash and
5891 * sets the TRAILINGSLASH flag to denote this took place. There are several
5892 * checks on it performed later.
5894 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5895 * manner relying on an invariant that a non-directory vnode will get a miss.
5896 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5898 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5899 * and denotes this is the last path component, which avoids looping back.
5901 * Only plain lookups are supported for now to restrict corner cases to handle.
5903 static int __noinline
5904 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5909 struct nameidata *ndp;
5910 struct componentname *cnp;
5911 struct namecache *ncp;
5913 char *cn_nameptr_orig, *cn_nameptr_slash;
5920 tvp_seqc = fpl->tvp_seqc;
5922 MPASS(fpl->dvp == fpl->tvp);
5923 KASSERT(cache_fpl_istrailingslash(fpl),
5924 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5926 KASSERT(cnp->cn_nameptr[0] == '\0',
5927 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5929 KASSERT(cnp->cn_namelen == 0,
5930 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5932 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5934 if (cnp->cn_nameiop != LOOKUP) {
5935 return (cache_fpl_aborted(fpl));
5938 if (__predict_false(tvp->v_type != VDIR)) {
5939 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5940 return (cache_fpl_aborted(fpl));
5942 cache_fpl_smr_exit(fpl);
5943 return (cache_fpl_handled_error(fpl, ENOTDIR));
5947 * Denote the last component.
5949 ndp->ni_next = &cnp->cn_nameptr[0];
5950 MPASS(cache_fpl_islastcn(ndp));
5953 * Unwind trailing slashes.
5955 cn_nameptr_orig = cnp->cn_nameptr;
5956 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5958 if (cnp->cn_nameptr[0] != '/') {
5964 * Unwind to the beginning of the path component.
5966 * Note the path may or may not have started with a slash.
5968 cn_nameptr_slash = cnp->cn_nameptr;
5969 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5971 if (cnp->cn_nameptr[0] == '/') {
5975 if (cnp->cn_nameptr[0] == '/') {
5979 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5980 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5981 cache_fpl_checkpoint(fpl);
5984 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5985 if (ni_pathlen != fpl->debug.ni_pathlen) {
5986 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5987 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5988 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5993 * If this was a "./" lookup the parent directory is already correct.
5995 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
6000 * Otherwise we need to look it up.
6003 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
6004 if (__predict_false(ncp == NULL)) {
6005 return (cache_fpl_aborted(fpl));
6007 nc_flag = atomic_load_char(&ncp->nc_flag);
6008 if ((nc_flag & NCF_ISDOTDOT) != 0) {
6009 return (cache_fpl_aborted(fpl));
6011 fpl->dvp = ncp->nc_dvp;
6012 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
6013 if (seqc_in_modify(fpl->dvp_seqc)) {
6014 return (cache_fpl_aborted(fpl));
6020 * See the API contract for VOP_FPLOOKUP_VEXEC.
6022 static int __noinline
6023 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
6025 struct componentname *cnp;
6031 dvp_seqc = fpl->dvp_seqc;
6034 * Hack: delayed empty path checking.
6036 if (cnp->cn_pnbuf[0] == '\0') {
6037 return (cache_fplookup_emptypath(fpl));
6041 * TODO: Due to ignoring trailing slashes lookup will perform a
6042 * permission check on the last dir when it should not be doing it. It
6043 * may fail, but said failure should be ignored. It is possible to fix
6044 * it up fully without resorting to regular lookup, but for now just
6047 if (cache_fpl_istrailingslash(fpl)) {
6048 return (cache_fpl_aborted(fpl));
6052 * Hack: delayed degenerate path checking.
6054 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
6055 return (cache_fplookup_degenerate(fpl));
6059 * Hack: delayed name len checking.
6061 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
6062 cache_fpl_smr_exit(fpl);
6063 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
6067 * Hack: they may be looking up foo/bar, where foo is not a directory.
6068 * In such a case we need to return ENOTDIR, but we may happen to get
6069 * here with a different error.
6071 if (dvp->v_type != VDIR) {
6076 * Hack: handle O_SEARCH.
6078 * Open Group Base Specifications Issue 7, 2018 edition states:
6080 * If the access mode of the open file description associated with the
6081 * file descriptor is not O_SEARCH, the function shall check whether
6082 * directory searches are permitted using the current permissions of
6083 * the directory underlying the file descriptor. If the access mode is
6084 * O_SEARCH, the function shall not perform the check.
6087 * Regular lookup tests for the NOEXECCHECK flag for every path
6088 * component to decide whether to do the permission check. However,
6089 * since most lookups never have the flag (and when they do it is only
6090 * present for the first path component), lockless lookup only acts on
6091 * it if there is a permission problem. Here the flag is represented
6092 * with a boolean so that we don't have to clear it on the way out.
6094 * For simplicity this always aborts.
6095 * TODO: check if this is the first lookup and ignore the permission
6096 * problem. Note the flag has to survive fallback (if it happens to be
6100 return (cache_fpl_aborted(fpl));
6105 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6106 error = cache_fpl_aborted(fpl);
6108 cache_fpl_partial(fpl);
6112 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6113 error = cache_fpl_aborted(fpl);
6115 cache_fpl_smr_exit(fpl);
6116 cache_fpl_handled_error(fpl, error);
6124 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
6126 struct nameidata *ndp;
6127 struct componentname *cnp;
6134 cache_fpl_checkpoint(fpl);
6137 * The vnode at hand is almost always stable, skip checking for it.
6138 * Worst case this postpones the check towards the end of the iteration
6142 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
6144 mp = atomic_load_ptr(&dvp->v_mount);
6145 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
6146 return (cache_fpl_aborted(fpl));
6149 MPASS(fpl->tvp == NULL);
6152 cache_fplookup_parse(fpl);
6154 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
6155 if (__predict_false(error != 0)) {
6156 error = cache_fplookup_failed_vexec(fpl, error);
6160 error = cache_fplookup_next(fpl);
6161 if (__predict_false(cache_fpl_terminated(fpl))) {
6165 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
6167 if (fpl->tvp->v_type == VLNK) {
6168 error = cache_fplookup_symlink(fpl);
6169 if (cache_fpl_terminated(fpl)) {
6173 if (cache_fpl_islastcn(ndp)) {
6174 error = cache_fplookup_final(fpl);
6178 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
6179 error = cache_fpl_aborted(fpl);
6183 fpl->dvp = fpl->tvp;
6184 fpl->dvp_seqc = fpl->tvp_seqc;
6185 cache_fplookup_parse_advance(fpl);
6188 cache_fpl_checkpoint(fpl);
6195 * Fast path lookup protected with SMR and sequence counters.
6197 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
6199 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
6202 * Traditional vnode lookup conceptually looks like this:
6208 * vn_unlock(current);
6215 * Each jump to the next vnode is safe memory-wise and atomic with respect to
6216 * any modifications thanks to holding respective locks.
6218 * The same guarantee can be provided with a combination of safe memory
6219 * reclamation and sequence counters instead. If all operations which affect
6220 * the relationship between the current vnode and the one we are looking for
6221 * also modify the counter, we can verify whether all the conditions held as
6222 * we made the jump. This includes things like permissions, mount points etc.
6223 * Counter modification is provided by enclosing relevant places in
6224 * vn_seqc_write_begin()/end() calls.
6226 * Thus this translates to:
6229 * dvp_seqc = seqc_read_any(dvp);
6230 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
6234 * tvp_seqc = seqc_read_any(tvp);
6235 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6237 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6239 * dvp = tvp; // we know nothing of importance has changed
6240 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6244 * vget(); // secure the vnode
6245 * if (!seqc_consistent(tvp, tvp_seqc) // final check
6247 * // at this point we know nothing has changed for any parent<->child pair
6248 * // as they were crossed during the lookup, meaning we matched the guarantee
6249 * // of the locked variant
6252 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6253 * - they are called while within vfs_smr protection which they must never exit
6254 * - EAGAIN can be returned to denote checking could not be performed, it is
6255 * always valid to return it
6256 * - if the sequence counter has not changed the result must be valid
6257 * - if the sequence counter has changed both false positives and false negatives
6258 * are permitted (since the result will be rejected later)
6259 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6261 * Caveats to watch out for:
6262 * - vnodes are passed unlocked and unreferenced with nothing stopping
6263 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6264 * to use atomic_load_ptr to fetch it.
6265 * - the aforementioned object can also get freed, meaning absent other means it
6266 * should be protected with vfs_smr
6267 * - either safely checking permissions as they are modified or guaranteeing
6268 * their stability is left to the routine
6271 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6274 struct cache_fpl fpl;
6277 struct componentname *cnp;
6280 fpl.status = CACHE_FPL_STATUS_UNSET;
6283 fpl.cnp = cnp = &ndp->ni_cnd;
6284 MPASS(ndp->ni_lcf == 0);
6285 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6286 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6288 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6289 MPASS(ndp->ni_resflags == 0);
6291 if (__predict_false(!cache_can_fplookup(&fpl))) {
6292 *status = fpl.status;
6293 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6294 return (EOPNOTSUPP);
6297 cache_fpl_checkpoint_outer(&fpl);
6299 cache_fpl_smr_enter_initial(&fpl);
6301 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6303 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6304 fpl.fsearch = false;
6305 fpl.tvp = NULL; /* for degenerate path handling */
6307 pwd = pwd_get_smr();
6309 namei_setup_rootdir(ndp, cnp, pwd);
6310 ndp->ni_topdir = pwd->pwd_jdir;
6312 if (cnp->cn_pnbuf[0] == '/') {
6313 dvp = cache_fpl_handle_root(&fpl);
6314 ndp->ni_resflags = NIRES_ABS;
6316 if (ndp->ni_dirfd == AT_FDCWD) {
6317 dvp = pwd->pwd_cdir;
6319 error = cache_fplookup_dirfd(&fpl, &dvp);
6320 if (__predict_false(error != 0)) {
6326 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6327 error = cache_fplookup_impl(dvp, &fpl);
6329 cache_fpl_smr_assert_not_entered(&fpl);
6330 cache_fpl_assert_status(&fpl);
6331 *status = fpl.status;
6332 if (SDT_PROBES_ENABLED()) {
6333 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6334 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6335 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6339 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6340 MPASS(error != CACHE_FPL_FAILED);
6342 cache_fpl_cleanup_cnp(fpl.cnp);
6343 MPASS(fpl.dvp == NULL);
6344 MPASS(fpl.tvp == NULL);
6346 ndp->ni_dvp = fpl.dvp;
6347 ndp->ni_vp = fpl.tvp;