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);
1825 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1826 blp = HASH2BUCKETLOCK(hash);
1828 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1833 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1834 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1835 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1844 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1845 if (__predict_false(error != 0)) {
1846 atomic_add_long(&zap_bucket_fail, 1);
1849 counter_u64_add(numposzaps, 1);
1850 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1854 counter_u64_add(nummisszap, 1);
1855 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1859 static int __noinline
1860 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1861 struct timespec *tsp, int *ticksp)
1866 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1873 * When we lookup "." we still can be asked to lock it
1876 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1877 if (ltype != VOP_ISLOCKED(*vpp)) {
1878 if (ltype == LK_EXCLUSIVE) {
1879 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1880 if (VN_IS_DOOMED((*vpp))) {
1881 /* forced unmount */
1887 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1892 static int __noinline
1893 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1894 struct timespec *tsp, int *ticksp)
1896 struct namecache_ts *ncp_ts;
1897 struct namecache *ncp;
1903 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1905 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1906 cache_remove_cnp(dvp, cnp);
1911 dvlp = VP2VNODELOCK(dvp);
1913 ncp = dvp->v_cache_dd;
1915 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1919 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1920 if (ncp->nc_flag & NCF_NEGATIVE)
1927 goto negative_success;
1928 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1929 cache_out_ts(ncp, tsp, ticksp);
1930 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1931 NCF_DTS && tsp != NULL) {
1932 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1933 *tsp = ncp_ts->nc_dotdottime;
1937 ltype = VOP_ISLOCKED(dvp);
1939 vs = vget_prep(*vpp);
1941 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1942 vn_lock(dvp, ltype | LK_RETRY);
1943 if (VN_IS_DOOMED(dvp)) {
1955 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1956 if (cnp->cn_flags & ISLASTCN) {
1957 counter_u64_add(numnegzaps, 1);
1958 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1965 whiteout = (ncp->nc_flag & NCF_WHITE);
1966 cache_out_ts(ncp, tsp, ticksp);
1967 if (cache_neg_hit_prep(ncp))
1968 cache_neg_promote(ncp);
1970 cache_neg_hit_finish(ncp);
1973 cnp->cn_flags |= ISWHITEOUT;
1978 * Lookup a name in the name cache
1982 * - dvp: Parent directory in which to search.
1983 * - vpp: Return argument. Will contain desired vnode on cache hit.
1984 * - cnp: Parameters of the name search. The most interesting bits of
1985 * the cn_flags field have the following meanings:
1986 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1988 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1989 * - tsp: Return storage for cache timestamp. On a successful (positive
1990 * or negative) lookup, tsp will be filled with any timespec that
1991 * was stored when this cache entry was created. However, it will
1992 * be clear for "." entries.
1993 * - ticks: Return storage for alternate cache timestamp. On a successful
1994 * (positive or negative) lookup, it will contain the ticks value
1995 * that was current when the cache entry was created, unless cnp
1998 * Either both tsp and ticks have to be provided or neither of them.
2002 * - -1: A positive cache hit. vpp will contain the desired vnode.
2003 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
2004 * to a forced unmount. vpp will not be modified. If the entry
2005 * is a whiteout, then the ISWHITEOUT flag will be set in
2007 * - 0: A cache miss. vpp will not be modified.
2011 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
2012 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
2013 * lock is not recursively acquired.
2015 static int __noinline
2016 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2017 struct timespec *tsp, int *ticksp)
2019 struct namecache *ncp;
2026 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2027 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
2030 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2031 blp = HASH2BUCKETLOCK(hash);
2034 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2035 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2036 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2040 if (__predict_false(ncp == NULL)) {
2042 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2043 counter_u64_add(nummiss, 1);
2047 if (ncp->nc_flag & NCF_NEGATIVE)
2048 goto negative_success;
2050 counter_u64_add(numposhits, 1);
2052 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2053 cache_out_ts(ncp, tsp, ticksp);
2055 vs = vget_prep(*vpp);
2057 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2065 * We don't get here with regular lookup apart from corner cases.
2067 if (__predict_true(cnp->cn_nameiop == CREATE)) {
2068 if (cnp->cn_flags & ISLASTCN) {
2069 counter_u64_add(numnegzaps, 1);
2070 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2071 if (__predict_false(error != 0)) {
2072 atomic_add_long(&zap_bucket_fail2, 1);
2080 whiteout = (ncp->nc_flag & NCF_WHITE);
2081 cache_out_ts(ncp, tsp, ticksp);
2082 if (cache_neg_hit_prep(ncp))
2083 cache_neg_promote(ncp);
2085 cache_neg_hit_finish(ncp);
2088 cnp->cn_flags |= ISWHITEOUT;
2093 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2094 struct timespec *tsp, int *ticksp)
2096 struct namecache *ncp;
2100 bool whiteout, neg_promote;
2103 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2106 if (__predict_false(!doingcache)) {
2107 cnp->cn_flags &= ~MAKEENTRY;
2112 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2113 if (cnp->cn_namelen == 1)
2114 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2115 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2116 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2119 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2121 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2122 cache_remove_cnp(dvp, cnp);
2126 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2129 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2130 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2131 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2135 if (__predict_false(ncp == NULL)) {
2137 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2138 counter_u64_add(nummiss, 1);
2142 nc_flag = atomic_load_char(&ncp->nc_flag);
2143 if (nc_flag & NCF_NEGATIVE)
2144 goto negative_success;
2146 counter_u64_add(numposhits, 1);
2148 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2149 cache_out_ts(ncp, tsp, ticksp);
2151 if (!cache_ncp_canuse(ncp)) {
2156 vs = vget_prep_smr(*vpp);
2158 if (__predict_false(vs == VGET_NONE)) {
2162 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2169 if (cnp->cn_nameiop == CREATE) {
2170 if (cnp->cn_flags & ISLASTCN) {
2176 cache_out_ts(ncp, tsp, ticksp);
2177 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2178 neg_promote = cache_neg_hit_prep(ncp);
2179 if (!cache_ncp_canuse(ncp)) {
2180 cache_neg_hit_abort(ncp);
2186 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2189 cache_neg_hit_finish(ncp);
2193 cnp->cn_flags |= ISWHITEOUT;
2196 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2199 struct celockstate {
2203 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2204 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2207 cache_celockstate_init(struct celockstate *cel)
2210 bzero(cel, sizeof(*cel));
2214 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2217 struct mtx *vlp1, *vlp2;
2219 MPASS(cel->vlp[0] == NULL);
2220 MPASS(cel->vlp[1] == NULL);
2221 MPASS(cel->vlp[2] == NULL);
2223 MPASS(vp != NULL || dvp != NULL);
2225 vlp1 = VP2VNODELOCK(vp);
2226 vlp2 = VP2VNODELOCK(dvp);
2227 cache_sort_vnodes(&vlp1, &vlp2);
2238 cache_unlock_vnodes_cel(struct celockstate *cel)
2241 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2243 if (cel->vlp[0] != NULL)
2244 mtx_unlock(cel->vlp[0]);
2245 if (cel->vlp[1] != NULL)
2246 mtx_unlock(cel->vlp[1]);
2247 if (cel->vlp[2] != NULL)
2248 mtx_unlock(cel->vlp[2]);
2252 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2257 cache_assert_vlp_locked(cel->vlp[0]);
2258 cache_assert_vlp_locked(cel->vlp[1]);
2259 MPASS(cel->vlp[2] == NULL);
2262 vlp = VP2VNODELOCK(vp);
2265 if (vlp >= cel->vlp[1]) {
2268 if (mtx_trylock(vlp))
2270 cache_unlock_vnodes_cel(cel);
2271 atomic_add_long(&cache_lock_vnodes_cel_3_failures, 1);
2272 if (vlp < cel->vlp[0]) {
2274 mtx_lock(cel->vlp[0]);
2275 mtx_lock(cel->vlp[1]);
2277 if (cel->vlp[0] != NULL)
2278 mtx_lock(cel->vlp[0]);
2280 mtx_lock(cel->vlp[1]);
2290 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2294 MPASS(cel->blp[0] == NULL);
2295 MPASS(cel->blp[1] == NULL);
2297 cache_sort_vnodes(&blp1, &blp2);
2308 cache_unlock_buckets_cel(struct celockstate *cel)
2311 if (cel->blp[0] != NULL)
2312 mtx_unlock(cel->blp[0]);
2313 mtx_unlock(cel->blp[1]);
2317 * Lock part of the cache affected by the insertion.
2319 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2320 * However, insertion can result in removal of an old entry. In this
2321 * case we have an additional vnode and bucketlock pair to lock.
2323 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2324 * preserving the locking order (smaller address first).
2327 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2330 struct namecache *ncp;
2331 struct mtx *blps[2];
2334 blps[0] = HASH2BUCKETLOCK(hash);
2337 cache_lock_vnodes_cel(cel, dvp, vp);
2338 if (vp == NULL || vp->v_type != VDIR)
2340 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2343 nc_flag = atomic_load_char(&ncp->nc_flag);
2344 if ((nc_flag & NCF_ISDOTDOT) == 0)
2346 MPASS(ncp->nc_dvp == vp);
2347 blps[1] = NCP2BUCKETLOCK(ncp);
2348 if ((nc_flag & NCF_NEGATIVE) != 0)
2350 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2353 * All vnodes got re-locked. Re-validate the state and if
2354 * nothing changed we are done. Otherwise restart.
2356 if (ncp == vp->v_cache_dd &&
2357 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2358 blps[1] == NCP2BUCKETLOCK(ncp) &&
2359 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2361 cache_unlock_vnodes_cel(cel);
2366 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2370 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2373 struct namecache *ncp;
2374 struct mtx *blps[2];
2377 blps[0] = HASH2BUCKETLOCK(hash);
2380 cache_lock_vnodes_cel(cel, dvp, vp);
2381 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2384 nc_flag = atomic_load_char(&ncp->nc_flag);
2385 if ((nc_flag & NCF_ISDOTDOT) == 0)
2387 MPASS(ncp->nc_dvp == dvp);
2388 blps[1] = NCP2BUCKETLOCK(ncp);
2389 if ((nc_flag & NCF_NEGATIVE) != 0)
2391 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2393 if (ncp == dvp->v_cache_dd &&
2394 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2395 blps[1] == NCP2BUCKETLOCK(ncp) &&
2396 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2398 cache_unlock_vnodes_cel(cel);
2403 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2407 cache_enter_unlock(struct celockstate *cel)
2410 cache_unlock_buckets_cel(cel);
2411 cache_unlock_vnodes_cel(cel);
2414 static void __noinline
2415 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2416 struct componentname *cnp)
2418 struct celockstate cel;
2419 struct namecache *ncp;
2423 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2425 len = cnp->cn_namelen;
2426 cache_celockstate_init(&cel);
2427 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2428 cache_enter_lock_dd(&cel, dvp, vp, hash);
2429 ncp = dvp->v_cache_dd;
2430 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2431 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2432 cache_zap_locked(ncp);
2436 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2437 cache_enter_unlock(&cel);
2443 * Add an entry to the cache.
2446 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2447 struct timespec *tsp, struct timespec *dtsp)
2449 struct celockstate cel;
2450 struct namecache *ncp, *n2, *ndd;
2451 struct namecache_ts *ncp_ts;
2452 struct nchashhead *ncpp;
2457 KASSERT(cnp->cn_namelen <= NAME_MAX,
2458 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2460 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2461 VNPASS(dvp->v_type != VNON, dvp);
2463 VNPASS(!VN_IS_DOOMED(vp), vp);
2464 VNPASS(vp->v_type != VNON, vp);
2466 if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
2468 ("%s: different vnodes for dot entry (%p; %p)\n", __func__,
2472 ("%s: same vnode for non-dot entry [%s] (%p)\n", __func__,
2473 cnp->cn_nameptr, dvp));
2477 if (__predict_false(!doingcache))
2482 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2483 if (cnp->cn_namelen == 1)
2485 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2486 cache_enter_dotdot_prep(dvp, vp, cnp);
2487 flag = NCF_ISDOTDOT;
2491 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2495 cache_celockstate_init(&cel);
2500 * Calculate the hash key and setup as much of the new
2501 * namecache entry as possible before acquiring the lock.
2503 ncp->nc_flag = flag | NCF_WIP;
2506 cache_neg_init(ncp);
2509 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2510 ncp_ts->nc_time = *tsp;
2511 ncp_ts->nc_ticks = ticks;
2512 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2514 ncp_ts->nc_dotdottime = *dtsp;
2515 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2518 len = ncp->nc_nlen = cnp->cn_namelen;
2519 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2520 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2521 ncp->nc_name[len] = '\0';
2522 cache_enter_lock(&cel, dvp, vp, hash);
2525 * See if this vnode or negative entry is already in the cache
2526 * with this name. This can happen with concurrent lookups of
2527 * the same path name.
2529 ncpp = NCHHASH(hash);
2530 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2531 if (n2->nc_dvp == dvp &&
2532 n2->nc_nlen == cnp->cn_namelen &&
2533 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2534 MPASS(cache_ncp_canuse(n2));
2535 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2537 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2538 __func__, NULL, vp, cnp->cn_nameptr));
2540 KASSERT(n2->nc_vp == vp,
2541 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2542 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2544 * Entries are supposed to be immutable unless in the
2545 * process of getting destroyed. Accommodating for
2546 * changing timestamps is possible but not worth it.
2547 * This should be harmless in terms of correctness, in
2548 * the worst case resulting in an earlier expiration.
2549 * Alternatively, the found entry can be replaced
2552 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2555 KASSERT((n2->nc_flag & NCF_TS) != 0,
2557 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2558 n2_ts->nc_time = ncp_ts->nc_time;
2559 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2561 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2562 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2566 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2568 goto out_unlock_free;
2572 if (flag == NCF_ISDOTDOT) {
2574 * See if we are trying to add .. entry, but some other lookup
2575 * has populated v_cache_dd pointer already.
2577 if (dvp->v_cache_dd != NULL)
2578 goto out_unlock_free;
2579 KASSERT(vp == NULL || vp->v_type == VDIR,
2580 ("wrong vnode type %p", vp));
2581 atomic_thread_fence_rel();
2582 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2586 if (flag != NCF_ISDOTDOT) {
2588 * For this case, the cache entry maps both the
2589 * directory name in it and the name ".." for the
2590 * directory's parent.
2592 if ((ndd = vp->v_cache_dd) != NULL) {
2593 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2594 cache_zap_locked(ndd);
2598 atomic_thread_fence_rel();
2599 atomic_store_ptr(&vp->v_cache_dd, ncp);
2600 } else if (vp->v_type != VDIR) {
2601 if (vp->v_cache_dd != NULL) {
2602 atomic_store_ptr(&vp->v_cache_dd, NULL);
2607 if (flag != NCF_ISDOTDOT) {
2608 if (LIST_EMPTY(&dvp->v_cache_src)) {
2609 cache_hold_vnode(dvp);
2611 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2615 * If the entry is "negative", we place it into the
2616 * "negative" cache queue, otherwise, we place it into the
2617 * destination vnode's cache entries queue.
2620 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2621 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2624 if (cnp->cn_flags & ISWHITEOUT)
2625 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2626 cache_neg_insert(ncp);
2627 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2632 * Insert the new namecache entry into the appropriate chain
2633 * within the cache entries table.
2635 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2637 atomic_thread_fence_rel();
2639 * Mark the entry as fully constructed.
2640 * It is immutable past this point until its removal.
2642 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2644 cache_enter_unlock(&cel);
2649 cache_enter_unlock(&cel);
2655 * A variant of the above accepting flags.
2657 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2659 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2660 * happens to match and it is doing it in an inefficient manner. It was added
2661 * to accommodate NFS which runs into a case where the target for a given name
2662 * may change from under it. Note this does nothing to solve the following
2663 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2664 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2667 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2668 struct timespec *tsp, struct timespec *dtsp, int flags)
2671 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2673 if (flags & VFS_CACHE_DROPOLD)
2674 cache_remove_cnp(dvp, cnp);
2675 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2679 cache_roundup_2(u_long val)
2683 for (res = 1; res <= val; res <<= 1)
2689 static struct nchashhead *
2690 nchinittbl(u_long elements, u_long *hashmask)
2692 struct nchashhead *hashtbl;
2695 hashsize = cache_roundup_2(elements) / 2;
2697 hashtbl = malloc(hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2698 for (i = 0; i < hashsize; i++)
2699 CK_SLIST_INIT(&hashtbl[i]);
2700 *hashmask = hashsize - 1;
2705 ncfreetbl(struct nchashhead *hashtbl)
2708 free(hashtbl, M_VFSCACHE);
2712 * Name cache initialization, from vfs_init() when we are booting
2715 nchinit(void *dummy __unused)
2719 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2720 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2721 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2722 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2723 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2724 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2725 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2726 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2728 VFS_SMR_ZONE_SET(cache_zone_small);
2729 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2730 VFS_SMR_ZONE_SET(cache_zone_large);
2731 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2733 ncsize = desiredvnodes * ncsizefactor;
2734 cache_recalc_neg_min();
2735 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2736 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2737 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2739 if (ncbuckethash > nchash)
2740 ncbuckethash = nchash;
2741 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2743 for (i = 0; i < numbucketlocks; i++)
2744 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2745 ncvnodehash = ncbuckethash;
2746 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2748 for (i = 0; i < numvnodelocks; i++)
2749 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2751 for (i = 0; i < numneglists; i++) {
2752 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2753 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2754 TAILQ_INIT(&neglists[i].nl_list);
2755 TAILQ_INIT(&neglists[i].nl_hotlist);
2758 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2761 cache_vnode_init(struct vnode *vp)
2764 LIST_INIT(&vp->v_cache_src);
2765 TAILQ_INIT(&vp->v_cache_dst);
2766 vp->v_cache_dd = NULL;
2771 * Induce transient cache misses for lockless operation in cache_lookup() by
2772 * using a temporary hash table.
2774 * This will force a fs lookup.
2776 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2777 * to observe all CPUs not performing the lookup.
2780 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2783 MPASS(temphash < nchash);
2785 * Change the size. The new size is smaller and can safely be used
2786 * against the existing table. All lookups which now hash wrong will
2787 * result in a cache miss, which all callers are supposed to know how
2790 atomic_store_long(&nchash, temphash);
2791 atomic_thread_fence_rel();
2792 vfs_smr_synchronize();
2794 * At this point everyone sees the updated hash value, but they still
2795 * see the old table.
2797 atomic_store_ptr(&nchashtbl, temptbl);
2798 atomic_thread_fence_rel();
2799 vfs_smr_synchronize();
2801 * At this point everyone sees the updated table pointer and size pair.
2806 * Set the new hash table.
2808 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2809 * lockless operation in cache_lookup().
2812 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2815 MPASS(nchash < new_hash);
2817 * Change the pointer first. This wont result in out of bounds access
2818 * since the temporary table is guaranteed to be smaller.
2820 atomic_store_ptr(&nchashtbl, new_tbl);
2821 atomic_thread_fence_rel();
2822 vfs_smr_synchronize();
2824 * At this point everyone sees the updated pointer value, but they
2825 * still see the old size.
2827 atomic_store_long(&nchash, new_hash);
2828 atomic_thread_fence_rel();
2829 vfs_smr_synchronize();
2831 * At this point everyone sees the updated table pointer and size pair.
2836 cache_changesize(u_long newmaxvnodes)
2838 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2839 u_long new_nchash, old_nchash, temphash;
2840 struct namecache *ncp;
2845 newncsize = newmaxvnodes * ncsizefactor;
2846 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2847 if (newmaxvnodes < numbucketlocks)
2848 newmaxvnodes = numbucketlocks;
2850 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2851 /* If same hash table size, nothing to do */
2852 if (nchash == new_nchash) {
2853 ncfreetbl(new_nchashtbl);
2857 temptbl = nchinittbl(1, &temphash);
2860 * Move everything from the old hash table to the new table.
2861 * None of the namecache entries in the table can be removed
2862 * because to do so, they have to be removed from the hash table.
2864 cache_lock_all_vnodes();
2865 cache_lock_all_buckets();
2866 old_nchashtbl = nchashtbl;
2867 old_nchash = nchash;
2868 cache_changesize_set_temp(temptbl, temphash);
2869 for (i = 0; i <= old_nchash; i++) {
2870 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2871 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2873 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2874 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2878 cache_recalc_neg_min();
2879 cache_changesize_set_new(new_nchashtbl, new_nchash);
2880 cache_unlock_all_buckets();
2881 cache_unlock_all_vnodes();
2882 ncfreetbl(old_nchashtbl);
2887 * Remove all entries from and to a particular vnode.
2890 cache_purge_impl(struct vnode *vp)
2892 struct cache_freebatch batch;
2893 struct namecache *ncp;
2894 struct mtx *vlp, *vlp2;
2897 vlp = VP2VNODELOCK(vp);
2901 while (!LIST_EMPTY(&vp->v_cache_src)) {
2902 ncp = LIST_FIRST(&vp->v_cache_src);
2903 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2905 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2907 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2908 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2909 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2911 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2913 ncp = vp->v_cache_dd;
2915 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2916 ("lost dotdot link"));
2917 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2919 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2921 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2925 cache_free_batch(&batch);
2929 * Opportunistic check to see if there is anything to do.
2932 cache_has_entries(struct vnode *vp)
2935 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2936 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2942 cache_purge(struct vnode *vp)
2945 SDT_PROBE1(vfs, namecache, purge, done, vp);
2946 if (!cache_has_entries(vp))
2948 cache_purge_impl(vp);
2952 * Only to be used by vgone.
2955 cache_purge_vgone(struct vnode *vp)
2959 VNPASS(VN_IS_DOOMED(vp), vp);
2960 if (cache_has_entries(vp)) {
2961 cache_purge_impl(vp);
2966 * Serialize against a potential thread doing cache_purge.
2968 vlp = VP2VNODELOCK(vp);
2969 mtx_wait_unlocked(vlp);
2970 if (cache_has_entries(vp)) {
2971 cache_purge_impl(vp);
2978 * Remove all negative entries for a particular directory vnode.
2981 cache_purge_negative(struct vnode *vp)
2983 struct cache_freebatch batch;
2984 struct namecache *ncp, *nnp;
2987 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2988 if (LIST_EMPTY(&vp->v_cache_src))
2991 vlp = VP2VNODELOCK(vp);
2993 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2994 if (!(ncp->nc_flag & NCF_NEGATIVE))
2996 cache_zap_negative_locked_vnode_kl(ncp, vp);
2997 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
3000 cache_free_batch(&batch);
3004 * Entry points for modifying VOP operations.
3007 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
3008 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
3011 ASSERT_VOP_IN_SEQC(fdvp);
3012 ASSERT_VOP_IN_SEQC(fvp);
3013 ASSERT_VOP_IN_SEQC(tdvp);
3015 ASSERT_VOP_IN_SEQC(tvp);
3020 KASSERT(!cache_remove_cnp(tdvp, tcnp),
3021 ("%s: lingering negative entry", __func__));
3023 cache_remove_cnp(tdvp, tcnp);
3029 * Historically renaming was always purging all revelang entries,
3030 * but that's quite wasteful. In particular turns out that in many cases
3031 * the target file is immediately accessed after rename, inducing a cache
3034 * Recode this to reduce relocking and reuse the existing entry (if any)
3035 * instead of just removing it above and allocating a new one here.
3037 cache_enter(tdvp, fvp, tcnp);
3041 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
3044 ASSERT_VOP_IN_SEQC(dvp);
3045 ASSERT_VOP_IN_SEQC(vp);
3051 * Validate that if an entry exists it matches.
3054 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
3056 struct namecache *ncp;
3060 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
3061 if (CK_SLIST_EMPTY(NCHHASH(hash)))
3063 blp = HASH2BUCKETLOCK(hash);
3065 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3066 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3067 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
3068 if (ncp->nc_vp != vp)
3069 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
3070 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3077 cache_assert_no_entries(struct vnode *vp)
3080 VNPASS(TAILQ_EMPTY(&vp->v_cache_dst), vp);
3081 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
3082 VNPASS(vp->v_cache_dd == NULL, vp);
3087 * Flush all entries referencing a particular filesystem.
3090 cache_purgevfs(struct mount *mp)
3092 struct vnode *vp, *mvp;
3093 size_t visited __sdt_used, purged __sdt_used;
3095 visited = purged = 0;
3097 * Somewhat wasteful iteration over all vnodes. Would be better to
3098 * support filtering and avoid the interlock to begin with.
3100 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3102 if (!cache_has_entries(vp)) {
3113 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3117 * Perform canonical checks and cache lookup and pass on to filesystem
3118 * through the vop_cachedlookup only if needed.
3122 vfs_cache_lookup(struct vop_lookup_args *ap)
3126 struct vnode **vpp = ap->a_vpp;
3127 struct componentname *cnp = ap->a_cnp;
3128 int flags = cnp->cn_flags;
3133 if (dvp->v_type != VDIR)
3136 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3137 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3140 error = vn_dir_check_exec(dvp, cnp);
3144 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3146 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3152 /* Implementation of the getcwd syscall. */
3154 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3160 buflen = uap->buflen;
3161 if (__predict_false(buflen < 2))
3163 if (buflen > MAXPATHLEN)
3164 buflen = MAXPATHLEN;
3166 buf = uma_zalloc(namei_zone, M_WAITOK);
3167 error = vn_getcwd(buf, &retbuf, &buflen);
3169 error = copyout(retbuf, uap->buf, buflen);
3170 uma_zfree(namei_zone, buf);
3175 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3181 pwd = pwd_get_smr();
3182 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3184 VFS_SMR_ASSERT_NOT_ENTERED();
3186 pwd = pwd_hold(curthread);
3187 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3193 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3200 * Canonicalize a path by walking it forward and back.
3203 * - Nothing guarantees the integrity of the entire chain. Consider the case
3204 * where the path "foo/bar/baz/qux" is passed, but "bar" is moved out of
3205 * "foo" into "quux" during the backwards walk. The result will be
3206 * "quux/bar/baz/qux", which could not have been obtained by an incremental
3207 * walk in userspace. Moreover, the path we return is inaccessible if the
3208 * calling thread lacks permission to traverse "quux".
3211 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3212 size_t size, int flags, enum uio_seg pathseg)
3214 struct nameidata nd;
3215 char *retbuf, *freebuf;
3220 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | WANTPARENT | AUDITVNODE1,
3221 pathseg, path, fd, &cap_fstat_rights);
3222 if ((error = namei(&nd)) != 0)
3225 if (nd.ni_vp->v_type == VREG && nd.ni_dvp->v_type != VDIR &&
3226 (nd.ni_vp->v_vflag & VV_ROOT) != 0) {
3228 * This happens if vp is a file mount. The call to
3229 * vn_fullpath_hardlink can panic if path resolution can't be
3230 * handled without the directory.
3232 * To resolve this, we find the vnode which was mounted on -
3233 * this should have a unique global path since we disallow
3234 * mounting on linked files.
3236 struct vnode *covered_vp;
3237 error = vn_lock(nd.ni_vp, LK_SHARED);
3240 covered_vp = nd.ni_vp->v_mount->mnt_vnodecovered;
3242 VOP_UNLOCK(nd.ni_vp);
3243 error = vn_fullpath(covered_vp, &retbuf, &freebuf);
3246 error = vn_fullpath_hardlink(nd.ni_vp, nd.ni_dvp, nd.ni_cnd.cn_nameptr,
3247 nd.ni_cnd.cn_namelen, &retbuf, &freebuf, &size);
3250 error = copyout(retbuf, buf, size);
3251 free(freebuf, M_TEMP);
3261 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3264 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3265 uap->flags, UIO_USERSPACE));
3269 * Retrieve the full filesystem path that correspond to a vnode from the name
3270 * cache (if available)
3273 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3280 if (__predict_false(vp == NULL))
3283 buflen = MAXPATHLEN;
3284 buf = malloc(buflen, M_TEMP, M_WAITOK);
3286 pwd = pwd_get_smr();
3287 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3288 VFS_SMR_ASSERT_NOT_ENTERED();
3290 pwd = pwd_hold(curthread);
3291 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3302 * This function is similar to vn_fullpath, but it attempts to lookup the
3303 * pathname relative to the global root mount point. This is required for the
3304 * auditing sub-system, as audited pathnames must be absolute, relative to the
3305 * global root mount point.
3308 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3314 if (__predict_false(vp == NULL))
3316 buflen = MAXPATHLEN;
3317 buf = malloc(buflen, M_TEMP, M_WAITOK);
3319 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3320 VFS_SMR_ASSERT_NOT_ENTERED();
3322 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3331 static struct namecache *
3332 vn_dd_from_dst(struct vnode *vp)
3334 struct namecache *ncp;
3336 cache_assert_vnode_locked(vp);
3337 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3338 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3345 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3348 struct namecache *ncp;
3352 vlp = VP2VNODELOCK(*vp);
3354 ncp = (*vp)->v_cache_dd;
3355 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3356 KASSERT(ncp == vn_dd_from_dst(*vp),
3357 ("%s: mismatch for dd entry (%p != %p)", __func__,
3358 ncp, vn_dd_from_dst(*vp)));
3360 ncp = vn_dd_from_dst(*vp);
3363 if (*buflen < ncp->nc_nlen) {
3366 counter_u64_add(numfullpathfail4, 1);
3368 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3372 *buflen -= ncp->nc_nlen;
3373 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3374 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3383 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3386 vn_lock(*vp, LK_SHARED | LK_RETRY);
3387 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3390 counter_u64_add(numfullpathfail2, 1);
3391 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3396 if (VN_IS_DOOMED(dvp)) {
3397 /* forced unmount */
3400 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3404 * *vp has its use count incremented still.
3411 * Resolve a directory to a pathname.
3413 * The name of the directory can always be found in the namecache or fetched
3414 * from the filesystem. There is also guaranteed to be only one parent, meaning
3415 * we can just follow vnodes up until we find the root.
3417 * The vnode must be referenced.
3420 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3421 size_t *len, size_t addend)
3423 #ifdef KDTRACE_HOOKS
3424 struct vnode *startvp = vp;
3429 bool slash_prefixed;
3431 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3432 VNPASS(vp->v_usecount > 0, vp);
3436 slash_prefixed = true;
3441 slash_prefixed = false;
3446 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3447 counter_u64_add(numfullpathcalls, 1);
3448 while (vp != rdir && vp != rootvnode) {
3450 * The vp vnode must be already fully constructed,
3451 * since it is either found in namecache or obtained
3452 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3453 * without obtaining the vnode lock.
3455 if ((vp->v_vflag & VV_ROOT) != 0) {
3456 vn_lock(vp, LK_RETRY | LK_SHARED);
3459 * With the vnode locked, check for races with
3460 * unmount, forced or not. Note that we
3461 * already verified that vp is not equal to
3462 * the root vnode, which means that
3463 * mnt_vnodecovered can be NULL only for the
3466 if (VN_IS_DOOMED(vp) ||
3467 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3468 vp1->v_mountedhere != vp->v_mount) {
3471 SDT_PROBE3(vfs, namecache, fullpath, return,
3481 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3482 error = vn_vptocnp(&vp, buf, &buflen);
3488 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3492 buf[--buflen] = '/';
3493 slash_prefixed = true;
3497 if (!slash_prefixed) {
3500 counter_u64_add(numfullpathfail4, 1);
3501 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3505 buf[--buflen] = '/';
3507 counter_u64_add(numfullpathfound, 1);
3510 *retbuf = buf + buflen;
3511 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3518 * Resolve an arbitrary vnode to a pathname.
3521 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3522 * resolve to a different path than the one used to find it
3523 * - namecache is not mandatory, meaning names are not guaranteed to be added
3524 * (in which case resolving fails)
3526 static void __inline
3527 cache_rev_failed_impl(int *reason, int line)
3532 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3535 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3536 char **retbuf, size_t *buflen, size_t addend)
3538 #ifdef KDTRACE_HOOKS
3539 struct vnode *startvp = vp;
3543 struct namecache *ncp;
3547 #ifdef KDTRACE_HOOKS
3550 seqc_t vp_seqc, tvp_seqc;
3553 VFS_SMR_ASSERT_ENTERED();
3555 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3560 orig_buflen = *buflen;
3563 MPASS(*buflen >= 2);
3565 buf[*buflen] = '\0';
3568 if (vp == rdir || vp == rootvnode) {
3576 #ifdef KDTRACE_HOOKS
3580 ncp = NULL; /* for sdt probe down below */
3581 vp_seqc = vn_seqc_read_any(vp);
3582 if (seqc_in_modify(vp_seqc)) {
3583 cache_rev_failed(&reason);
3588 #ifdef KDTRACE_HOOKS
3591 if ((vp->v_vflag & VV_ROOT) != 0) {
3592 mp = atomic_load_ptr(&vp->v_mount);
3594 cache_rev_failed(&reason);
3597 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3598 tvp_seqc = vn_seqc_read_any(tvp);
3599 if (seqc_in_modify(tvp_seqc)) {
3600 cache_rev_failed(&reason);
3603 if (!vn_seqc_consistent(vp, vp_seqc)) {
3604 cache_rev_failed(&reason);
3611 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3613 cache_rev_failed(&reason);
3616 nc_flag = atomic_load_char(&ncp->nc_flag);
3617 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3618 cache_rev_failed(&reason);
3621 if (ncp->nc_nlen >= *buflen) {
3622 cache_rev_failed(&reason);
3626 *buflen -= ncp->nc_nlen;
3627 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3631 tvp_seqc = vn_seqc_read_any(tvp);
3632 if (seqc_in_modify(tvp_seqc)) {
3633 cache_rev_failed(&reason);
3636 if (!vn_seqc_consistent(vp, vp_seqc)) {
3637 cache_rev_failed(&reason);
3641 * Acquire fence provided by vn_seqc_read_any above.
3643 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3644 cache_rev_failed(&reason);
3647 if (!cache_ncp_canuse(ncp)) {
3648 cache_rev_failed(&reason);
3653 if (vp == rdir || vp == rootvnode)
3658 *retbuf = buf + *buflen;
3659 *buflen = orig_buflen - *buflen + addend;
3660 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3664 *buflen = orig_buflen;
3665 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3671 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3674 size_t orig_buflen, addend;
3680 orig_buflen = *buflen;
3684 if (vp->v_type != VDIR) {
3686 buf[*buflen] = '\0';
3687 error = vn_vptocnp(&vp, buf, buflen);
3696 addend = orig_buflen - *buflen;
3699 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3703 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3705 * Since the namecache does not track hardlinks, the caller is expected to
3706 * first look up the target vnode with WANTPARENT flag passed to namei to get
3709 * Then we have 2 cases:
3710 * - if the found vnode is a directory, the path can be constructed just by
3711 * following names up the chain
3712 * - otherwise we populate the buffer with the saved name and start resolving
3716 vn_fullpath_hardlink(struct vnode *vp, struct vnode *dvp,
3717 const char *hrdl_name, size_t hrdl_name_length,
3718 char **retbuf, char **freebuf, size_t *buflen)
3724 __enum_uint8(vtype) type;
3728 if (*buflen > MAXPATHLEN)
3729 *buflen = MAXPATHLEN;
3731 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3736 * Check for VBAD to work around the vp_crossmp bug in lookup().
3738 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3739 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3740 * If the type is VDIR (like in this very case) we can skip looking
3741 * at ni_dvp in the first place. However, since vnodes get passed here
3742 * unlocked the target may transition to doomed state (type == VBAD)
3743 * before we get to evaluate the condition. If this happens, we will
3744 * populate part of the buffer and descend to vn_fullpath_dir with
3745 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3747 type = atomic_load_8(&vp->v_type);
3753 addend = hrdl_name_length + 2;
3754 if (*buflen < addend) {
3759 tmpbuf = buf + *buflen;
3761 memcpy(&tmpbuf[1], hrdl_name, hrdl_name_length);
3762 tmpbuf[addend - 1] = '\0';
3767 pwd = pwd_get_smr();
3768 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3770 VFS_SMR_ASSERT_NOT_ENTERED();
3772 pwd = pwd_hold(curthread);
3774 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3790 vn_dir_dd_ino(struct vnode *vp)
3792 struct namecache *ncp;
3797 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3798 vlp = VP2VNODELOCK(vp);
3800 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3801 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3804 vs = vget_prep(ddvp);
3806 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3815 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3817 struct namecache *ncp;
3821 vlp = VP2VNODELOCK(vp);
3823 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3824 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3830 l = min(ncp->nc_nlen, buflen - 1);
3831 memcpy(buf, ncp->nc_name, l);
3838 * This function updates path string to vnode's full global path
3839 * and checks the size of the new path string against the pathlen argument.
3841 * Requires a locked, referenced vnode.
3842 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3844 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3845 * because it falls back to the ".." lookup if the namecache lookup fails.
3848 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3851 struct nameidata nd;
3856 ASSERT_VOP_ELOCKED(vp, __func__);
3858 /* Construct global filesystem path from vp. */
3860 error = vn_fullpath_global(vp, &rpath, &fbuf);
3867 if (strlen(rpath) >= pathlen) {
3869 error = ENAMETOOLONG;
3874 * Re-lookup the vnode by path to detect a possible rename.
3875 * As a side effect, the vnode is relocked.
3876 * If vnode was renamed, return ENOENT.
3878 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3888 strcpy(path, rpath);
3900 * This is similar to vn_path_to_global_path but allows for regular
3901 * files which may not be present in the cache.
3903 * Requires a locked, referenced vnode.
3904 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3907 vn_path_to_global_path_hardlink(struct thread *td, struct vnode *vp,
3908 struct vnode *dvp, char *path, u_int pathlen, const char *leaf_name,
3911 struct nameidata nd;
3917 ASSERT_VOP_ELOCKED(vp, __func__);
3920 * Construct global filesystem path from dvp, vp and leaf
3925 error = vn_fullpath_hardlink(vp, dvp, leaf_name, leaf_length,
3926 &rpath, &fbuf, &len);
3933 if (strlen(rpath) >= pathlen) {
3935 error = ENAMETOOLONG;
3940 * Re-lookup the vnode by path to detect a possible rename.
3941 * As a side effect, the vnode is relocked.
3942 * If vnode was renamed, return ENOENT.
3944 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3954 strcpy(path, rpath);
3967 db_print_vpath(struct vnode *vp)
3970 while (vp != NULL) {
3971 db_printf("%p: ", vp);
3972 if (vp == rootvnode) {
3976 if (vp->v_vflag & VV_ROOT) {
3977 db_printf("<mount point>");
3978 vp = vp->v_mount->mnt_vnodecovered;
3980 struct namecache *ncp;
3984 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3987 for (i = 0; i < ncp->nc_nlen; i++)
3988 db_printf("%c", *ncn++);
4001 DB_SHOW_COMMAND(vpath, db_show_vpath)
4006 db_printf("usage: show vpath <struct vnode *>\n");
4010 vp = (struct vnode *)addr;
4016 static int cache_fast_lookup = 1;
4018 #define CACHE_FPL_FAILED -2020
4021 cache_vop_bad_vexec(struct vop_fplookup_vexec_args *v)
4023 vn_printf(v->a_vp, "no proper vop_fplookup_vexec\n");
4024 panic("no proper vop_fplookup_vexec");
4028 cache_vop_bad_symlink(struct vop_fplookup_symlink_args *v)
4030 vn_printf(v->a_vp, "no proper vop_fplookup_symlink\n");
4031 panic("no proper vop_fplookup_symlink");
4035 cache_vop_vector_register(struct vop_vector *v)
4040 if (v->vop_fplookup_vexec != NULL) {
4043 if (v->vop_fplookup_symlink != NULL) {
4052 v->vop_fplookup_vexec = cache_vop_bad_vexec;
4053 v->vop_fplookup_symlink = cache_vop_bad_symlink;
4057 printf("%s: invalid vop vector %p -- either all or none fplookup vops "
4058 "need to be provided", __func__, v);
4059 if (v->vop_fplookup_vexec == NULL) {
4060 printf("%s: missing vop_fplookup_vexec\n", __func__);
4062 if (v->vop_fplookup_symlink == NULL) {
4063 printf("%s: missing vop_fplookup_symlink\n", __func__);
4065 panic("bad vop vector %p", v);
4070 cache_validate_vop_vector(struct mount *mp, struct vop_vector *vops)
4075 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4078 if (vops->vop_fplookup_vexec == NULL ||
4079 vops->vop_fplookup_vexec == cache_vop_bad_vexec)
4080 panic("bad vop_fplookup_vexec on vector %p for filesystem %s",
4081 vops, mp->mnt_vfc->vfc_name);
4083 if (vops->vop_fplookup_symlink == NULL ||
4084 vops->vop_fplookup_symlink == cache_vop_bad_symlink)
4085 panic("bad vop_fplookup_symlink on vector %p for filesystem %s",
4086 vops, mp->mnt_vfc->vfc_name);
4091 cache_fast_lookup_enabled_recalc(void)
4097 mac_on = mac_vnode_check_lookup_enabled();
4098 mac_on |= mac_vnode_check_readlink_enabled();
4103 lookup_flag = atomic_load_int(&cache_fast_lookup);
4104 if (lookup_flag && !mac_on) {
4105 atomic_store_char(&cache_fast_lookup_enabled, true);
4107 atomic_store_char(&cache_fast_lookup_enabled, false);
4112 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
4116 old = atomic_load_int(&cache_fast_lookup);
4117 error = sysctl_handle_int(oidp, arg1, arg2, req);
4118 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
4119 cache_fast_lookup_enabled_recalc();
4122 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
4123 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
4126 * Components of nameidata (or objects it can point to) which may
4127 * need restoring in case fast path lookup fails.
4129 struct nameidata_outer {
4134 struct nameidata_saved {
4142 struct cache_fpl_debug {
4148 struct nameidata *ndp;
4149 struct componentname *cnp;
4156 struct nameidata_saved snd;
4157 struct nameidata_outer snd_outer;
4159 enum cache_fpl_status status:8;
4164 struct cache_fpl_debug debug;
4168 static bool cache_fplookup_mp_supported(struct mount *mp);
4169 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
4170 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
4171 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
4172 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
4173 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
4174 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
4175 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
4176 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
4177 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
4180 cache_fpl_cleanup_cnp(struct componentname *cnp)
4183 uma_zfree(namei_zone, cnp->cn_pnbuf);
4184 cnp->cn_pnbuf = NULL;
4185 cnp->cn_nameptr = NULL;
4188 static struct vnode *
4189 cache_fpl_handle_root(struct cache_fpl *fpl)
4191 struct nameidata *ndp;
4192 struct componentname *cnp;
4197 MPASS(*(cnp->cn_nameptr) == '/');
4199 cache_fpl_pathlen_dec(fpl);
4201 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4204 cache_fpl_pathlen_dec(fpl);
4205 } while (*(cnp->cn_nameptr) == '/');
4208 return (ndp->ni_rootdir);
4212 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
4215 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
4216 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
4220 cache_fpl_checkpoint(struct cache_fpl *fpl)
4224 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
4225 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4230 cache_fpl_restore_partial(struct cache_fpl *fpl)
4233 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4235 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4240 cache_fpl_restore_abort(struct cache_fpl *fpl)
4243 cache_fpl_restore_partial(fpl);
4245 * It is 0 on entry by API contract.
4247 fpl->ndp->ni_resflags = 0;
4248 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4249 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4253 #define cache_fpl_smr_assert_entered(fpl) ({ \
4254 struct cache_fpl *_fpl = (fpl); \
4255 MPASS(_fpl->in_smr == true); \
4256 VFS_SMR_ASSERT_ENTERED(); \
4258 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4259 struct cache_fpl *_fpl = (fpl); \
4260 MPASS(_fpl->in_smr == false); \
4261 VFS_SMR_ASSERT_NOT_ENTERED(); \
4264 cache_fpl_assert_status(struct cache_fpl *fpl)
4267 switch (fpl->status) {
4268 case CACHE_FPL_STATUS_UNSET:
4269 __assert_unreachable();
4271 case CACHE_FPL_STATUS_DESTROYED:
4272 case CACHE_FPL_STATUS_ABORTED:
4273 case CACHE_FPL_STATUS_PARTIAL:
4274 case CACHE_FPL_STATUS_HANDLED:
4279 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4280 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4281 #define cache_fpl_assert_status(fpl) do { } while (0)
4284 #define cache_fpl_smr_enter_initial(fpl) ({ \
4285 struct cache_fpl *_fpl = (fpl); \
4287 _fpl->in_smr = true; \
4290 #define cache_fpl_smr_enter(fpl) ({ \
4291 struct cache_fpl *_fpl = (fpl); \
4292 MPASS(_fpl->in_smr == false); \
4294 _fpl->in_smr = true; \
4297 #define cache_fpl_smr_exit(fpl) ({ \
4298 struct cache_fpl *_fpl = (fpl); \
4299 MPASS(_fpl->in_smr == true); \
4301 _fpl->in_smr = false; \
4305 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4308 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4309 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4310 ("%s: converting to abort from %d at %d, set at %d\n",
4311 __func__, fpl->status, line, fpl->line));
4313 cache_fpl_smr_assert_not_entered(fpl);
4314 fpl->status = CACHE_FPL_STATUS_ABORTED;
4316 return (CACHE_FPL_FAILED);
4319 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4321 static int __noinline
4322 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4324 struct nameidata *ndp;
4325 struct componentname *cnp;
4330 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4331 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4332 ("%s: converting to abort from %d at %d, set at %d\n",
4333 __func__, fpl->status, line, fpl->line));
4335 fpl->status = CACHE_FPL_STATUS_ABORTED;
4338 cache_fpl_smr_exit(fpl);
4339 cache_fpl_restore_abort(fpl);
4341 * Resolving symlinks overwrites data passed by the caller.
4344 if (ndp->ni_loopcnt > 0) {
4345 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4346 cache_fpl_cleanup_cnp(cnp);
4348 return (CACHE_FPL_FAILED);
4351 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4353 static int __noinline
4354 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4357 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4358 ("%s: setting to partial at %d, but already set to %d at %d\n",
4359 __func__, line, fpl->status, fpl->line));
4360 cache_fpl_smr_assert_entered(fpl);
4361 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4363 return (cache_fplookup_partial_setup(fpl));
4366 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4369 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4372 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4373 ("%s: setting to handled at %d, but already set to %d at %d\n",
4374 __func__, line, fpl->status, fpl->line));
4375 cache_fpl_smr_assert_not_entered(fpl);
4376 fpl->status = CACHE_FPL_STATUS_HANDLED;
4381 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4384 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4387 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4388 ("%s: setting to handled at %d, but already set to %d at %d\n",
4389 __func__, line, fpl->status, fpl->line));
4391 MPASS(error != CACHE_FPL_FAILED);
4392 cache_fpl_smr_assert_not_entered(fpl);
4393 fpl->status = CACHE_FPL_STATUS_HANDLED;
4400 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4403 cache_fpl_terminated(struct cache_fpl *fpl)
4406 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4409 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4410 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4411 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | ISRESTARTED | WILLBEDIR | \
4412 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | OPENREAD | \
4413 OPENWRITE | WANTIOCTLCAPS)
4415 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4416 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4418 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4419 "supported and internal flags overlap");
4422 cache_fpl_islastcn(struct nameidata *ndp)
4425 return (*ndp->ni_next == 0);
4429 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4432 MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4433 return (*(fpl->nulchar - 1) == '/');
4437 cache_fpl_isdotdot(struct componentname *cnp)
4440 if (cnp->cn_namelen == 2 &&
4441 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4447 cache_can_fplookup(struct cache_fpl *fpl)
4449 struct nameidata *ndp;
4450 struct componentname *cnp;
4457 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4458 cache_fpl_aborted_early(fpl);
4461 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4462 cache_fpl_aborted_early(fpl);
4465 if (IN_CAPABILITY_MODE(td)) {
4466 cache_fpl_aborted_early(fpl);
4469 if (AUDITING_TD(td)) {
4470 cache_fpl_aborted_early(fpl);
4473 if (ndp->ni_startdir != NULL) {
4474 cache_fpl_aborted_early(fpl);
4480 static int __noinline
4481 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4483 struct nameidata *ndp;
4484 struct componentname *cnp;
4491 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4492 if (__predict_false(error != 0)) {
4493 return (cache_fpl_aborted(fpl));
4495 fpl->fsearch = fsearch;
4496 if ((*vpp)->v_type != VDIR) {
4497 if (!((cnp->cn_flags & EMPTYPATH) != 0 && cnp->cn_pnbuf[0] == '\0')) {
4498 cache_fpl_smr_exit(fpl);
4499 return (cache_fpl_handled_error(fpl, ENOTDIR));
4505 static int __noinline
4506 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4509 struct componentname *cnp;
4515 cache_fpl_smr_exit(fpl);
4516 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4517 return (cache_fpl_handled_error(fpl, ENOENT));
4519 return (cache_fpl_aborted(fpl));
4523 * The target vnode is not supported, prepare for the slow path to take over.
4525 static int __noinline
4526 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4528 struct nameidata *ndp;
4529 struct componentname *cnp;
4539 dvp_seqc = fpl->dvp_seqc;
4541 if (!pwd_hold_smr(pwd)) {
4542 return (cache_fpl_aborted(fpl));
4546 * Note that seqc is checked before the vnode is locked, so by
4547 * the time regular lookup gets to it it may have moved.
4549 * Ultimately this does not affect correctness, any lookup errors
4550 * are userspace racing with itself. It is guaranteed that any
4551 * path which ultimately gets found could also have been found
4552 * by regular lookup going all the way in absence of concurrent
4555 dvs = vget_prep_smr(dvp);
4556 cache_fpl_smr_exit(fpl);
4557 if (__predict_false(dvs == VGET_NONE)) {
4559 return (cache_fpl_aborted(fpl));
4562 vget_finish_ref(dvp, dvs);
4563 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4566 return (cache_fpl_aborted(fpl));
4569 cache_fpl_restore_partial(fpl);
4571 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4572 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4573 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4577 ndp->ni_startdir = dvp;
4578 cnp->cn_flags |= MAKEENTRY;
4579 if (cache_fpl_islastcn(ndp))
4580 cnp->cn_flags |= ISLASTCN;
4581 if (cache_fpl_isdotdot(cnp))
4582 cnp->cn_flags |= ISDOTDOT;
4585 * Skip potential extra slashes parsing did not take care of.
4586 * cache_fplookup_skip_slashes explains the mechanism.
4588 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4591 cache_fpl_pathlen_dec(fpl);
4592 } while (*(cnp->cn_nameptr) == '/');
4595 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4597 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4598 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4599 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4600 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4607 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4609 struct componentname *cnp;
4616 tvp_seqc = fpl->tvp_seqc;
4618 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4619 lkflags = LK_SHARED;
4620 if ((cnp->cn_flags & LOCKSHARED) == 0)
4621 lkflags = LK_EXCLUSIVE;
4622 error = vget_finish(tvp, lkflags, tvs);
4623 if (__predict_false(error != 0)) {
4624 return (cache_fpl_aborted(fpl));
4627 vget_finish_ref(tvp, tvs);
4630 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4631 if ((cnp->cn_flags & LOCKLEAF) != 0)
4635 return (cache_fpl_aborted(fpl));
4638 return (cache_fpl_handled(fpl));
4642 * They want to possibly modify the state of the namecache.
4644 static int __noinline
4645 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4647 struct nameidata *ndp __diagused;
4648 struct componentname *cnp;
4650 struct vnode *dvp, *tvp;
4659 dvp_seqc = fpl->dvp_seqc;
4661 MPASS(*(cnp->cn_nameptr) != '/');
4662 MPASS(cache_fpl_islastcn(ndp));
4663 if ((cnp->cn_flags & LOCKPARENT) == 0)
4664 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4665 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4666 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4667 cnp->cn_nameiop == RENAME);
4668 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4669 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4671 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4672 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4676 * Regular lookup nulifies the slash, which we don't do here.
4677 * Don't take chances with filesystem routines seeing it for
4680 if (cache_fpl_istrailingslash(fpl)) {
4681 return (cache_fpl_partial(fpl));
4684 mp = atomic_load_ptr(&dvp->v_mount);
4685 if (__predict_false(mp == NULL)) {
4686 return (cache_fpl_aborted(fpl));
4689 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4690 cache_fpl_smr_exit(fpl);
4692 * Original code keeps not checking for CREATE which
4693 * might be a bug. For now let the old lookup decide.
4695 if (cnp->cn_nameiop == CREATE) {
4696 return (cache_fpl_aborted(fpl));
4698 return (cache_fpl_handled_error(fpl, EROFS));
4701 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4702 cache_fpl_smr_exit(fpl);
4703 return (cache_fpl_handled_error(fpl, EEXIST));
4707 * Secure access to dvp; check cache_fplookup_partial_setup for
4710 * XXX At least UFS requires its lookup routine to be called for
4711 * the last path component, which leads to some level of complication
4713 * - the target routine always locks the target vnode, but our caller
4714 * may not need it locked
4715 * - some of the VOP machinery asserts that the parent is locked, which
4716 * once more may be not required
4718 * TODO: add a flag for filesystems which don't need this.
4720 dvs = vget_prep_smr(dvp);
4721 cache_fpl_smr_exit(fpl);
4722 if (__predict_false(dvs == VGET_NONE)) {
4723 return (cache_fpl_aborted(fpl));
4726 vget_finish_ref(dvp, dvs);
4727 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4729 return (cache_fpl_aborted(fpl));
4732 error = vn_lock(dvp, LK_EXCLUSIVE);
4733 if (__predict_false(error != 0)) {
4735 return (cache_fpl_aborted(fpl));
4739 cnp->cn_flags |= ISLASTCN;
4741 cnp->cn_flags |= MAKEENTRY;
4742 if (cache_fpl_isdotdot(cnp))
4743 cnp->cn_flags |= ISDOTDOT;
4744 cnp->cn_lkflags = LK_EXCLUSIVE;
4745 error = VOP_LOOKUP(dvp, &tvp, cnp);
4753 return (cache_fpl_handled_error(fpl, error));
4756 return (cache_fpl_aborted(fpl));
4762 MPASS(error == EJUSTRETURN);
4763 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4766 return (cache_fpl_handled(fpl));
4770 * There are very hairy corner cases concerning various flag combinations
4771 * and locking state. In particular here we only hold one lock instead of
4774 * Skip the complexity as it is of no significance for normal workloads.
4776 if (__predict_false(tvp == dvp)) {
4779 return (cache_fpl_aborted(fpl));
4783 * If they want the symlink itself we are fine, but if they want to
4784 * follow it regular lookup has to be engaged.
4786 if (tvp->v_type == VLNK) {
4787 if ((cnp->cn_flags & FOLLOW) != 0) {
4790 return (cache_fpl_aborted(fpl));
4795 * Since we expect this to be the terminal vnode it should almost never
4798 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4801 return (cache_fpl_aborted(fpl));
4804 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4807 return (cache_fpl_handled_error(fpl, EEXIST));
4810 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4814 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4818 return (cache_fpl_handled(fpl));
4821 static int __noinline
4822 cache_fplookup_modifying(struct cache_fpl *fpl)
4824 struct nameidata *ndp;
4828 if (!cache_fpl_islastcn(ndp)) {
4829 return (cache_fpl_partial(fpl));
4831 return (cache_fplookup_final_modifying(fpl));
4834 static int __noinline
4835 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4837 struct componentname *cnp;
4838 enum vgetstate dvs, tvs;
4839 struct vnode *dvp, *tvp;
4845 dvp_seqc = fpl->dvp_seqc;
4848 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4851 * This is less efficient than it can be for simplicity.
4853 dvs = vget_prep_smr(dvp);
4854 if (__predict_false(dvs == VGET_NONE)) {
4855 return (cache_fpl_aborted(fpl));
4857 tvs = vget_prep_smr(tvp);
4858 if (__predict_false(tvs == VGET_NONE)) {
4859 cache_fpl_smr_exit(fpl);
4860 vget_abort(dvp, dvs);
4861 return (cache_fpl_aborted(fpl));
4864 cache_fpl_smr_exit(fpl);
4866 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4867 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4868 if (__predict_false(error != 0)) {
4869 vget_abort(tvp, tvs);
4870 return (cache_fpl_aborted(fpl));
4873 vget_finish_ref(dvp, dvs);
4876 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4877 vget_abort(tvp, tvs);
4878 if ((cnp->cn_flags & LOCKPARENT) != 0)
4882 return (cache_fpl_aborted(fpl));
4885 error = cache_fplookup_final_child(fpl, tvs);
4886 if (__predict_false(error != 0)) {
4887 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4888 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4889 if ((cnp->cn_flags & LOCKPARENT) != 0)
4896 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4901 cache_fplookup_final(struct cache_fpl *fpl)
4903 struct componentname *cnp;
4905 struct vnode *dvp, *tvp;
4910 dvp_seqc = fpl->dvp_seqc;
4913 MPASS(*(cnp->cn_nameptr) != '/');
4915 if (cnp->cn_nameiop != LOOKUP) {
4916 return (cache_fplookup_final_modifying(fpl));
4919 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4920 return (cache_fplookup_final_withparent(fpl));
4922 tvs = vget_prep_smr(tvp);
4923 if (__predict_false(tvs == VGET_NONE)) {
4924 return (cache_fpl_partial(fpl));
4927 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4928 cache_fpl_smr_exit(fpl);
4929 vget_abort(tvp, tvs);
4930 return (cache_fpl_aborted(fpl));
4933 cache_fpl_smr_exit(fpl);
4934 return (cache_fplookup_final_child(fpl, tvs));
4938 * Comment from locked lookup:
4939 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4940 * directory, e.g. like "/." or ".".
4942 static int __noinline
4943 cache_fplookup_degenerate(struct cache_fpl *fpl)
4945 struct componentname *cnp;
4953 fpl->tvp = fpl->dvp;
4954 fpl->tvp_seqc = fpl->dvp_seqc;
4960 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4962 ("%s: encountered non-slash; string [%s]\n", __func__,
4967 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4968 cache_fpl_smr_exit(fpl);
4969 return (cache_fpl_handled_error(fpl, EISDIR));
4972 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4973 return (cache_fplookup_final_withparent(fpl));
4976 dvs = vget_prep_smr(dvp);
4977 cache_fpl_smr_exit(fpl);
4978 if (__predict_false(dvs == VGET_NONE)) {
4979 return (cache_fpl_aborted(fpl));
4982 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4983 lkflags = LK_SHARED;
4984 if ((cnp->cn_flags & LOCKSHARED) == 0)
4985 lkflags = LK_EXCLUSIVE;
4986 error = vget_finish(dvp, lkflags, dvs);
4987 if (__predict_false(error != 0)) {
4988 return (cache_fpl_aborted(fpl));
4991 vget_finish_ref(dvp, dvs);
4993 return (cache_fpl_handled(fpl));
4996 static int __noinline
4997 cache_fplookup_emptypath(struct cache_fpl *fpl)
4999 struct nameidata *ndp;
5000 struct componentname *cnp;
5005 fpl->tvp = fpl->dvp;
5006 fpl->tvp_seqc = fpl->dvp_seqc;
5012 MPASS(*cnp->cn_pnbuf == '\0');
5014 if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
5015 cache_fpl_smr_exit(fpl);
5016 return (cache_fpl_handled_error(fpl, ENOENT));
5019 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
5021 tvs = vget_prep_smr(tvp);
5022 cache_fpl_smr_exit(fpl);
5023 if (__predict_false(tvs == VGET_NONE)) {
5024 return (cache_fpl_aborted(fpl));
5027 if ((cnp->cn_flags & LOCKLEAF) != 0) {
5028 lkflags = LK_SHARED;
5029 if ((cnp->cn_flags & LOCKSHARED) == 0)
5030 lkflags = LK_EXCLUSIVE;
5031 error = vget_finish(tvp, lkflags, tvs);
5032 if (__predict_false(error != 0)) {
5033 return (cache_fpl_aborted(fpl));
5036 vget_finish_ref(tvp, tvs);
5039 ndp->ni_resflags |= NIRES_EMPTYPATH;
5040 return (cache_fpl_handled(fpl));
5043 static int __noinline
5044 cache_fplookup_noentry(struct cache_fpl *fpl)
5046 struct nameidata *ndp;
5047 struct componentname *cnp;
5049 struct vnode *dvp, *tvp;
5056 dvp_seqc = fpl->dvp_seqc;
5058 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
5059 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
5060 if (cnp->cn_nameiop == LOOKUP)
5061 MPASS((cnp->cn_flags & NOCACHE) == 0);
5062 MPASS(!cache_fpl_isdotdot(cnp));
5065 * Hack: delayed name len checking.
5067 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5068 cache_fpl_smr_exit(fpl);
5069 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5072 if (cnp->cn_nameptr[0] == '/') {
5073 return (cache_fplookup_skip_slashes(fpl));
5076 if (cnp->cn_pnbuf[0] == '\0') {
5077 return (cache_fplookup_emptypath(fpl));
5080 if (cnp->cn_nameptr[0] == '\0') {
5081 if (fpl->tvp == NULL) {
5082 return (cache_fplookup_degenerate(fpl));
5084 return (cache_fplookup_trailingslash(fpl));
5087 if (cnp->cn_nameiop != LOOKUP) {
5089 return (cache_fplookup_modifying(fpl));
5093 * Only try to fill in the component if it is the last one,
5094 * otherwise not only there may be several to handle but the
5095 * walk may be complicated.
5097 if (!cache_fpl_islastcn(ndp)) {
5098 return (cache_fpl_partial(fpl));
5102 * Regular lookup nulifies the slash, which we don't do here.
5103 * Don't take chances with filesystem routines seeing it for
5106 if (cache_fpl_istrailingslash(fpl)) {
5107 return (cache_fpl_partial(fpl));
5111 * Secure access to dvp; check cache_fplookup_partial_setup for
5114 dvs = vget_prep_smr(dvp);
5115 cache_fpl_smr_exit(fpl);
5116 if (__predict_false(dvs == VGET_NONE)) {
5117 return (cache_fpl_aborted(fpl));
5120 vget_finish_ref(dvp, dvs);
5121 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5123 return (cache_fpl_aborted(fpl));
5126 error = vn_lock(dvp, LK_SHARED);
5127 if (__predict_false(error != 0)) {
5129 return (cache_fpl_aborted(fpl));
5134 * TODO: provide variants which don't require locking either vnode.
5136 cnp->cn_flags |= ISLASTCN | MAKEENTRY;
5137 cnp->cn_lkflags = LK_SHARED;
5138 if ((cnp->cn_flags & LOCKSHARED) == 0) {
5139 cnp->cn_lkflags = LK_EXCLUSIVE;
5141 error = VOP_LOOKUP(dvp, &tvp, cnp);
5149 return (cache_fpl_handled_error(fpl, error));
5152 return (cache_fpl_aborted(fpl));
5158 MPASS(error == EJUSTRETURN);
5159 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5161 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5164 return (cache_fpl_handled(fpl));
5167 if (tvp->v_type == VLNK) {
5168 if ((cnp->cn_flags & FOLLOW) != 0) {
5171 return (cache_fpl_aborted(fpl));
5175 if (__predict_false(cache_fplookup_is_mp(fpl))) {
5178 return (cache_fpl_aborted(fpl));
5181 if ((cnp->cn_flags & LOCKLEAF) == 0) {
5185 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5187 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5190 return (cache_fpl_handled(fpl));
5193 static int __noinline
5194 cache_fplookup_dot(struct cache_fpl *fpl)
5198 MPASS(!seqc_in_modify(fpl->dvp_seqc));
5200 if (__predict_false(fpl->dvp->v_type != VDIR)) {
5201 cache_fpl_smr_exit(fpl);
5202 return (cache_fpl_handled_error(fpl, ENOTDIR));
5206 * Just re-assign the value. seqc will be checked later for the first
5207 * non-dot path component in line and/or before deciding to return the
5210 fpl->tvp = fpl->dvp;
5211 fpl->tvp_seqc = fpl->dvp_seqc;
5213 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
5216 if (cache_fplookup_is_mp(fpl)) {
5217 error = cache_fplookup_cross_mount(fpl);
5222 static int __noinline
5223 cache_fplookup_dotdot(struct cache_fpl *fpl)
5225 struct nameidata *ndp;
5226 struct componentname *cnp;
5227 struct namecache *ncp;
5236 MPASS(cache_fpl_isdotdot(cnp));
5239 * XXX this is racy the same way regular lookup is
5241 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5243 if (dvp == pr->pr_root)
5246 if (dvp == ndp->ni_rootdir ||
5247 dvp == ndp->ni_topdir ||
5251 fpl->tvp_seqc = vn_seqc_read_any(dvp);
5252 if (seqc_in_modify(fpl->tvp_seqc)) {
5253 return (cache_fpl_aborted(fpl));
5258 if ((dvp->v_vflag & VV_ROOT) != 0) {
5261 * The opposite of climb mount is needed here.
5263 return (cache_fpl_partial(fpl));
5266 if (__predict_false(dvp->v_type != VDIR)) {
5267 cache_fpl_smr_exit(fpl);
5268 return (cache_fpl_handled_error(fpl, ENOTDIR));
5271 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5273 return (cache_fpl_aborted(fpl));
5276 nc_flag = atomic_load_char(&ncp->nc_flag);
5277 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5278 if ((nc_flag & NCF_NEGATIVE) != 0)
5279 return (cache_fpl_aborted(fpl));
5280 fpl->tvp = ncp->nc_vp;
5282 fpl->tvp = ncp->nc_dvp;
5285 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5286 if (seqc_in_modify(fpl->tvp_seqc)) {
5287 return (cache_fpl_partial(fpl));
5291 * Acquire fence provided by vn_seqc_read_any above.
5293 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5294 return (cache_fpl_aborted(fpl));
5297 if (!cache_ncp_canuse(ncp)) {
5298 return (cache_fpl_aborted(fpl));
5304 static int __noinline
5305 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5307 u_char nc_flag __diagused;
5311 nc_flag = atomic_load_char(&ncp->nc_flag);
5312 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5315 * If they want to create an entry we need to replace this one.
5317 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5319 return (cache_fplookup_modifying(fpl));
5321 neg_promote = cache_neg_hit_prep(ncp);
5322 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5323 cache_neg_hit_abort(ncp);
5324 return (cache_fpl_partial(fpl));
5327 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5329 cache_neg_hit_finish(ncp);
5330 cache_fpl_smr_exit(fpl);
5331 return (cache_fpl_handled_error(fpl, ENOENT));
5335 * Resolve a symlink. Called by filesystem-specific routines.
5338 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5341 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5343 struct nameidata *ndp;
5344 struct componentname *cnp;
5350 if (__predict_false(len == 0)) {
5354 if (__predict_false(len > MAXPATHLEN - 2)) {
5355 if (cache_fpl_istrailingslash(fpl)) {
5360 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5362 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5363 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5364 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5365 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5369 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5370 return (ENAMETOOLONG);
5373 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5378 if (ndp->ni_pathlen > 1) {
5379 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5381 if (cache_fpl_istrailingslash(fpl)) {
5383 cnp->cn_pnbuf[len] = '/';
5384 cnp->cn_pnbuf[len + 1] = '\0';
5386 cnp->cn_pnbuf[len] = '\0';
5389 bcopy(string, cnp->cn_pnbuf, len);
5391 ndp->ni_pathlen += adjust;
5392 cache_fpl_pathlen_add(fpl, adjust);
5393 cnp->cn_nameptr = cnp->cn_pnbuf;
5394 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5399 static int __noinline
5400 cache_fplookup_symlink(struct cache_fpl *fpl)
5403 struct nameidata *ndp;
5404 struct componentname *cnp;
5405 struct vnode *dvp, *tvp;
5413 if (cache_fpl_islastcn(ndp)) {
5414 if ((cnp->cn_flags & FOLLOW) == 0) {
5415 return (cache_fplookup_final(fpl));
5419 mp = atomic_load_ptr(&dvp->v_mount);
5420 if (__predict_false(mp == NULL)) {
5421 return (cache_fpl_aborted(fpl));
5425 * Note this check races against setting the flag just like regular
5428 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5429 cache_fpl_smr_exit(fpl);
5430 return (cache_fpl_handled_error(fpl, EACCES));
5433 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5434 if (__predict_false(error != 0)) {
5437 return (cache_fpl_partial(fpl));
5441 cache_fpl_smr_exit(fpl);
5442 return (cache_fpl_handled_error(fpl, error));
5444 return (cache_fpl_aborted(fpl));
5448 if (*(cnp->cn_nameptr) == '/') {
5449 fpl->dvp = cache_fpl_handle_root(fpl);
5450 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5451 if (seqc_in_modify(fpl->dvp_seqc)) {
5452 return (cache_fpl_aborted(fpl));
5455 * The main loop assumes that ->dvp points to a vnode belonging
5456 * to a filesystem which can do lockless lookup, but the absolute
5457 * symlink can be wandering off to one which does not.
5459 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5460 if (__predict_false(mp == NULL)) {
5461 return (cache_fpl_aborted(fpl));
5463 if (!cache_fplookup_mp_supported(mp)) {
5464 cache_fpl_checkpoint(fpl);
5465 return (cache_fpl_partial(fpl));
5472 cache_fplookup_next(struct cache_fpl *fpl)
5474 struct componentname *cnp;
5475 struct namecache *ncp;
5476 struct vnode *dvp, *tvp;
5485 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5486 if (cnp->cn_namelen == 1) {
5487 return (cache_fplookup_dot(fpl));
5489 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5490 return (cache_fplookup_dotdot(fpl));
5494 MPASS(!cache_fpl_isdotdot(cnp));
5496 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5497 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5498 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5502 if (__predict_false(ncp == NULL)) {
5503 return (cache_fplookup_noentry(fpl));
5506 tvp = atomic_load_ptr(&ncp->nc_vp);
5507 nc_flag = atomic_load_char(&ncp->nc_flag);
5508 if ((nc_flag & NCF_NEGATIVE) != 0) {
5509 return (cache_fplookup_neg(fpl, ncp, hash));
5512 if (!cache_ncp_canuse(ncp)) {
5513 return (cache_fpl_partial(fpl));
5517 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5518 if (seqc_in_modify(fpl->tvp_seqc)) {
5519 return (cache_fpl_partial(fpl));
5522 counter_u64_add(numposhits, 1);
5523 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5526 if (cache_fplookup_is_mp(fpl)) {
5527 error = cache_fplookup_cross_mount(fpl);
5533 cache_fplookup_mp_supported(struct mount *mp)
5537 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5543 * Walk up the mount stack (if any).
5545 * Correctness is provided in the following ways:
5546 * - all vnodes are protected from freeing with SMR
5547 * - struct mount objects are type stable making them always safe to access
5548 * - stability of the particular mount is provided by busying it
5549 * - relationship between the vnode which is mounted on and the mount is
5550 * verified with the vnode sequence counter after busying
5551 * - association between root vnode of the mount and the mount is protected
5554 * From that point on we can read the sequence counter of the root vnode
5555 * and get the next mount on the stack (if any) using the same protection.
5557 * By the end of successful walk we are guaranteed the reached state was
5558 * indeed present at least at some point which matches the regular lookup.
5560 static int __noinline
5561 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5563 struct mount *mp, *prev_mp;
5564 struct mount_pcpu *mpcpu, *prev_mpcpu;
5569 vp_seqc = fpl->tvp_seqc;
5571 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5572 mp = atomic_load_ptr(&vp->v_mountedhere);
5573 if (__predict_false(mp == NULL)) {
5579 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5580 if (prev_mp != NULL)
5581 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5582 return (cache_fpl_partial(fpl));
5584 if (prev_mp != NULL)
5585 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5586 if (!vn_seqc_consistent(vp, vp_seqc)) {
5587 vfs_op_thread_exit_crit(mp, mpcpu);
5588 return (cache_fpl_partial(fpl));
5590 if (!cache_fplookup_mp_supported(mp)) {
5591 vfs_op_thread_exit_crit(mp, mpcpu);
5592 return (cache_fpl_partial(fpl));
5594 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5596 vfs_op_thread_exit_crit(mp, mpcpu);
5597 return (cache_fpl_partial(fpl));
5599 vp_seqc = vn_seqc_read_any(vp);
5600 if (seqc_in_modify(vp_seqc)) {
5601 vfs_op_thread_exit_crit(mp, mpcpu);
5602 return (cache_fpl_partial(fpl));
5606 mp = atomic_load_ptr(&vp->v_mountedhere);
5611 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5613 fpl->tvp_seqc = vp_seqc;
5617 static int __noinline
5618 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5621 struct mount_pcpu *mpcpu;
5626 vp_seqc = fpl->tvp_seqc;
5628 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5629 mp = atomic_load_ptr(&vp->v_mountedhere);
5630 if (__predict_false(mp == NULL)) {
5634 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5635 return (cache_fpl_partial(fpl));
5637 if (!vn_seqc_consistent(vp, vp_seqc)) {
5638 vfs_op_thread_exit_crit(mp, mpcpu);
5639 return (cache_fpl_partial(fpl));
5641 if (!cache_fplookup_mp_supported(mp)) {
5642 vfs_op_thread_exit_crit(mp, mpcpu);
5643 return (cache_fpl_partial(fpl));
5645 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5646 if (__predict_false(vp == NULL)) {
5647 vfs_op_thread_exit_crit(mp, mpcpu);
5648 return (cache_fpl_partial(fpl));
5650 vp_seqc = vn_seqc_read_any(vp);
5651 vfs_op_thread_exit_crit(mp, mpcpu);
5652 if (seqc_in_modify(vp_seqc)) {
5653 return (cache_fpl_partial(fpl));
5655 mp = atomic_load_ptr(&vp->v_mountedhere);
5656 if (__predict_false(mp != NULL)) {
5658 * There are possibly more mount points on top.
5659 * Normally this does not happen so for simplicity just start
5662 return (cache_fplookup_climb_mount(fpl));
5666 fpl->tvp_seqc = vp_seqc;
5671 * Check if a vnode is mounted on.
5674 cache_fplookup_is_mp(struct cache_fpl *fpl)
5679 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5685 * The code was originally copy-pasted from regular lookup and despite
5686 * clean ups leaves performance on the table. Any modifications here
5687 * must take into account that in case off fallback the resulting
5688 * nameidata state has to be compatible with the original.
5692 * Debug ni_pathlen tracking.
5696 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5699 fpl->debug.ni_pathlen += n;
5700 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5701 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5705 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5708 fpl->debug.ni_pathlen -= n;
5709 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5710 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5714 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5717 cache_fpl_pathlen_add(fpl, 1);
5721 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5724 cache_fpl_pathlen_sub(fpl, 1);
5728 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5733 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5738 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5743 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5749 cache_fplookup_parse(struct cache_fpl *fpl)
5751 struct nameidata *ndp;
5752 struct componentname *cnp;
5762 * Find the end of this path component, it is either / or nul.
5764 * Store / as a temporary sentinel so that we only have one character
5765 * to test for. Pathnames tend to be short so this should not be
5766 * resulting in cache misses.
5768 * TODO: fix this to be word-sized.
5770 MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5771 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5772 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5773 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5774 fpl->nulchar, cnp->cn_pnbuf));
5775 KASSERT(*fpl->nulchar == '\0',
5776 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5778 hash = cache_get_hash_iter_start(dvp);
5779 *fpl->nulchar = '/';
5780 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5781 KASSERT(*cp != '\0',
5782 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5784 hash = cache_get_hash_iter(*cp, hash);
5787 *fpl->nulchar = '\0';
5788 fpl->hash = cache_get_hash_iter_finish(hash);
5790 cnp->cn_namelen = cp - cnp->cn_nameptr;
5791 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5795 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5796 * we are going to fail this lookup with ENAMETOOLONG (see below).
5798 if (cnp->cn_namelen <= NAME_MAX) {
5799 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5800 panic("%s: mismatched hash for [%s] len %ld", __func__,
5801 cnp->cn_nameptr, cnp->cn_namelen);
5807 * Hack: we have to check if the found path component's length exceeds
5808 * NAME_MAX. However, the condition is very rarely true and check can
5809 * be elided in the common case -- if an entry was found in the cache,
5810 * then it could not have been too long to begin with.
5816 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5818 struct nameidata *ndp;
5819 struct componentname *cnp;
5824 cnp->cn_nameptr = ndp->ni_next;
5825 KASSERT(*(cnp->cn_nameptr) == '/',
5826 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5827 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5829 cache_fpl_pathlen_dec(fpl);
5833 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5835 * Lockless lookup tries to elide checking for spurious slashes and should they
5836 * be present is guaranteed to fail to find an entry. In this case the caller
5837 * must check if the name starts with a slash and call this routine. It is
5838 * going to fast forward across the spurious slashes and set the state up for
5841 static int __noinline
5842 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5844 struct nameidata *ndp;
5845 struct componentname *cnp;
5850 MPASS(*(cnp->cn_nameptr) == '/');
5853 cache_fpl_pathlen_dec(fpl);
5854 } while (*(cnp->cn_nameptr) == '/');
5857 * Go back to one slash so that cache_fplookup_parse_advance has
5858 * something to skip.
5861 cache_fpl_pathlen_inc(fpl);
5864 * cache_fplookup_parse_advance starts from ndp->ni_next
5866 ndp->ni_next = cnp->cn_nameptr;
5869 * See cache_fplookup_dot.
5871 fpl->tvp = fpl->dvp;
5872 fpl->tvp_seqc = fpl->dvp_seqc;
5878 * Handle trailing slashes (e.g., "foo/").
5880 * If a trailing slash is found the terminal vnode must be a directory.
5881 * Regular lookup shortens the path by nulifying the first trailing slash and
5882 * sets the TRAILINGSLASH flag to denote this took place. There are several
5883 * checks on it performed later.
5885 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5886 * manner relying on an invariant that a non-directory vnode will get a miss.
5887 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5889 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5890 * and denotes this is the last path component, which avoids looping back.
5892 * Only plain lookups are supported for now to restrict corner cases to handle.
5894 static int __noinline
5895 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5900 struct nameidata *ndp;
5901 struct componentname *cnp;
5902 struct namecache *ncp;
5904 char *cn_nameptr_orig, *cn_nameptr_slash;
5911 tvp_seqc = fpl->tvp_seqc;
5913 MPASS(fpl->dvp == fpl->tvp);
5914 KASSERT(cache_fpl_istrailingslash(fpl),
5915 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5917 KASSERT(cnp->cn_nameptr[0] == '\0',
5918 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5920 KASSERT(cnp->cn_namelen == 0,
5921 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5923 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5925 if (cnp->cn_nameiop != LOOKUP) {
5926 return (cache_fpl_aborted(fpl));
5929 if (__predict_false(tvp->v_type != VDIR)) {
5930 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5931 return (cache_fpl_aborted(fpl));
5933 cache_fpl_smr_exit(fpl);
5934 return (cache_fpl_handled_error(fpl, ENOTDIR));
5938 * Denote the last component.
5940 ndp->ni_next = &cnp->cn_nameptr[0];
5941 MPASS(cache_fpl_islastcn(ndp));
5944 * Unwind trailing slashes.
5946 cn_nameptr_orig = cnp->cn_nameptr;
5947 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5949 if (cnp->cn_nameptr[0] != '/') {
5955 * Unwind to the beginning of the path component.
5957 * Note the path may or may not have started with a slash.
5959 cn_nameptr_slash = cnp->cn_nameptr;
5960 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5962 if (cnp->cn_nameptr[0] == '/') {
5966 if (cnp->cn_nameptr[0] == '/') {
5970 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5971 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5972 cache_fpl_checkpoint(fpl);
5975 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5976 if (ni_pathlen != fpl->debug.ni_pathlen) {
5977 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5978 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5979 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5984 * If this was a "./" lookup the parent directory is already correct.
5986 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5991 * Otherwise we need to look it up.
5994 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5995 if (__predict_false(ncp == NULL)) {
5996 return (cache_fpl_aborted(fpl));
5998 nc_flag = atomic_load_char(&ncp->nc_flag);
5999 if ((nc_flag & NCF_ISDOTDOT) != 0) {
6000 return (cache_fpl_aborted(fpl));
6002 fpl->dvp = ncp->nc_dvp;
6003 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
6004 if (seqc_in_modify(fpl->dvp_seqc)) {
6005 return (cache_fpl_aborted(fpl));
6011 * See the API contract for VOP_FPLOOKUP_VEXEC.
6013 static int __noinline
6014 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
6016 struct componentname *cnp;
6022 dvp_seqc = fpl->dvp_seqc;
6025 * Hack: delayed empty path checking.
6027 if (cnp->cn_pnbuf[0] == '\0') {
6028 return (cache_fplookup_emptypath(fpl));
6032 * TODO: Due to ignoring trailing slashes lookup will perform a
6033 * permission check on the last dir when it should not be doing it. It
6034 * may fail, but said failure should be ignored. It is possible to fix
6035 * it up fully without resorting to regular lookup, but for now just
6038 if (cache_fpl_istrailingslash(fpl)) {
6039 return (cache_fpl_aborted(fpl));
6043 * Hack: delayed degenerate path checking.
6045 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
6046 return (cache_fplookup_degenerate(fpl));
6050 * Hack: delayed name len checking.
6052 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
6053 cache_fpl_smr_exit(fpl);
6054 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
6058 * Hack: they may be looking up foo/bar, where foo is not a directory.
6059 * In such a case we need to return ENOTDIR, but we may happen to get
6060 * here with a different error.
6062 if (dvp->v_type != VDIR) {
6067 * Hack: handle O_SEARCH.
6069 * Open Group Base Specifications Issue 7, 2018 edition states:
6071 * If the access mode of the open file description associated with the
6072 * file descriptor is not O_SEARCH, the function shall check whether
6073 * directory searches are permitted using the current permissions of
6074 * the directory underlying the file descriptor. If the access mode is
6075 * O_SEARCH, the function shall not perform the check.
6078 * Regular lookup tests for the NOEXECCHECK flag for every path
6079 * component to decide whether to do the permission check. However,
6080 * since most lookups never have the flag (and when they do it is only
6081 * present for the first path component), lockless lookup only acts on
6082 * it if there is a permission problem. Here the flag is represented
6083 * with a boolean so that we don't have to clear it on the way out.
6085 * For simplicity this always aborts.
6086 * TODO: check if this is the first lookup and ignore the permission
6087 * problem. Note the flag has to survive fallback (if it happens to be
6091 return (cache_fpl_aborted(fpl));
6096 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6097 error = cache_fpl_aborted(fpl);
6099 cache_fpl_partial(fpl);
6103 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6104 error = cache_fpl_aborted(fpl);
6106 cache_fpl_smr_exit(fpl);
6107 cache_fpl_handled_error(fpl, error);
6115 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
6117 struct nameidata *ndp;
6118 struct componentname *cnp;
6125 cache_fpl_checkpoint(fpl);
6128 * The vnode at hand is almost always stable, skip checking for it.
6129 * Worst case this postpones the check towards the end of the iteration
6133 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
6135 mp = atomic_load_ptr(&dvp->v_mount);
6136 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
6137 return (cache_fpl_aborted(fpl));
6140 MPASS(fpl->tvp == NULL);
6143 cache_fplookup_parse(fpl);
6145 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
6146 if (__predict_false(error != 0)) {
6147 error = cache_fplookup_failed_vexec(fpl, error);
6151 error = cache_fplookup_next(fpl);
6152 if (__predict_false(cache_fpl_terminated(fpl))) {
6156 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
6158 if (fpl->tvp->v_type == VLNK) {
6159 error = cache_fplookup_symlink(fpl);
6160 if (cache_fpl_terminated(fpl)) {
6164 if (cache_fpl_islastcn(ndp)) {
6165 error = cache_fplookup_final(fpl);
6169 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
6170 error = cache_fpl_aborted(fpl);
6174 fpl->dvp = fpl->tvp;
6175 fpl->dvp_seqc = fpl->tvp_seqc;
6176 cache_fplookup_parse_advance(fpl);
6179 cache_fpl_checkpoint(fpl);
6186 * Fast path lookup protected with SMR and sequence counters.
6188 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
6190 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
6193 * Traditional vnode lookup conceptually looks like this:
6199 * vn_unlock(current);
6206 * Each jump to the next vnode is safe memory-wise and atomic with respect to
6207 * any modifications thanks to holding respective locks.
6209 * The same guarantee can be provided with a combination of safe memory
6210 * reclamation and sequence counters instead. If all operations which affect
6211 * the relationship between the current vnode and the one we are looking for
6212 * also modify the counter, we can verify whether all the conditions held as
6213 * we made the jump. This includes things like permissions, mount points etc.
6214 * Counter modification is provided by enclosing relevant places in
6215 * vn_seqc_write_begin()/end() calls.
6217 * Thus this translates to:
6220 * dvp_seqc = seqc_read_any(dvp);
6221 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
6225 * tvp_seqc = seqc_read_any(tvp);
6226 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6228 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6230 * dvp = tvp; // we know nothing of importance has changed
6231 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6235 * vget(); // secure the vnode
6236 * if (!seqc_consistent(tvp, tvp_seqc) // final check
6238 * // at this point we know nothing has changed for any parent<->child pair
6239 * // as they were crossed during the lookup, meaning we matched the guarantee
6240 * // of the locked variant
6243 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6244 * - they are called while within vfs_smr protection which they must never exit
6245 * - EAGAIN can be returned to denote checking could not be performed, it is
6246 * always valid to return it
6247 * - if the sequence counter has not changed the result must be valid
6248 * - if the sequence counter has changed both false positives and false negatives
6249 * are permitted (since the result will be rejected later)
6250 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6252 * Caveats to watch out for:
6253 * - vnodes are passed unlocked and unreferenced with nothing stopping
6254 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6255 * to use atomic_load_ptr to fetch it.
6256 * - the aforementioned object can also get freed, meaning absent other means it
6257 * should be protected with vfs_smr
6258 * - either safely checking permissions as they are modified or guaranteeing
6259 * their stability is left to the routine
6262 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6265 struct cache_fpl fpl;
6268 struct componentname *cnp;
6271 fpl.status = CACHE_FPL_STATUS_UNSET;
6274 fpl.cnp = cnp = &ndp->ni_cnd;
6275 MPASS(ndp->ni_lcf == 0);
6276 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6277 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6279 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6280 MPASS(ndp->ni_resflags == 0);
6282 if (__predict_false(!cache_can_fplookup(&fpl))) {
6283 *status = fpl.status;
6284 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6285 return (EOPNOTSUPP);
6288 cache_fpl_checkpoint_outer(&fpl);
6290 cache_fpl_smr_enter_initial(&fpl);
6292 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6294 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6295 fpl.fsearch = false;
6296 fpl.tvp = NULL; /* for degenerate path handling */
6298 pwd = pwd_get_smr();
6300 namei_setup_rootdir(ndp, cnp, pwd);
6301 ndp->ni_topdir = pwd->pwd_jdir;
6303 if (cnp->cn_pnbuf[0] == '/') {
6304 dvp = cache_fpl_handle_root(&fpl);
6305 ndp->ni_resflags = NIRES_ABS;
6307 if (ndp->ni_dirfd == AT_FDCWD) {
6308 dvp = pwd->pwd_cdir;
6310 error = cache_fplookup_dirfd(&fpl, &dvp);
6311 if (__predict_false(error != 0)) {
6317 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6318 error = cache_fplookup_impl(dvp, &fpl);
6320 cache_fpl_smr_assert_not_entered(&fpl);
6321 cache_fpl_assert_status(&fpl);
6322 *status = fpl.status;
6323 if (SDT_PROBES_ENABLED()) {
6324 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6325 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6326 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6330 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6331 MPASS(error != CACHE_FPL_FAILED);
6333 cache_fpl_cleanup_cnp(fpl.cnp);
6334 MPASS(fpl.dvp == NULL);
6335 MPASS(fpl.tvp == NULL);
6337 ndp->ni_dvp = fpl.dvp;
6338 ndp->ni_vp = fpl.tvp;