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
35 #include <sys/cdefs.h>
37 #include "opt_ktrace.h"
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/capsicum.h>
42 #include <sys/counter.h>
43 #include <sys/filedesc.h>
44 #include <sys/fnv_hash.h>
45 #include <sys/kernel.h>
48 #include <sys/malloc.h>
49 #include <sys/fcntl.h>
51 #include <sys/mount.h>
52 #include <sys/namei.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysproto.h>
61 #include <sys/vnode.h>
64 #include <sys/ktrace.h>
67 #include <machine/_inttypes.h>
70 #include <security/audit/audit.h>
71 #include <security/mac/mac_framework.h>
80 * High level overview of name caching in the VFS layer.
82 * Originally caching was implemented as part of UFS, later extracted to allow
83 * use by other filesystems. A decision was made to make it optional and
84 * completely detached from the rest of the kernel, which comes with limitations
85 * outlined near the end of this comment block.
87 * This fundamental choice needs to be revisited. In the meantime, the current
88 * state is described below. Significance of all notable routines is explained
89 * in comments placed above their implementation. Scattered thoroughout the
90 * file are TODO comments indicating shortcomings which can be fixed without
91 * reworking everything (most of the fixes will likely be reusable). Various
92 * details are omitted from this explanation to not clutter the overview, they
93 * have to be checked by reading the code and associated commentary.
95 * Keep in mind that it's individual path components which are cached, not full
96 * paths. That is, for a fully cached path "foo/bar/baz" there are 3 entries,
99 * I. Data organization
101 * Entries are described by "struct namecache" objects and stored in a hash
102 * table. See cache_get_hash for more information.
104 * "struct vnode" contains pointers to source entries (names which can be found
105 * when traversing through said vnode), destination entries (names of that
106 * vnode (see "Limitations" for a breakdown on the subject) and a pointer to
109 * The (directory vnode; name) tuple reliably determines the target entry if
112 * Since there are no small locks at this time (all are 32 bytes in size on
113 * LP64), the code works around the problem by introducing lock arrays to
114 * protect hash buckets and vnode lists.
116 * II. Filesystem integration
118 * Filesystems participating in name caching do the following:
119 * - set vop_lookup routine to vfs_cache_lookup
120 * - set vop_cachedlookup to whatever can perform the lookup if the above fails
121 * - if they support lockless lookup (see below), vop_fplookup_vexec and
122 * vop_fplookup_symlink are set along with the MNTK_FPLOOKUP flag on the
124 * - call cache_purge or cache_vop_* routines to eliminate stale entries as
126 * - call cache_enter to add entries depending on the MAKEENTRY flag
128 * With the above in mind, there are 2 entry points when doing lookups:
129 * - ... -> namei -> cache_fplookup -- this is the default
130 * - ... -> VOP_LOOKUP -> vfs_cache_lookup -- normally only called by namei
131 * should the above fail
133 * Example code flow how an entry is added:
134 * ... -> namei -> cache_fplookup -> cache_fplookup_noentry -> VOP_LOOKUP ->
135 * vfs_cache_lookup -> VOP_CACHEDLOOKUP -> ufs_lookup_ino -> cache_enter
137 * III. Performance considerations
139 * For lockless case forward lookup avoids any writes to shared areas apart
140 * from the terminal path component. In other words non-modifying lookups of
141 * different files don't suffer any scalability problems in the namecache.
142 * Looking up the same file is limited by VFS and goes beyond the scope of this
145 * At least on amd64 the single-threaded bottleneck for long paths is hashing
146 * (see cache_get_hash). There are cases where the code issues acquire fence
147 * multiple times, they can be combined on architectures which suffer from it.
149 * For locked case each encountered vnode has to be referenced and locked in
150 * order to be handed out to the caller (normally that's namei). This
151 * introduces significant hit single-threaded and serialization multi-threaded.
153 * Reverse lookup (e.g., "getcwd") fully scales provided it is fully cached --
154 * avoids any writes to shared areas to any components.
156 * Unrelated insertions are partially serialized on updating the global entry
157 * counter and possibly serialized on colliding bucket or vnode locks.
161 * Note not everything has an explicit dtrace probe nor it should have, thus
162 * some of the one-liners below depend on implementation details.
166 * # Check what lookups failed to be handled in a lockless manner. Column 1 is
167 * # line number, column 2 is status code (see cache_fpl_status)
168 * dtrace -n 'vfs:fplookup:lookup:done { @[arg1, arg2] = count(); }'
170 * # Lengths of names added by binary name
171 * dtrace -n 'fbt::cache_enter_time:entry { @[execname] = quantize(args[2]->cn_namelen); }'
173 * # Same as above but only those which exceed 64 characters
174 * dtrace -n 'fbt::cache_enter_time:entry /args[2]->cn_namelen > 64/ { @[execname] = quantize(args[2]->cn_namelen); }'
176 * # Who is performing lookups with spurious slashes (e.g., "foo//bar") and what
178 * dtrace -n 'fbt::cache_fplookup_skip_slashes:entry { @[execname, stringof(args[0]->cnp->cn_pnbuf)] = count(); }'
180 * V. Limitations and implementation defects
182 * - since it is possible there is no entry for an open file, tools like
183 * "procstat" may fail to resolve fd -> vnode -> path to anything
184 * - even if a filesystem adds an entry, it may get purged (e.g., due to memory
185 * shortage) in which case the above problem applies
186 * - hardlinks are not tracked, thus if a vnode is reachable in more than one
187 * way, resolving a name may return a different path than the one used to
188 * open it (even if said path is still valid)
189 * - by default entries are not added for newly created files
190 * - adding an entry may need to evict negative entry first, which happens in 2
191 * distinct places (evicting on lookup, adding in a later VOP) making it
192 * impossible to simply reuse it
193 * - there is a simple scheme to evict negative entries as the cache is approaching
194 * its capacity, but it is very unclear if doing so is a good idea to begin with
195 * - vnodes are subject to being recycled even if target inode is left in memory,
196 * which loses the name cache entries when it perhaps should not. in case of tmpfs
197 * names get duplicated -- kept by filesystem itself and namecache separately
198 * - struct namecache has a fixed size and comes in 2 variants, often wasting
199 * space. now hard to replace with malloc due to dependence on SMR, which
200 * requires UMA zones to opt in
201 * - lack of better integration with the kernel also turns nullfs into a layered
202 * filesystem instead of something which can take advantage of caching
204 * Appendix A: where is the time lost, expanding on paragraph III
206 * While some care went into optimizing lookups, there is still plenty of
207 * performance left on the table, most notably from single-threaded standpoint.
208 * Below is a woefully incomplete list of changes which can help. Ideas are
209 * mostly sketched out, no claim is made all kinks or prerequisites are laid
212 * Note there is performance lost all over VFS.
214 * === SMR-only lookup
216 * For commonly used ops like stat(2), when the terminal vnode *is* cached,
217 * lockless lookup could refrain from refing/locking the found vnode and
218 * instead return while within the SMR section. Then a call to, say,
219 * vop_stat_smr could do the work (or fail with EAGAIN), finally the result
220 * would be validated with seqc not changing. This would be faster
221 * single-threaded as it dodges atomics and would provide full scalability for
222 * multicore uses. This would *not* work for open(2) or other calls which need
223 * the vnode to hang around for the long haul, but would work for aforementioned
224 * stat(2) but also access(2), readlink(2), realpathat(2) and probably more.
226 * === hotpatching for sdt probes
228 * They result in *tons* of branches all over with rather regrettable codegen
229 * at times. Removing sdt probes altogether gives over 2% boost in lookup rate.
230 * Reworking the code to patch itself at runtime with asm goto would solve it.
231 * asm goto is fully supported by gcc and clang.
235 * On all architectures it operates one byte at a time, while it could be
236 * word-sized instead thanks to the Mycroft trick.
238 * API itself is rather pessimal for path lookup, accepting arbitrary sizes and
239 * *optionally* filling in the length parameter.
241 * Instead a new routine (copyinpath?) could be introduced, demanding a buffer
242 * size which is a multiply of the word (and never zero), with the length
243 * always returned. On top of it the routine could be allowed to transform the
244 * buffer in arbitrary ways, most notably writing past the found length (not to
245 * be confused with writing past buffer size) -- this would allow word-sized
246 * movs while checking for '\0' later.
248 * === detour through namei
250 * Currently one suffers being called from namei, which then has to check if
251 * things worked out locklessly. Instead the lockless lookup could be the
252 * actual entry point which calls what is currently namei as a fallback.
254 * === avoidable branches in cache_can_fplookup
256 * The cache_fast_lookup_enabled flag check could be hotpatchable (in fact if
257 * this is off, none of fplookup code should execute).
259 * Both audit and capsicum branches can be combined into one, but it requires
260 * paying off a lot of tech debt first.
262 * ni_startdir could be indicated with a flag in cn_flags, eliminating the
267 * Crossing a mount requires checking if perhaps something is mounted on top.
268 * Instead, an additional entry could be added to struct mount with a pointer
269 * to the final mount on the stack. This would be recalculated on each
274 * It could become part of the API contract to *always* have a rootvnode set in
275 * mnt_rootvnode. Such vnodes are annotated with VV_ROOT and vnlru would have
276 * to be modified to always skip them.
278 * === inactive on v_usecount reaching 0
280 * VOP_NEED_INACTIVE should not exist. Filesystems would indicate need for such
281 * processing with a bit in usecount.
285 * Hold count should probably get eliminated, but one can argue it is a useful
286 * feature. Even if so, handling of v_usecount could be decoupled from it --
287 * vnlru et al would consider the vnode not-freeable if has either hold or
290 * This would eliminate 2 atomics.
293 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
296 SDT_PROVIDER_DECLARE(vfs);
297 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
299 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
301 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
303 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
305 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
306 "struct namecache *", "int", "int");
307 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
308 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
309 "char *", "struct vnode *");
310 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
311 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
312 "struct vnode *", "char *");
313 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
315 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
316 "struct vnode *", "char *");
317 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
319 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
320 "struct componentname *");
321 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
322 "struct componentname *");
323 SDT_PROBE_DEFINE3(vfs, namecache, purge, done, "struct vnode *", "size_t", "size_t");
324 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
325 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
326 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
327 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
329 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
331 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
333 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
335 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
336 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
337 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
339 static char __read_frequently cache_fast_lookup_enabled = true;
342 * This structure describes the elements in the cache of recent
343 * names looked up by namei.
349 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
350 "the state must fit in a union with a pointer without growing it");
353 LIST_ENTRY(namecache) nc_src; /* source vnode list */
354 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
355 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
356 struct vnode *nc_dvp; /* vnode of parent of name */
358 struct vnode *nu_vp; /* vnode the name refers to */
359 struct negstate nu_neg;/* negative entry state */
361 u_char nc_flag; /* flag bits */
362 u_char nc_nlen; /* length of name */
363 char nc_name[]; /* segment name + nul */
367 * struct namecache_ts repeats struct namecache layout up to the
369 * struct namecache_ts is used in place of struct namecache when time(s) need
370 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
371 * both a non-dotdot directory name plus dotdot for the directory's
374 * See below for alignment requirement.
376 struct namecache_ts {
377 struct timespec nc_time; /* timespec provided by fs */
378 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
379 int nc_ticks; /* ticks value when entry was added */
381 struct namecache nc_nc;
384 TAILQ_HEAD(cache_freebatch, namecache);
387 * At least mips n32 performs 64-bit accesses to timespec as found
388 * in namecache_ts and requires them to be aligned. Since others
389 * may be in the same spot suffer a little bit and enforce the
390 * alignment for everyone. Note this is a nop for 64-bit platforms.
392 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
395 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
396 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
397 * smaller and the value was bumped to retain the total size, but it
398 * was never re-evaluated for suitability. A simple test counting
399 * lengths during package building shows that the value of 45 covers
400 * about 86% of all added entries, reaching 99% at 65.
402 * Regardless of the above, use of dedicated zones instead of malloc may be
403 * inducing additional waste. This may be hard to address as said zones are
404 * tied to VFS SMR. Even if retaining them, the current split should be
408 #define CACHE_PATH_CUTOFF 45
409 #define CACHE_LARGE_PAD 6
411 #define CACHE_PATH_CUTOFF 41
412 #define CACHE_LARGE_PAD 2
415 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
416 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
417 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
418 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
420 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
421 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
422 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
423 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
425 #define nc_vp n_un.nu_vp
426 #define nc_neg n_un.nu_neg
429 * Flags in namecache.nc_flag
431 #define NCF_WHITE 0x01
432 #define NCF_ISDOTDOT 0x02
435 #define NCF_DVDROP 0x10
436 #define NCF_NEGATIVE 0x20
437 #define NCF_INVALID 0x40
441 * Flags in negstate.neg_flag
445 static bool cache_neg_evict_cond(u_long lnumcache);
448 * Mark an entry as invalid.
450 * This is called before it starts getting deconstructed.
453 cache_ncp_invalidate(struct namecache *ncp)
456 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
457 ("%s: entry %p already invalid", __func__, ncp));
458 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
459 atomic_thread_fence_rel();
463 * Check whether the entry can be safely used.
465 * All places which elide locks are supposed to call this after they are
466 * done with reading from an entry.
468 #define cache_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)) == 0); \
478 * Like the above but also checks NCF_WHITE.
480 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
481 struct namecache *_ncp = (ncp); \
484 atomic_thread_fence_acq(); \
485 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
486 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
491 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
492 "Name cache parameters");
494 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
495 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RD, &ncsize, 0,
496 "Total namecache capacity");
498 u_int ncsizefactor = 2;
499 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
500 "Size factor for namecache");
502 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
503 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
504 "Ratio of negative namecache entries");
507 * Negative entry % of namecache capacity above which automatic eviction is allowed.
509 * Check cache_neg_evict_cond for details.
511 static u_int ncnegminpct = 3;
513 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
514 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
515 "Negative entry count above which automatic eviction is allowed");
518 * Structures associated with name caching.
520 #define NCHHASH(hash) \
521 (&nchashtbl[(hash) & nchash])
522 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
523 static u_long __read_mostly nchash; /* size of hash table */
524 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
525 "Size of namecache hash table");
526 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
527 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
529 struct nchstats nchstats; /* cache effectiveness statistics */
531 static u_int __exclusive_cache_line neg_cycle;
534 #define numneglists (ncneghash + 1)
537 struct mtx nl_evict_lock;
538 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
539 TAILQ_HEAD(, namecache) nl_list;
540 TAILQ_HEAD(, namecache) nl_hotlist;
542 } __aligned(CACHE_LINE_SIZE);
544 static struct neglist neglists[numneglists];
546 static inline struct neglist *
547 NCP2NEGLIST(struct namecache *ncp)
550 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
553 static inline struct negstate *
554 NCP2NEGSTATE(struct namecache *ncp)
557 MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
558 return (&ncp->nc_neg);
561 #define numbucketlocks (ncbuckethash + 1)
562 static u_int __read_mostly ncbuckethash;
563 static struct mtx_padalign __read_mostly *bucketlocks;
564 #define HASH2BUCKETLOCK(hash) \
565 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
567 #define numvnodelocks (ncvnodehash + 1)
568 static u_int __read_mostly ncvnodehash;
569 static struct mtx __read_mostly *vnodelocks;
570 static inline struct mtx *
571 VP2VNODELOCK(struct vnode *vp)
574 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
578 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
580 struct namecache_ts *ncp_ts;
582 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
583 (tsp == NULL && ticksp == NULL),
589 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
590 *tsp = ncp_ts->nc_time;
591 *ticksp = ncp_ts->nc_ticks;
595 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
596 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
597 "VFS namecache enabled");
600 /* Export size information to userland */
601 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
602 sizeof(struct namecache), "sizeof(struct namecache)");
605 * The new name cache statistics
607 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
608 "Name cache statistics");
610 #define STATNODE_ULONG(name, varname, descr) \
611 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
612 #define STATNODE_COUNTER(name, varname, descr) \
613 static COUNTER_U64_DEFINE_EARLY(varname); \
614 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
616 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
617 STATNODE_ULONG(count, numcache, "Number of cache entries");
618 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
619 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
620 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
621 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
622 STATNODE_COUNTER(poszaps, numposzaps,
623 "Number of cache hits (positive) we do not want to cache");
624 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
625 STATNODE_COUNTER(negzaps, numnegzaps,
626 "Number of cache hits (negative) we do not want to cache");
627 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
628 /* These count for vn_getcwd(), too. */
629 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
630 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
631 "Number of fullpath search errors (VOP_VPTOCNP failures)");
632 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
633 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
634 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
637 * Debug or developer statistics.
639 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
640 "Name cache debugging");
641 #define DEBUGNODE_ULONG(name, varname, descr) \
642 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
643 static u_long zap_bucket_relock_success;
644 DEBUGNODE_ULONG(zap_bucket_relock_success, zap_bucket_relock_success,
645 "Number of successful removals after relocking");
646 static u_long zap_bucket_fail;
647 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
648 static u_long zap_bucket_fail2;
649 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
650 static u_long cache_lock_vnodes_cel_3_failures;
651 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
652 "Number of times 3-way vnode locking failed");
654 static void cache_zap_locked(struct namecache *ncp);
655 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
656 char **retbuf, size_t *buflen, size_t addend);
657 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
658 char **retbuf, size_t *buflen);
659 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
660 char **retbuf, size_t *len, size_t addend);
662 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
665 cache_assert_vlp_locked(struct mtx *vlp)
669 mtx_assert(vlp, MA_OWNED);
673 cache_assert_vnode_locked(struct vnode *vp)
677 vlp = VP2VNODELOCK(vp);
678 cache_assert_vlp_locked(vlp);
682 * Directory vnodes with entries are held for two reasons:
683 * 1. make them less of a target for reclamation in vnlru
684 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
686 * It will be feasible to stop doing it altogether if all filesystems start
687 * supporting lockless lookup.
690 cache_hold_vnode(struct vnode *vp)
693 cache_assert_vnode_locked(vp);
694 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
696 counter_u64_add(numcachehv, 1);
700 cache_drop_vnode(struct vnode *vp)
704 * Called after all locks are dropped, meaning we can't assert
705 * on the state of v_cache_src.
708 counter_u64_add(numcachehv, -1);
714 static uma_zone_t __read_mostly cache_zone_small;
715 static uma_zone_t __read_mostly cache_zone_small_ts;
716 static uma_zone_t __read_mostly cache_zone_large;
717 static uma_zone_t __read_mostly cache_zone_large_ts;
720 cache_symlink_alloc(size_t size, int flags)
723 if (size < CACHE_ZONE_SMALL_SIZE) {
724 return (uma_zalloc_smr(cache_zone_small, flags));
726 if (size < CACHE_ZONE_LARGE_SIZE) {
727 return (uma_zalloc_smr(cache_zone_large, flags));
729 counter_u64_add(symlinktoobig, 1);
730 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
735 cache_symlink_free(char *string, size_t size)
738 MPASS(string != NULL);
739 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
740 ("%s: size %zu too big", __func__, size));
742 if (size < CACHE_ZONE_SMALL_SIZE) {
743 uma_zfree_smr(cache_zone_small, string);
746 if (size < CACHE_ZONE_LARGE_SIZE) {
747 uma_zfree_smr(cache_zone_large, string);
750 __assert_unreachable();
753 static struct namecache *
754 cache_alloc_uma(int len, bool ts)
756 struct namecache_ts *ncp_ts;
757 struct namecache *ncp;
759 if (__predict_false(ts)) {
760 if (len <= CACHE_PATH_CUTOFF)
761 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
763 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
764 ncp = &ncp_ts->nc_nc;
766 if (len <= CACHE_PATH_CUTOFF)
767 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
769 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
775 cache_free_uma(struct namecache *ncp)
777 struct namecache_ts *ncp_ts;
779 if (__predict_false(ncp->nc_flag & NCF_TS)) {
780 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
781 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
782 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
784 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
786 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
787 uma_zfree_smr(cache_zone_small, ncp);
789 uma_zfree_smr(cache_zone_large, ncp);
793 static struct namecache *
794 cache_alloc(int len, bool ts)
799 * Avoid blowout in namecache entries.
802 * 1. filesystems may end up trying to add an already existing entry
803 * (for example this can happen after a cache miss during concurrent
804 * lookup), in which case we will call cache_neg_evict despite not
806 * 2. the routine may fail to free anything and no provisions are made
807 * to make it try harder (see the inside for failure modes)
808 * 3. it only ever looks at negative entries.
810 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
811 if (cache_neg_evict_cond(lnumcache)) {
812 lnumcache = atomic_load_long(&numcache);
814 if (__predict_false(lnumcache >= ncsize)) {
815 atomic_subtract_long(&numcache, 1);
816 counter_u64_add(numdrops, 1);
819 return (cache_alloc_uma(len, ts));
823 cache_free(struct namecache *ncp)
827 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
828 cache_drop_vnode(ncp->nc_dvp);
831 atomic_subtract_long(&numcache, 1);
835 cache_free_batch(struct cache_freebatch *batch)
837 struct namecache *ncp, *nnp;
841 if (TAILQ_EMPTY(batch))
843 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
844 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
845 cache_drop_vnode(ncp->nc_dvp);
850 atomic_subtract_long(&numcache, i);
852 SDT_PROBE1(vfs, namecache, purge, batch, i);
858 * The code was made to use FNV in 2001 and this choice needs to be revisited.
860 * Short summary of the difficulty:
861 * The longest name which can be inserted is NAME_MAX characters in length (or
862 * 255 at the time of writing this comment), while majority of names used in
863 * practice are significantly shorter (mostly below 10). More importantly
864 * majority of lookups performed find names are even shorter than that.
866 * This poses a problem where hashes which do better than FNV past word size
867 * (or so) tend to come with additional overhead when finalizing the result,
868 * making them noticeably slower for the most commonly used range.
870 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
872 * When looking it up the most time consuming part by a large margin (at least
873 * on amd64) is hashing. Replacing FNV with something which pessimizes short
874 * input would make the slowest part stand out even more.
878 * TODO: With the value stored we can do better than computing the hash based
882 cache_prehash(struct vnode *vp)
885 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
889 cache_get_hash(char *name, u_char len, struct vnode *dvp)
892 return (fnv_32_buf(name, len, dvp->v_nchash));
896 cache_get_hash_iter_start(struct vnode *dvp)
899 return (dvp->v_nchash);
903 cache_get_hash_iter(char c, uint32_t hash)
906 return (fnv_32_buf(&c, 1, hash));
910 cache_get_hash_iter_finish(uint32_t hash)
916 static inline struct nchashhead *
917 NCP2BUCKET(struct namecache *ncp)
921 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
922 return (NCHHASH(hash));
925 static inline struct mtx *
926 NCP2BUCKETLOCK(struct namecache *ncp)
930 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
931 return (HASH2BUCKETLOCK(hash));
936 cache_assert_bucket_locked(struct namecache *ncp)
940 blp = NCP2BUCKETLOCK(ncp);
941 mtx_assert(blp, MA_OWNED);
945 cache_assert_bucket_unlocked(struct namecache *ncp)
949 blp = NCP2BUCKETLOCK(ncp);
950 mtx_assert(blp, MA_NOTOWNED);
953 #define cache_assert_bucket_locked(x) do { } while (0)
954 #define cache_assert_bucket_unlocked(x) do { } while (0)
957 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
959 _cache_sort_vnodes(void **p1, void **p2)
963 MPASS(*p1 != NULL || *p2 != NULL);
973 cache_lock_all_buckets(void)
977 for (i = 0; i < numbucketlocks; i++)
978 mtx_lock(&bucketlocks[i]);
982 cache_unlock_all_buckets(void)
986 for (i = 0; i < numbucketlocks; i++)
987 mtx_unlock(&bucketlocks[i]);
991 cache_lock_all_vnodes(void)
995 for (i = 0; i < numvnodelocks; i++)
996 mtx_lock(&vnodelocks[i]);
1000 cache_unlock_all_vnodes(void)
1004 for (i = 0; i < numvnodelocks; i++)
1005 mtx_unlock(&vnodelocks[i]);
1009 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
1012 cache_sort_vnodes(&vlp1, &vlp2);
1015 if (!mtx_trylock(vlp1))
1018 if (!mtx_trylock(vlp2)) {
1028 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
1031 MPASS(vlp1 != NULL || vlp2 != NULL);
1032 MPASS(vlp1 <= vlp2);
1041 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
1044 MPASS(vlp1 != NULL || vlp2 != NULL);
1053 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
1055 struct nchstats snap;
1057 if (req->oldptr == NULL)
1058 return (SYSCTL_OUT(req, 0, sizeof(snap)));
1061 snap.ncs_goodhits = counter_u64_fetch(numposhits);
1062 snap.ncs_neghits = counter_u64_fetch(numneghits);
1063 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
1064 counter_u64_fetch(numnegzaps);
1065 snap.ncs_miss = counter_u64_fetch(nummisszap) +
1066 counter_u64_fetch(nummiss);
1068 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
1070 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
1071 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
1072 "VFS cache effectiveness statistics");
1075 cache_recalc_neg_min(void)
1078 neg_min = (ncsize * ncnegminpct) / 100;
1082 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1088 error = sysctl_handle_int(oidp, &val, 0, req);
1089 if (error != 0 || req->newptr == NULL)
1092 if (val == ncnegminpct)
1094 if (val < 0 || val > 99)
1097 cache_recalc_neg_min();
1101 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1102 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1103 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1107 * Grab an atomic snapshot of the name cache hash chain lengths
1109 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1110 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1111 "hash table stats");
1114 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1116 struct nchashhead *ncpp;
1117 struct namecache *ncp;
1118 int i, error, n_nchash, *cntbuf;
1121 n_nchash = nchash + 1; /* nchash is max index, not count */
1122 if (req->oldptr == NULL)
1123 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1124 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1125 cache_lock_all_buckets();
1126 if (n_nchash != nchash + 1) {
1127 cache_unlock_all_buckets();
1128 free(cntbuf, M_TEMP);
1131 /* Scan hash tables counting entries */
1132 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1133 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1135 cache_unlock_all_buckets();
1136 for (error = 0, i = 0; i < n_nchash; i++)
1137 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1139 free(cntbuf, M_TEMP);
1142 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1143 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1144 "nchash chain lengths");
1147 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1150 struct nchashhead *ncpp;
1151 struct namecache *ncp;
1153 int count, maxlength, used, pct;
1156 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1158 cache_lock_all_buckets();
1159 n_nchash = nchash + 1; /* nchash is max index, not count */
1163 /* Scan hash tables for applicable entries */
1164 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1166 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1171 if (maxlength < count)
1174 n_nchash = nchash + 1;
1175 cache_unlock_all_buckets();
1176 pct = (used * 100) / (n_nchash / 100);
1177 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1180 error = SYSCTL_OUT(req, &used, sizeof(used));
1183 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1186 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1191 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1192 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1193 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1197 * Negative entries management
1199 * Various workloads create plenty of negative entries and barely use them
1200 * afterwards. Moreover malicious users can keep performing bogus lookups
1201 * adding even more entries. For example "make tinderbox" as of writing this
1202 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1205 * As such, a rather aggressive eviction method is needed. The currently
1206 * employed method is a placeholder.
1208 * Entries are split over numneglists separate lists, each of which is further
1209 * split into hot and cold entries. Entries get promoted after getting a hit.
1210 * Eviction happens on addition of new entry.
1212 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1213 "Name cache negative entry statistics");
1215 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1216 "Number of negative cache entries");
1218 static COUNTER_U64_DEFINE_EARLY(neg_created);
1219 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1220 "Number of created negative entries");
1222 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1223 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1224 "Number of evicted negative entries");
1226 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1227 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1228 &neg_evict_skipped_empty,
1229 "Number of times evicting failed due to lack of entries");
1231 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1232 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1233 &neg_evict_skipped_missed,
1234 "Number of times evicting failed due to target entry disappearing");
1236 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1237 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1238 &neg_evict_skipped_contended,
1239 "Number of times evicting failed due to contention");
1241 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1242 "Number of cache hits (negative)");
1245 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1250 for (i = 0; i < numneglists; i++)
1251 out += neglists[i].nl_hotnum;
1253 return (SYSCTL_OUT(req, &out, sizeof(out)));
1255 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1256 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1257 "Number of hot negative entries");
1260 cache_neg_init(struct namecache *ncp)
1262 struct negstate *ns;
1264 ncp->nc_flag |= NCF_NEGATIVE;
1265 ns = NCP2NEGSTATE(ncp);
1268 counter_u64_add(neg_created, 1);
1271 #define CACHE_NEG_PROMOTION_THRESH 2
1274 cache_neg_hit_prep(struct namecache *ncp)
1276 struct negstate *ns;
1279 ns = NCP2NEGSTATE(ncp);
1280 n = atomic_load_char(&ns->neg_hit);
1282 if (n >= CACHE_NEG_PROMOTION_THRESH)
1284 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1287 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1291 * Nothing to do here but it is provided for completeness as some
1292 * cache_neg_hit_prep callers may end up returning without even
1293 * trying to promote.
1295 #define cache_neg_hit_abort(ncp) do { } while (0)
1298 cache_neg_hit_finish(struct namecache *ncp)
1301 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1302 counter_u64_add(numneghits, 1);
1306 * Move a negative entry to the hot list.
1309 cache_neg_promote_locked(struct namecache *ncp)
1312 struct negstate *ns;
1314 ns = NCP2NEGSTATE(ncp);
1315 nl = NCP2NEGLIST(ncp);
1316 mtx_assert(&nl->nl_lock, MA_OWNED);
1317 if ((ns->neg_flag & NEG_HOT) == 0) {
1318 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1319 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1321 ns->neg_flag |= NEG_HOT;
1326 * Move a hot negative entry to the cold list.
1329 cache_neg_demote_locked(struct namecache *ncp)
1332 struct negstate *ns;
1334 ns = NCP2NEGSTATE(ncp);
1335 nl = NCP2NEGLIST(ncp);
1336 mtx_assert(&nl->nl_lock, MA_OWNED);
1337 MPASS(ns->neg_flag & NEG_HOT);
1338 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1339 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1341 ns->neg_flag &= ~NEG_HOT;
1342 atomic_store_char(&ns->neg_hit, 0);
1346 * Move a negative entry to the hot list if it matches the lookup.
1348 * We have to take locks, but they may be contended and in the worst
1349 * case we may need to go off CPU. We don't want to spin within the
1350 * smr section and we can't block with it. Exiting the section means
1351 * the found entry could have been evicted. We are going to look it
1355 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1356 struct namecache *oncp, uint32_t hash)
1358 struct namecache *ncp;
1362 nl = NCP2NEGLIST(oncp);
1364 mtx_lock(&nl->nl_lock);
1366 * For hash iteration.
1371 * Avoid all surprises by only succeeding if we got the same entry and
1372 * bailing completely otherwise.
1373 * XXX There are no provisions to keep the vnode around, meaning we may
1374 * end up promoting a negative entry for a *new* vnode and returning
1375 * ENOENT on its account. This is the error we want to return anyway
1376 * and promotion is harmless.
1378 * In particular at this point there can be a new ncp which matches the
1379 * search but hashes to a different neglist.
1381 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1387 * No match to begin with.
1389 if (__predict_false(ncp == NULL)) {
1394 * The newly found entry may be something different...
1396 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1397 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1402 * ... and not even negative.
1404 nc_flag = atomic_load_char(&ncp->nc_flag);
1405 if ((nc_flag & NCF_NEGATIVE) == 0) {
1409 if (!cache_ncp_canuse(ncp)) {
1413 cache_neg_promote_locked(ncp);
1414 cache_neg_hit_finish(ncp);
1416 mtx_unlock(&nl->nl_lock);
1420 mtx_unlock(&nl->nl_lock);
1425 cache_neg_promote(struct namecache *ncp)
1429 nl = NCP2NEGLIST(ncp);
1430 mtx_lock(&nl->nl_lock);
1431 cache_neg_promote_locked(ncp);
1432 mtx_unlock(&nl->nl_lock);
1436 cache_neg_insert(struct namecache *ncp)
1440 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1441 cache_assert_bucket_locked(ncp);
1442 nl = NCP2NEGLIST(ncp);
1443 mtx_lock(&nl->nl_lock);
1444 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1445 mtx_unlock(&nl->nl_lock);
1446 atomic_add_long(&numneg, 1);
1450 cache_neg_remove(struct namecache *ncp)
1453 struct negstate *ns;
1455 cache_assert_bucket_locked(ncp);
1456 nl = NCP2NEGLIST(ncp);
1457 ns = NCP2NEGSTATE(ncp);
1458 mtx_lock(&nl->nl_lock);
1459 if ((ns->neg_flag & NEG_HOT) != 0) {
1460 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1463 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1465 mtx_unlock(&nl->nl_lock);
1466 atomic_subtract_long(&numneg, 1);
1469 static struct neglist *
1470 cache_neg_evict_select_list(void)
1475 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1476 nl = &neglists[c % numneglists];
1477 if (!mtx_trylock(&nl->nl_evict_lock)) {
1478 counter_u64_add(neg_evict_skipped_contended, 1);
1484 static struct namecache *
1485 cache_neg_evict_select_entry(struct neglist *nl)
1487 struct namecache *ncp, *lncp;
1488 struct negstate *ns, *lns;
1491 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1492 mtx_assert(&nl->nl_lock, MA_OWNED);
1493 ncp = TAILQ_FIRST(&nl->nl_list);
1497 lns = NCP2NEGSTATE(lncp);
1498 for (i = 1; i < 4; i++) {
1499 ncp = TAILQ_NEXT(ncp, nc_dst);
1502 ns = NCP2NEGSTATE(ncp);
1503 if (ns->neg_hit < lns->neg_hit) {
1512 cache_neg_evict(void)
1514 struct namecache *ncp, *ncp2;
1523 nl = cache_neg_evict_select_list();
1528 mtx_lock(&nl->nl_lock);
1529 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1531 cache_neg_demote_locked(ncp);
1533 ncp = cache_neg_evict_select_entry(nl);
1535 counter_u64_add(neg_evict_skipped_empty, 1);
1536 mtx_unlock(&nl->nl_lock);
1537 mtx_unlock(&nl->nl_evict_lock);
1540 nlen = ncp->nc_nlen;
1542 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1543 dvlp = VP2VNODELOCK(dvp);
1544 blp = HASH2BUCKETLOCK(hash);
1545 mtx_unlock(&nl->nl_lock);
1546 mtx_unlock(&nl->nl_evict_lock);
1550 * Note that since all locks were dropped above, the entry may be
1551 * gone or reallocated to be something else.
1553 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1554 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1555 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1559 counter_u64_add(neg_evict_skipped_missed, 1);
1563 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1564 MPASS(blp == NCP2BUCKETLOCK(ncp));
1565 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1567 cache_zap_locked(ncp);
1568 counter_u64_add(neg_evicted, 1);
1579 * Maybe evict a negative entry to create more room.
1581 * The ncnegfactor parameter limits what fraction of the total count
1582 * can comprise of negative entries. However, if the cache is just
1583 * warming up this leads to excessive evictions. As such, ncnegminpct
1584 * (recomputed to neg_min) dictates whether the above should be
1587 * Try evicting if the cache is close to full capacity regardless of
1588 * other considerations.
1591 cache_neg_evict_cond(u_long lnumcache)
1595 if (ncsize - 1000 < lnumcache)
1597 lnumneg = atomic_load_long(&numneg);
1598 if (lnumneg < neg_min)
1600 if (lnumneg * ncnegfactor < lnumcache)
1603 return (cache_neg_evict());
1607 * cache_zap_locked():
1609 * Removes a namecache entry from cache, whether it contains an actual
1610 * pointer to a vnode or if it is just a negative cache entry.
1613 cache_zap_locked(struct namecache *ncp)
1615 struct nchashhead *ncpp;
1616 struct vnode *dvp, *vp;
1621 if (!(ncp->nc_flag & NCF_NEGATIVE))
1622 cache_assert_vnode_locked(vp);
1623 cache_assert_vnode_locked(dvp);
1624 cache_assert_bucket_locked(ncp);
1626 cache_ncp_invalidate(ncp);
1628 ncpp = NCP2BUCKET(ncp);
1629 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1630 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1631 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1632 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1633 if (ncp == vp->v_cache_dd) {
1634 atomic_store_ptr(&vp->v_cache_dd, NULL);
1637 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1638 cache_neg_remove(ncp);
1640 if (ncp->nc_flag & NCF_ISDOTDOT) {
1641 if (ncp == dvp->v_cache_dd) {
1642 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1645 LIST_REMOVE(ncp, nc_src);
1646 if (LIST_EMPTY(&dvp->v_cache_src)) {
1647 ncp->nc_flag |= NCF_DVDROP;
1653 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1657 MPASS(ncp->nc_dvp == vp);
1658 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1659 cache_assert_vnode_locked(vp);
1661 blp = NCP2BUCKETLOCK(ncp);
1663 cache_zap_locked(ncp);
1668 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1671 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1674 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1675 cache_assert_vnode_locked(vp);
1677 if (ncp->nc_flag & NCF_NEGATIVE) {
1678 if (*vlpp != NULL) {
1682 cache_zap_negative_locked_vnode_kl(ncp, vp);
1686 pvlp = VP2VNODELOCK(vp);
1687 blp = NCP2BUCKETLOCK(ncp);
1688 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1689 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1691 if (*vlpp == vlp1 || *vlpp == vlp2) {
1695 if (*vlpp != NULL) {
1699 cache_sort_vnodes(&vlp1, &vlp2);
1704 if (!mtx_trylock(vlp1))
1710 cache_zap_locked(ncp);
1712 if (to_unlock != NULL)
1713 mtx_unlock(to_unlock);
1720 MPASS(*vlpp == NULL);
1726 * If trylocking failed we can get here. We know enough to take all needed locks
1727 * in the right order and re-lookup the entry.
1730 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1731 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1734 struct namecache *rncp;
1737 cache_assert_bucket_unlocked(ncp);
1739 cache_sort_vnodes(&dvlp, &vlp);
1740 cache_lock_vnodes(dvlp, vlp);
1742 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1743 if (rncp == ncp && rncp->nc_dvp == dvp &&
1744 rncp->nc_nlen == cnp->cn_namelen &&
1745 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1752 if (!(ncp->nc_flag & NCF_NEGATIVE))
1753 rvlp = VP2VNODELOCK(rncp->nc_vp);
1759 cache_zap_locked(rncp);
1761 cache_unlock_vnodes(dvlp, vlp);
1762 atomic_add_long(&zap_bucket_relock_success, 1);
1767 cache_unlock_vnodes(dvlp, vlp);
1771 static int __noinline
1772 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1773 uint32_t hash, struct mtx *blp)
1775 struct mtx *dvlp, *vlp;
1778 cache_assert_bucket_locked(ncp);
1780 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1782 if (!(ncp->nc_flag & NCF_NEGATIVE))
1783 vlp = VP2VNODELOCK(ncp->nc_vp);
1784 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1785 cache_zap_locked(ncp);
1787 cache_unlock_vnodes(dvlp, vlp);
1793 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1796 static __noinline int
1797 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1799 struct namecache *ncp;
1801 struct mtx *dvlp, *dvlp2;
1805 if (cnp->cn_namelen == 2 &&
1806 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1807 dvlp = VP2VNODELOCK(dvp);
1811 ncp = dvp->v_cache_dd;
1816 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1819 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1820 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1822 MPASS(dvp->v_cache_dd == NULL);
1828 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1833 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1838 * XXX note that access here is completely unlocked with no provisions
1839 * to keep the hash allocated. If one is sufficiently unlucky a
1840 * parallel cache resize can reallocate the hash, unmap backing pages
1841 * and cause the empty check below to fault.
1843 * Fixing this has epsilon priority, but can be done with no overhead
1844 * for this codepath with sufficient effort.
1846 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1847 blp = HASH2BUCKETLOCK(hash);
1849 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1854 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1855 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1856 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1865 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1866 if (__predict_false(error != 0)) {
1867 atomic_add_long(&zap_bucket_fail, 1);
1870 counter_u64_add(numposzaps, 1);
1871 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1875 counter_u64_add(nummisszap, 1);
1876 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1880 static int __noinline
1881 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1882 struct timespec *tsp, int *ticksp)
1887 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1894 * When we lookup "." we still can be asked to lock it
1897 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1898 if (ltype != VOP_ISLOCKED(*vpp)) {
1899 if (ltype == LK_EXCLUSIVE) {
1900 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1901 if (VN_IS_DOOMED((*vpp))) {
1902 /* forced unmount */
1908 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1913 static int __noinline
1914 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1915 struct timespec *tsp, int *ticksp)
1917 struct namecache_ts *ncp_ts;
1918 struct namecache *ncp;
1924 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1926 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1927 cache_remove_cnp(dvp, cnp);
1932 dvlp = VP2VNODELOCK(dvp);
1934 ncp = dvp->v_cache_dd;
1936 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1940 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1941 if (ncp->nc_flag & NCF_NEGATIVE)
1948 goto negative_success;
1949 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1950 cache_out_ts(ncp, tsp, ticksp);
1951 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1952 NCF_DTS && tsp != NULL) {
1953 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1954 *tsp = ncp_ts->nc_dotdottime;
1958 ltype = VOP_ISLOCKED(dvp);
1960 vs = vget_prep(*vpp);
1962 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1963 vn_lock(dvp, ltype | LK_RETRY);
1964 if (VN_IS_DOOMED(dvp)) {
1976 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1977 if (cnp->cn_flags & ISLASTCN) {
1978 counter_u64_add(numnegzaps, 1);
1979 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1986 whiteout = (ncp->nc_flag & NCF_WHITE);
1987 cache_out_ts(ncp, tsp, ticksp);
1988 if (cache_neg_hit_prep(ncp))
1989 cache_neg_promote(ncp);
1991 cache_neg_hit_finish(ncp);
1994 cnp->cn_flags |= ISWHITEOUT;
1999 * Lookup a name in the name cache
2003 * - dvp: Parent directory in which to search.
2004 * - vpp: Return argument. Will contain desired vnode on cache hit.
2005 * - cnp: Parameters of the name search. The most interesting bits of
2006 * the cn_flags field have the following meanings:
2007 * - MAKEENTRY: If clear, free an entry from the cache rather than look
2009 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
2010 * - tsp: Return storage for cache timestamp. On a successful (positive
2011 * or negative) lookup, tsp will be filled with any timespec that
2012 * was stored when this cache entry was created. However, it will
2013 * be clear for "." entries.
2014 * - ticks: Return storage for alternate cache timestamp. On a successful
2015 * (positive or negative) lookup, it will contain the ticks value
2016 * that was current when the cache entry was created, unless cnp
2019 * Either both tsp and ticks have to be provided or neither of them.
2023 * - -1: A positive cache hit. vpp will contain the desired vnode.
2024 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
2025 * to a forced unmount. vpp will not be modified. If the entry
2026 * is a whiteout, then the ISWHITEOUT flag will be set in
2028 * - 0: A cache miss. vpp will not be modified.
2032 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
2033 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
2034 * lock is not recursively acquired.
2036 static int __noinline
2037 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2038 struct timespec *tsp, int *ticksp)
2040 struct namecache *ncp;
2047 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2048 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
2051 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2052 blp = HASH2BUCKETLOCK(hash);
2055 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2056 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2057 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2061 if (__predict_false(ncp == NULL)) {
2063 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2064 counter_u64_add(nummiss, 1);
2068 if (ncp->nc_flag & NCF_NEGATIVE)
2069 goto negative_success;
2071 counter_u64_add(numposhits, 1);
2073 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2074 cache_out_ts(ncp, tsp, ticksp);
2076 vs = vget_prep(*vpp);
2078 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2086 * We don't get here with regular lookup apart from corner cases.
2088 if (__predict_true(cnp->cn_nameiop == CREATE)) {
2089 if (cnp->cn_flags & ISLASTCN) {
2090 counter_u64_add(numnegzaps, 1);
2091 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2092 if (__predict_false(error != 0)) {
2093 atomic_add_long(&zap_bucket_fail2, 1);
2101 whiteout = (ncp->nc_flag & NCF_WHITE);
2102 cache_out_ts(ncp, tsp, ticksp);
2103 if (cache_neg_hit_prep(ncp))
2104 cache_neg_promote(ncp);
2106 cache_neg_hit_finish(ncp);
2109 cnp->cn_flags |= ISWHITEOUT;
2114 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2115 struct timespec *tsp, int *ticksp)
2117 struct namecache *ncp;
2121 bool whiteout, neg_promote;
2124 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2127 if (__predict_false(!doingcache)) {
2128 cnp->cn_flags &= ~MAKEENTRY;
2133 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2134 if (cnp->cn_namelen == 1)
2135 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2136 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2137 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2140 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2142 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2143 cache_remove_cnp(dvp, cnp);
2147 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2150 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2151 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2152 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2156 if (__predict_false(ncp == NULL)) {
2158 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2159 counter_u64_add(nummiss, 1);
2163 nc_flag = atomic_load_char(&ncp->nc_flag);
2164 if (nc_flag & NCF_NEGATIVE)
2165 goto negative_success;
2167 counter_u64_add(numposhits, 1);
2169 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2170 cache_out_ts(ncp, tsp, ticksp);
2172 if (!cache_ncp_canuse(ncp)) {
2177 vs = vget_prep_smr(*vpp);
2179 if (__predict_false(vs == VGET_NONE)) {
2183 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2190 if (cnp->cn_nameiop == CREATE) {
2191 if (cnp->cn_flags & ISLASTCN) {
2197 cache_out_ts(ncp, tsp, ticksp);
2198 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2199 neg_promote = cache_neg_hit_prep(ncp);
2200 if (!cache_ncp_canuse(ncp)) {
2201 cache_neg_hit_abort(ncp);
2207 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2210 cache_neg_hit_finish(ncp);
2214 cnp->cn_flags |= ISWHITEOUT;
2217 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2220 struct celockstate {
2224 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2225 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2228 cache_celockstate_init(struct celockstate *cel)
2231 bzero(cel, sizeof(*cel));
2235 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2238 struct mtx *vlp1, *vlp2;
2240 MPASS(cel->vlp[0] == NULL);
2241 MPASS(cel->vlp[1] == NULL);
2242 MPASS(cel->vlp[2] == NULL);
2244 MPASS(vp != NULL || dvp != NULL);
2246 vlp1 = VP2VNODELOCK(vp);
2247 vlp2 = VP2VNODELOCK(dvp);
2248 cache_sort_vnodes(&vlp1, &vlp2);
2259 cache_unlock_vnodes_cel(struct celockstate *cel)
2262 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2264 if (cel->vlp[0] != NULL)
2265 mtx_unlock(cel->vlp[0]);
2266 if (cel->vlp[1] != NULL)
2267 mtx_unlock(cel->vlp[1]);
2268 if (cel->vlp[2] != NULL)
2269 mtx_unlock(cel->vlp[2]);
2273 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2278 cache_assert_vlp_locked(cel->vlp[0]);
2279 cache_assert_vlp_locked(cel->vlp[1]);
2280 MPASS(cel->vlp[2] == NULL);
2283 vlp = VP2VNODELOCK(vp);
2286 if (vlp >= cel->vlp[1]) {
2289 if (mtx_trylock(vlp))
2291 cache_unlock_vnodes_cel(cel);
2292 atomic_add_long(&cache_lock_vnodes_cel_3_failures, 1);
2293 if (vlp < cel->vlp[0]) {
2295 mtx_lock(cel->vlp[0]);
2296 mtx_lock(cel->vlp[1]);
2298 if (cel->vlp[0] != NULL)
2299 mtx_lock(cel->vlp[0]);
2301 mtx_lock(cel->vlp[1]);
2311 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2315 MPASS(cel->blp[0] == NULL);
2316 MPASS(cel->blp[1] == NULL);
2318 cache_sort_vnodes(&blp1, &blp2);
2329 cache_unlock_buckets_cel(struct celockstate *cel)
2332 if (cel->blp[0] != NULL)
2333 mtx_unlock(cel->blp[0]);
2334 mtx_unlock(cel->blp[1]);
2338 * Lock part of the cache affected by the insertion.
2340 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2341 * However, insertion can result in removal of an old entry. In this
2342 * case we have an additional vnode and bucketlock pair to lock.
2344 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2345 * preserving the locking order (smaller address first).
2348 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2351 struct namecache *ncp;
2352 struct mtx *blps[2];
2355 blps[0] = HASH2BUCKETLOCK(hash);
2358 cache_lock_vnodes_cel(cel, dvp, vp);
2359 if (vp == NULL || vp->v_type != VDIR)
2361 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2364 nc_flag = atomic_load_char(&ncp->nc_flag);
2365 if ((nc_flag & NCF_ISDOTDOT) == 0)
2367 MPASS(ncp->nc_dvp == vp);
2368 blps[1] = NCP2BUCKETLOCK(ncp);
2369 if ((nc_flag & NCF_NEGATIVE) != 0)
2371 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2374 * All vnodes got re-locked. Re-validate the state and if
2375 * nothing changed we are done. Otherwise restart.
2377 if (ncp == vp->v_cache_dd &&
2378 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2379 blps[1] == NCP2BUCKETLOCK(ncp) &&
2380 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2382 cache_unlock_vnodes_cel(cel);
2387 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2391 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2394 struct namecache *ncp;
2395 struct mtx *blps[2];
2398 blps[0] = HASH2BUCKETLOCK(hash);
2401 cache_lock_vnodes_cel(cel, dvp, vp);
2402 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2405 nc_flag = atomic_load_char(&ncp->nc_flag);
2406 if ((nc_flag & NCF_ISDOTDOT) == 0)
2408 MPASS(ncp->nc_dvp == dvp);
2409 blps[1] = NCP2BUCKETLOCK(ncp);
2410 if ((nc_flag & NCF_NEGATIVE) != 0)
2412 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2414 if (ncp == dvp->v_cache_dd &&
2415 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2416 blps[1] == NCP2BUCKETLOCK(ncp) &&
2417 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2419 cache_unlock_vnodes_cel(cel);
2424 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2428 cache_enter_unlock(struct celockstate *cel)
2431 cache_unlock_buckets_cel(cel);
2432 cache_unlock_vnodes_cel(cel);
2435 static void __noinline
2436 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2437 struct componentname *cnp)
2439 struct celockstate cel;
2440 struct namecache *ncp;
2444 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2446 len = cnp->cn_namelen;
2447 cache_celockstate_init(&cel);
2448 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2449 cache_enter_lock_dd(&cel, dvp, vp, hash);
2450 ncp = dvp->v_cache_dd;
2451 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2452 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2453 cache_zap_locked(ncp);
2457 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2458 cache_enter_unlock(&cel);
2464 * Add an entry to the cache.
2467 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2468 struct timespec *tsp, struct timespec *dtsp)
2470 struct celockstate cel;
2471 struct namecache *ncp, *n2, *ndd;
2472 struct namecache_ts *ncp_ts;
2473 struct nchashhead *ncpp;
2478 KASSERT(cnp->cn_namelen <= NAME_MAX,
2479 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2481 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2482 VNPASS(dvp->v_type != VNON, dvp);
2484 VNPASS(!VN_IS_DOOMED(vp), vp);
2485 VNPASS(vp->v_type != VNON, vp);
2487 if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
2489 ("%s: different vnodes for dot entry (%p; %p)\n", __func__,
2493 ("%s: same vnode for non-dot entry [%s] (%p)\n", __func__,
2494 cnp->cn_nameptr, dvp));
2498 if (__predict_false(!doingcache))
2503 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2504 if (cnp->cn_namelen == 1)
2506 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2507 cache_enter_dotdot_prep(dvp, vp, cnp);
2508 flag = NCF_ISDOTDOT;
2512 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2516 cache_celockstate_init(&cel);
2521 * Calculate the hash key and setup as much of the new
2522 * namecache entry as possible before acquiring the lock.
2524 ncp->nc_flag = flag | NCF_WIP;
2527 cache_neg_init(ncp);
2530 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2531 ncp_ts->nc_time = *tsp;
2532 ncp_ts->nc_ticks = ticks;
2533 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2535 ncp_ts->nc_dotdottime = *dtsp;
2536 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2539 len = ncp->nc_nlen = cnp->cn_namelen;
2540 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2541 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2542 ncp->nc_name[len] = '\0';
2543 cache_enter_lock(&cel, dvp, vp, hash);
2546 * See if this vnode or negative entry is already in the cache
2547 * with this name. This can happen with concurrent lookups of
2548 * the same path name.
2550 ncpp = NCHHASH(hash);
2551 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2552 if (n2->nc_dvp == dvp &&
2553 n2->nc_nlen == cnp->cn_namelen &&
2554 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2555 MPASS(cache_ncp_canuse(n2));
2556 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2558 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2559 __func__, NULL, vp, cnp->cn_nameptr));
2561 KASSERT(n2->nc_vp == vp,
2562 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2563 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2565 * Entries are supposed to be immutable unless in the
2566 * process of getting destroyed. Accommodating for
2567 * changing timestamps is possible but not worth it.
2568 * This should be harmless in terms of correctness, in
2569 * the worst case resulting in an earlier expiration.
2570 * Alternatively, the found entry can be replaced
2573 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2576 KASSERT((n2->nc_flag & NCF_TS) != 0,
2578 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2579 n2_ts->nc_time = ncp_ts->nc_time;
2580 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2582 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2583 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2587 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2589 goto out_unlock_free;
2593 if (flag == NCF_ISDOTDOT) {
2595 * See if we are trying to add .. entry, but some other lookup
2596 * has populated v_cache_dd pointer already.
2598 if (dvp->v_cache_dd != NULL)
2599 goto out_unlock_free;
2600 KASSERT(vp == NULL || vp->v_type == VDIR,
2601 ("wrong vnode type %p", vp));
2602 atomic_thread_fence_rel();
2603 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2607 if (flag != NCF_ISDOTDOT) {
2609 * For this case, the cache entry maps both the
2610 * directory name in it and the name ".." for the
2611 * directory's parent.
2613 if ((ndd = vp->v_cache_dd) != NULL) {
2614 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2615 cache_zap_locked(ndd);
2619 atomic_thread_fence_rel();
2620 atomic_store_ptr(&vp->v_cache_dd, ncp);
2621 } else if (vp->v_type != VDIR) {
2622 if (vp->v_cache_dd != NULL) {
2623 atomic_store_ptr(&vp->v_cache_dd, NULL);
2628 if (flag != NCF_ISDOTDOT) {
2629 if (LIST_EMPTY(&dvp->v_cache_src)) {
2630 cache_hold_vnode(dvp);
2632 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2636 * If the entry is "negative", we place it into the
2637 * "negative" cache queue, otherwise, we place it into the
2638 * destination vnode's cache entries queue.
2641 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2642 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2645 if (cnp->cn_flags & ISWHITEOUT)
2646 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2647 cache_neg_insert(ncp);
2648 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2653 * Insert the new namecache entry into the appropriate chain
2654 * within the cache entries table.
2656 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2658 atomic_thread_fence_rel();
2660 * Mark the entry as fully constructed.
2661 * It is immutable past this point until its removal.
2663 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2665 cache_enter_unlock(&cel);
2670 cache_enter_unlock(&cel);
2676 * A variant of the above accepting flags.
2678 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2680 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2681 * happens to match and it is doing it in an inefficient manner. It was added
2682 * to accommodate NFS which runs into a case where the target for a given name
2683 * may change from under it. Note this does nothing to solve the following
2684 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2685 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2688 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2689 struct timespec *tsp, struct timespec *dtsp, int flags)
2692 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2694 if (flags & VFS_CACHE_DROPOLD)
2695 cache_remove_cnp(dvp, cnp);
2696 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2700 cache_roundup_2(u_long val)
2704 for (res = 1; res <= val; res <<= 1)
2710 static struct nchashhead *
2711 nchinittbl(u_long elements, u_long *hashmask)
2713 struct nchashhead *hashtbl;
2716 hashsize = cache_roundup_2(elements) / 2;
2718 hashtbl = malloc(hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2719 for (i = 0; i < hashsize; i++)
2720 CK_SLIST_INIT(&hashtbl[i]);
2721 *hashmask = hashsize - 1;
2726 ncfreetbl(struct nchashhead *hashtbl)
2729 free(hashtbl, M_VFSCACHE);
2733 * Name cache initialization, from vfs_init() when we are booting
2736 nchinit(void *dummy __unused)
2740 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2741 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2742 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2743 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2744 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2745 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2746 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2747 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2749 VFS_SMR_ZONE_SET(cache_zone_small);
2750 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2751 VFS_SMR_ZONE_SET(cache_zone_large);
2752 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2754 ncsize = desiredvnodes * ncsizefactor;
2755 cache_recalc_neg_min();
2756 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2757 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2758 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2760 if (ncbuckethash > nchash)
2761 ncbuckethash = nchash;
2762 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2764 for (i = 0; i < numbucketlocks; i++)
2765 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2766 ncvnodehash = ncbuckethash;
2767 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2769 for (i = 0; i < numvnodelocks; i++)
2770 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2772 for (i = 0; i < numneglists; i++) {
2773 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2774 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2775 TAILQ_INIT(&neglists[i].nl_list);
2776 TAILQ_INIT(&neglists[i].nl_hotlist);
2779 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2782 cache_vnode_init(struct vnode *vp)
2785 LIST_INIT(&vp->v_cache_src);
2786 TAILQ_INIT(&vp->v_cache_dst);
2787 vp->v_cache_dd = NULL;
2792 * Induce transient cache misses for lockless operation in cache_lookup() by
2793 * using a temporary hash table.
2795 * This will force a fs lookup.
2797 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2798 * to observe all CPUs not performing the lookup.
2801 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2804 MPASS(temphash < nchash);
2806 * Change the size. The new size is smaller and can safely be used
2807 * against the existing table. All lookups which now hash wrong will
2808 * result in a cache miss, which all callers are supposed to know how
2811 atomic_store_long(&nchash, temphash);
2812 atomic_thread_fence_rel();
2813 vfs_smr_synchronize();
2815 * At this point everyone sees the updated hash value, but they still
2816 * see the old table.
2818 atomic_store_ptr(&nchashtbl, temptbl);
2819 atomic_thread_fence_rel();
2820 vfs_smr_synchronize();
2822 * At this point everyone sees the updated table pointer and size pair.
2827 * Set the new hash table.
2829 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2830 * lockless operation in cache_lookup().
2833 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2836 MPASS(nchash < new_hash);
2838 * Change the pointer first. This wont result in out of bounds access
2839 * since the temporary table is guaranteed to be smaller.
2841 atomic_store_ptr(&nchashtbl, new_tbl);
2842 atomic_thread_fence_rel();
2843 vfs_smr_synchronize();
2845 * At this point everyone sees the updated pointer value, but they
2846 * still see the old size.
2848 atomic_store_long(&nchash, new_hash);
2849 atomic_thread_fence_rel();
2850 vfs_smr_synchronize();
2852 * At this point everyone sees the updated table pointer and size pair.
2857 cache_changesize(u_long newmaxvnodes)
2859 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2860 u_long new_nchash, old_nchash, temphash;
2861 struct namecache *ncp;
2866 newncsize = newmaxvnodes * ncsizefactor;
2867 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2868 if (newmaxvnodes < numbucketlocks)
2869 newmaxvnodes = numbucketlocks;
2871 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2872 /* If same hash table size, nothing to do */
2873 if (nchash == new_nchash) {
2874 ncfreetbl(new_nchashtbl);
2878 temptbl = nchinittbl(1, &temphash);
2881 * Move everything from the old hash table to the new table.
2882 * None of the namecache entries in the table can be removed
2883 * because to do so, they have to be removed from the hash table.
2885 cache_lock_all_vnodes();
2886 cache_lock_all_buckets();
2887 old_nchashtbl = nchashtbl;
2888 old_nchash = nchash;
2889 cache_changesize_set_temp(temptbl, temphash);
2890 for (i = 0; i <= old_nchash; i++) {
2891 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2892 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2894 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2895 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2899 cache_recalc_neg_min();
2900 cache_changesize_set_new(new_nchashtbl, new_nchash);
2901 cache_unlock_all_buckets();
2902 cache_unlock_all_vnodes();
2903 ncfreetbl(old_nchashtbl);
2908 * Remove all entries from and to a particular vnode.
2911 cache_purge_impl(struct vnode *vp)
2913 struct cache_freebatch batch;
2914 struct namecache *ncp;
2915 struct mtx *vlp, *vlp2;
2918 vlp = VP2VNODELOCK(vp);
2922 while (!LIST_EMPTY(&vp->v_cache_src)) {
2923 ncp = LIST_FIRST(&vp->v_cache_src);
2924 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2926 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2928 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2929 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2930 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2932 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2934 ncp = vp->v_cache_dd;
2936 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2937 ("lost dotdot link"));
2938 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2940 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2942 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2946 cache_free_batch(&batch);
2950 * Opportunistic check to see if there is anything to do.
2953 cache_has_entries(struct vnode *vp)
2956 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2957 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2963 cache_purge(struct vnode *vp)
2966 SDT_PROBE1(vfs, namecache, purge, done, vp);
2967 if (!cache_has_entries(vp))
2969 cache_purge_impl(vp);
2973 * Only to be used by vgone.
2976 cache_purge_vgone(struct vnode *vp)
2980 VNPASS(VN_IS_DOOMED(vp), vp);
2981 if (cache_has_entries(vp)) {
2982 cache_purge_impl(vp);
2987 * Serialize against a potential thread doing cache_purge.
2989 vlp = VP2VNODELOCK(vp);
2990 mtx_wait_unlocked(vlp);
2991 if (cache_has_entries(vp)) {
2992 cache_purge_impl(vp);
2999 * Remove all negative entries for a particular directory vnode.
3002 cache_purge_negative(struct vnode *vp)
3004 struct cache_freebatch batch;
3005 struct namecache *ncp, *nnp;
3008 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
3009 if (LIST_EMPTY(&vp->v_cache_src))
3012 vlp = VP2VNODELOCK(vp);
3014 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
3015 if (!(ncp->nc_flag & NCF_NEGATIVE))
3017 cache_zap_negative_locked_vnode_kl(ncp, vp);
3018 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
3021 cache_free_batch(&batch);
3025 * Entry points for modifying VOP operations.
3028 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
3029 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
3032 ASSERT_VOP_IN_SEQC(fdvp);
3033 ASSERT_VOP_IN_SEQC(fvp);
3034 ASSERT_VOP_IN_SEQC(tdvp);
3036 ASSERT_VOP_IN_SEQC(tvp);
3041 KASSERT(!cache_remove_cnp(tdvp, tcnp),
3042 ("%s: lingering negative entry", __func__));
3044 cache_remove_cnp(tdvp, tcnp);
3050 * Historically renaming was always purging all revelang entries,
3051 * but that's quite wasteful. In particular turns out that in many cases
3052 * the target file is immediately accessed after rename, inducing a cache
3055 * Recode this to reduce relocking and reuse the existing entry (if any)
3056 * instead of just removing it above and allocating a new one here.
3058 cache_enter(tdvp, fvp, tcnp);
3062 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
3065 ASSERT_VOP_IN_SEQC(dvp);
3066 ASSERT_VOP_IN_SEQC(vp);
3072 * Validate that if an entry exists it matches.
3075 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
3077 struct namecache *ncp;
3081 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
3082 if (CK_SLIST_EMPTY(NCHHASH(hash)))
3084 blp = HASH2BUCKETLOCK(hash);
3086 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3087 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3088 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
3089 if (ncp->nc_vp != vp)
3090 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
3091 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3098 cache_assert_no_entries(struct vnode *vp)
3101 VNPASS(TAILQ_EMPTY(&vp->v_cache_dst), vp);
3102 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
3103 VNPASS(vp->v_cache_dd == NULL, vp);
3108 * Flush all entries referencing a particular filesystem.
3111 cache_purgevfs(struct mount *mp)
3113 struct vnode *vp, *mvp;
3114 size_t visited __sdt_used, purged __sdt_used;
3116 visited = purged = 0;
3118 * Somewhat wasteful iteration over all vnodes. Would be better to
3119 * support filtering and avoid the interlock to begin with.
3121 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3123 if (!cache_has_entries(vp)) {
3134 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3138 * Perform canonical checks and cache lookup and pass on to filesystem
3139 * through the vop_cachedlookup only if needed.
3143 vfs_cache_lookup(struct vop_lookup_args *ap)
3147 struct vnode **vpp = ap->a_vpp;
3148 struct componentname *cnp = ap->a_cnp;
3149 int flags = cnp->cn_flags;
3154 if (dvp->v_type != VDIR)
3157 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3158 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3161 error = vn_dir_check_exec(dvp, cnp);
3165 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3167 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3173 /* Implementation of the getcwd syscall. */
3175 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3181 buflen = uap->buflen;
3182 if (__predict_false(buflen < 2))
3184 if (buflen > MAXPATHLEN)
3185 buflen = MAXPATHLEN;
3187 buf = uma_zalloc(namei_zone, M_WAITOK);
3188 error = vn_getcwd(buf, &retbuf, &buflen);
3190 error = copyout(retbuf, uap->buf, buflen);
3191 uma_zfree(namei_zone, buf);
3196 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3202 pwd = pwd_get_smr();
3203 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3205 VFS_SMR_ASSERT_NOT_ENTERED();
3207 pwd = pwd_hold(curthread);
3208 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3214 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3221 * Canonicalize a path by walking it forward and back.
3224 * - Nothing guarantees the integrity of the entire chain. Consider the case
3225 * where the path "foo/bar/baz/qux" is passed, but "bar" is moved out of
3226 * "foo" into "quux" during the backwards walk. The result will be
3227 * "quux/bar/baz/qux", which could not have been obtained by an incremental
3228 * walk in userspace. Moreover, the path we return is inaccessible if the
3229 * calling thread lacks permission to traverse "quux".
3232 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3233 size_t size, int flags, enum uio_seg pathseg)
3235 struct nameidata nd;
3236 char *retbuf, *freebuf;
3241 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | WANTPARENT | AUDITVNODE1,
3242 pathseg, path, fd, &cap_fstat_rights);
3243 if ((error = namei(&nd)) != 0)
3246 if (nd.ni_vp->v_type == VREG && nd.ni_dvp->v_type != VDIR &&
3247 (nd.ni_vp->v_vflag & VV_ROOT) != 0) {
3249 * This happens if vp is a file mount. The call to
3250 * vn_fullpath_hardlink can panic if path resolution can't be
3251 * handled without the directory.
3253 * To resolve this, we find the vnode which was mounted on -
3254 * this should have a unique global path since we disallow
3255 * mounting on linked files.
3257 struct vnode *covered_vp;
3258 error = vn_lock(nd.ni_vp, LK_SHARED);
3261 covered_vp = nd.ni_vp->v_mount->mnt_vnodecovered;
3263 VOP_UNLOCK(nd.ni_vp);
3264 error = vn_fullpath(covered_vp, &retbuf, &freebuf);
3267 error = vn_fullpath_hardlink(nd.ni_vp, nd.ni_dvp, nd.ni_cnd.cn_nameptr,
3268 nd.ni_cnd.cn_namelen, &retbuf, &freebuf, &size);
3271 error = copyout(retbuf, buf, size);
3272 free(freebuf, M_TEMP);
3282 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3285 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3286 uap->flags, UIO_USERSPACE));
3290 * Retrieve the full filesystem path that correspond to a vnode from the name
3291 * cache (if available)
3294 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3301 if (__predict_false(vp == NULL))
3304 buflen = MAXPATHLEN;
3305 buf = malloc(buflen, M_TEMP, M_WAITOK);
3307 pwd = pwd_get_smr();
3308 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3309 VFS_SMR_ASSERT_NOT_ENTERED();
3311 pwd = pwd_hold(curthread);
3312 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3323 * This function is similar to vn_fullpath, but it attempts to lookup the
3324 * pathname relative to the global root mount point. This is required for the
3325 * auditing sub-system, as audited pathnames must be absolute, relative to the
3326 * global root mount point.
3329 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3335 if (__predict_false(vp == NULL))
3337 buflen = MAXPATHLEN;
3338 buf = malloc(buflen, M_TEMP, M_WAITOK);
3340 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3341 VFS_SMR_ASSERT_NOT_ENTERED();
3343 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3352 static struct namecache *
3353 vn_dd_from_dst(struct vnode *vp)
3355 struct namecache *ncp;
3357 cache_assert_vnode_locked(vp);
3358 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3359 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3366 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3369 struct namecache *ncp;
3373 vlp = VP2VNODELOCK(*vp);
3375 ncp = (*vp)->v_cache_dd;
3376 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3377 KASSERT(ncp == vn_dd_from_dst(*vp),
3378 ("%s: mismatch for dd entry (%p != %p)", __func__,
3379 ncp, vn_dd_from_dst(*vp)));
3381 ncp = vn_dd_from_dst(*vp);
3384 if (*buflen < ncp->nc_nlen) {
3387 counter_u64_add(numfullpathfail4, 1);
3389 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3393 *buflen -= ncp->nc_nlen;
3394 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3395 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3404 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3407 vn_lock(*vp, LK_SHARED | LK_RETRY);
3408 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3411 counter_u64_add(numfullpathfail2, 1);
3412 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3417 if (VN_IS_DOOMED(dvp)) {
3418 /* forced unmount */
3421 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3425 * *vp has its use count incremented still.
3432 * Resolve a directory to a pathname.
3434 * The name of the directory can always be found in the namecache or fetched
3435 * from the filesystem. There is also guaranteed to be only one parent, meaning
3436 * we can just follow vnodes up until we find the root.
3438 * The vnode must be referenced.
3441 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3442 size_t *len, size_t addend)
3444 #ifdef KDTRACE_HOOKS
3445 struct vnode *startvp = vp;
3450 bool slash_prefixed;
3452 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3453 VNPASS(vp->v_usecount > 0, vp);
3457 slash_prefixed = true;
3462 slash_prefixed = false;
3467 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3468 counter_u64_add(numfullpathcalls, 1);
3469 while (vp != rdir && vp != rootvnode) {
3471 * The vp vnode must be already fully constructed,
3472 * since it is either found in namecache or obtained
3473 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3474 * without obtaining the vnode lock.
3476 if ((vp->v_vflag & VV_ROOT) != 0) {
3477 vn_lock(vp, LK_RETRY | LK_SHARED);
3480 * With the vnode locked, check for races with
3481 * unmount, forced or not. Note that we
3482 * already verified that vp is not equal to
3483 * the root vnode, which means that
3484 * mnt_vnodecovered can be NULL only for the
3487 if (VN_IS_DOOMED(vp) ||
3488 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3489 vp1->v_mountedhere != vp->v_mount) {
3492 SDT_PROBE3(vfs, namecache, fullpath, return,
3502 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3503 error = vn_vptocnp(&vp, buf, &buflen);
3509 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3513 buf[--buflen] = '/';
3514 slash_prefixed = true;
3518 if (!slash_prefixed) {
3521 counter_u64_add(numfullpathfail4, 1);
3522 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3526 buf[--buflen] = '/';
3528 counter_u64_add(numfullpathfound, 1);
3531 *retbuf = buf + buflen;
3532 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3539 * Resolve an arbitrary vnode to a pathname.
3542 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3543 * resolve to a different path than the one used to find it
3544 * - namecache is not mandatory, meaning names are not guaranteed to be added
3545 * (in which case resolving fails)
3547 static void __inline
3548 cache_rev_failed_impl(int *reason, int line)
3553 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3556 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3557 char **retbuf, size_t *buflen, size_t addend)
3559 #ifdef KDTRACE_HOOKS
3560 struct vnode *startvp = vp;
3564 struct namecache *ncp;
3568 #ifdef KDTRACE_HOOKS
3571 seqc_t vp_seqc, tvp_seqc;
3574 VFS_SMR_ASSERT_ENTERED();
3576 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3581 orig_buflen = *buflen;
3584 MPASS(*buflen >= 2);
3586 buf[*buflen] = '\0';
3589 if (vp == rdir || vp == rootvnode) {
3597 #ifdef KDTRACE_HOOKS
3601 ncp = NULL; /* for sdt probe down below */
3602 vp_seqc = vn_seqc_read_any(vp);
3603 if (seqc_in_modify(vp_seqc)) {
3604 cache_rev_failed(&reason);
3609 #ifdef KDTRACE_HOOKS
3612 if ((vp->v_vflag & VV_ROOT) != 0) {
3613 mp = atomic_load_ptr(&vp->v_mount);
3615 cache_rev_failed(&reason);
3618 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3619 tvp_seqc = vn_seqc_read_any(tvp);
3620 if (seqc_in_modify(tvp_seqc)) {
3621 cache_rev_failed(&reason);
3624 if (!vn_seqc_consistent(vp, vp_seqc)) {
3625 cache_rev_failed(&reason);
3632 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3634 cache_rev_failed(&reason);
3637 nc_flag = atomic_load_char(&ncp->nc_flag);
3638 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3639 cache_rev_failed(&reason);
3642 if (ncp->nc_nlen >= *buflen) {
3643 cache_rev_failed(&reason);
3647 *buflen -= ncp->nc_nlen;
3648 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3652 tvp_seqc = vn_seqc_read_any(tvp);
3653 if (seqc_in_modify(tvp_seqc)) {
3654 cache_rev_failed(&reason);
3657 if (!vn_seqc_consistent(vp, vp_seqc)) {
3658 cache_rev_failed(&reason);
3662 * Acquire fence provided by vn_seqc_read_any above.
3664 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3665 cache_rev_failed(&reason);
3668 if (!cache_ncp_canuse(ncp)) {
3669 cache_rev_failed(&reason);
3674 if (vp == rdir || vp == rootvnode)
3679 *retbuf = buf + *buflen;
3680 *buflen = orig_buflen - *buflen + addend;
3681 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3685 *buflen = orig_buflen;
3686 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3692 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3695 size_t orig_buflen, addend;
3701 orig_buflen = *buflen;
3705 if (vp->v_type != VDIR) {
3707 buf[*buflen] = '\0';
3708 error = vn_vptocnp(&vp, buf, buflen);
3717 addend = orig_buflen - *buflen;
3720 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3724 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3726 * Since the namecache does not track hardlinks, the caller is expected to
3727 * first look up the target vnode with WANTPARENT flag passed to namei to get
3730 * Then we have 2 cases:
3731 * - if the found vnode is a directory, the path can be constructed just by
3732 * following names up the chain
3733 * - otherwise we populate the buffer with the saved name and start resolving
3737 vn_fullpath_hardlink(struct vnode *vp, struct vnode *dvp,
3738 const char *hrdl_name, size_t hrdl_name_length,
3739 char **retbuf, char **freebuf, size_t *buflen)
3745 __enum_uint8(vtype) type;
3749 if (*buflen > MAXPATHLEN)
3750 *buflen = MAXPATHLEN;
3752 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3757 * Check for VBAD to work around the vp_crossmp bug in lookup().
3759 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3760 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3761 * If the type is VDIR (like in this very case) we can skip looking
3762 * at ni_dvp in the first place. However, since vnodes get passed here
3763 * unlocked the target may transition to doomed state (type == VBAD)
3764 * before we get to evaluate the condition. If this happens, we will
3765 * populate part of the buffer and descend to vn_fullpath_dir with
3766 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3768 type = atomic_load_8(&vp->v_type);
3774 addend = hrdl_name_length + 2;
3775 if (*buflen < addend) {
3780 tmpbuf = buf + *buflen;
3782 memcpy(&tmpbuf[1], hrdl_name, hrdl_name_length);
3783 tmpbuf[addend - 1] = '\0';
3788 pwd = pwd_get_smr();
3789 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3791 VFS_SMR_ASSERT_NOT_ENTERED();
3793 pwd = pwd_hold(curthread);
3795 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3811 vn_dir_dd_ino(struct vnode *vp)
3813 struct namecache *ncp;
3818 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3819 vlp = VP2VNODELOCK(vp);
3821 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3822 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3825 vs = vget_prep(ddvp);
3827 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3836 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3838 struct namecache *ncp;
3842 vlp = VP2VNODELOCK(vp);
3844 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3845 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3851 l = min(ncp->nc_nlen, buflen - 1);
3852 memcpy(buf, ncp->nc_name, l);
3859 * This function updates path string to vnode's full global path
3860 * and checks the size of the new path string against the pathlen argument.
3862 * Requires a locked, referenced vnode.
3863 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3865 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3866 * because it falls back to the ".." lookup if the namecache lookup fails.
3869 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3872 struct nameidata nd;
3877 ASSERT_VOP_ELOCKED(vp, __func__);
3879 /* Construct global filesystem path from vp. */
3881 error = vn_fullpath_global(vp, &rpath, &fbuf);
3888 if (strlen(rpath) >= pathlen) {
3890 error = ENAMETOOLONG;
3895 * Re-lookup the vnode by path to detect a possible rename.
3896 * As a side effect, the vnode is relocked.
3897 * If vnode was renamed, return ENOENT.
3899 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3909 strcpy(path, rpath);
3921 * This is similar to vn_path_to_global_path but allows for regular
3922 * files which may not be present in the cache.
3924 * Requires a locked, referenced vnode.
3925 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3928 vn_path_to_global_path_hardlink(struct thread *td, struct vnode *vp,
3929 struct vnode *dvp, char *path, u_int pathlen, const char *leaf_name,
3932 struct nameidata nd;
3938 ASSERT_VOP_ELOCKED(vp, __func__);
3941 * Construct global filesystem path from dvp, vp and leaf
3946 error = vn_fullpath_hardlink(vp, dvp, leaf_name, leaf_length,
3947 &rpath, &fbuf, &len);
3954 if (strlen(rpath) >= pathlen) {
3956 error = ENAMETOOLONG;
3961 * Re-lookup the vnode by path to detect a possible rename.
3962 * As a side effect, the vnode is relocked.
3963 * If vnode was renamed, return ENOENT.
3965 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3975 strcpy(path, rpath);
3988 db_print_vpath(struct vnode *vp)
3991 while (vp != NULL) {
3992 db_printf("%p: ", vp);
3993 if (vp == rootvnode) {
3997 if (vp->v_vflag & VV_ROOT) {
3998 db_printf("<mount point>");
3999 vp = vp->v_mount->mnt_vnodecovered;
4001 struct namecache *ncp;
4005 ncp = TAILQ_FIRST(&vp->v_cache_dst);
4008 for (i = 0; i < ncp->nc_nlen; i++)
4009 db_printf("%c", *ncn++);
4022 DB_SHOW_COMMAND(vpath, db_show_vpath)
4027 db_printf("usage: show vpath <struct vnode *>\n");
4031 vp = (struct vnode *)addr;
4037 static int cache_fast_lookup = 1;
4039 #define CACHE_FPL_FAILED -2020
4042 cache_vop_bad_vexec(struct vop_fplookup_vexec_args *v)
4044 vn_printf(v->a_vp, "no proper vop_fplookup_vexec\n");
4045 panic("no proper vop_fplookup_vexec");
4049 cache_vop_bad_symlink(struct vop_fplookup_symlink_args *v)
4051 vn_printf(v->a_vp, "no proper vop_fplookup_symlink\n");
4052 panic("no proper vop_fplookup_symlink");
4056 cache_vop_vector_register(struct vop_vector *v)
4061 if (v->vop_fplookup_vexec != NULL) {
4064 if (v->vop_fplookup_symlink != NULL) {
4073 v->vop_fplookup_vexec = cache_vop_bad_vexec;
4074 v->vop_fplookup_symlink = cache_vop_bad_symlink;
4078 printf("%s: invalid vop vector %p -- either all or none fplookup vops "
4079 "need to be provided", __func__, v);
4080 if (v->vop_fplookup_vexec == NULL) {
4081 printf("%s: missing vop_fplookup_vexec\n", __func__);
4083 if (v->vop_fplookup_symlink == NULL) {
4084 printf("%s: missing vop_fplookup_symlink\n", __func__);
4086 panic("bad vop vector %p", v);
4091 cache_validate_vop_vector(struct mount *mp, struct vop_vector *vops)
4096 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4099 if (vops->vop_fplookup_vexec == NULL ||
4100 vops->vop_fplookup_vexec == cache_vop_bad_vexec)
4101 panic("bad vop_fplookup_vexec on vector %p for filesystem %s",
4102 vops, mp->mnt_vfc->vfc_name);
4104 if (vops->vop_fplookup_symlink == NULL ||
4105 vops->vop_fplookup_symlink == cache_vop_bad_symlink)
4106 panic("bad vop_fplookup_symlink on vector %p for filesystem %s",
4107 vops, mp->mnt_vfc->vfc_name);
4112 cache_fast_lookup_enabled_recalc(void)
4118 mac_on = mac_vnode_check_lookup_enabled();
4119 mac_on |= mac_vnode_check_readlink_enabled();
4124 lookup_flag = atomic_load_int(&cache_fast_lookup);
4125 if (lookup_flag && !mac_on) {
4126 atomic_store_char(&cache_fast_lookup_enabled, true);
4128 atomic_store_char(&cache_fast_lookup_enabled, false);
4133 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
4137 old = atomic_load_int(&cache_fast_lookup);
4138 error = sysctl_handle_int(oidp, arg1, arg2, req);
4139 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
4140 cache_fast_lookup_enabled_recalc();
4143 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
4144 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
4147 * Components of nameidata (or objects it can point to) which may
4148 * need restoring in case fast path lookup fails.
4150 struct nameidata_outer {
4155 struct nameidata_saved {
4163 struct cache_fpl_debug {
4169 struct nameidata *ndp;
4170 struct componentname *cnp;
4177 struct nameidata_saved snd;
4178 struct nameidata_outer snd_outer;
4180 enum cache_fpl_status status:8;
4185 struct cache_fpl_debug debug;
4189 static bool cache_fplookup_mp_supported(struct mount *mp);
4190 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
4191 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
4192 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
4193 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
4194 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
4195 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
4196 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
4197 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
4198 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
4201 cache_fpl_cleanup_cnp(struct componentname *cnp)
4204 uma_zfree(namei_zone, cnp->cn_pnbuf);
4205 cnp->cn_pnbuf = NULL;
4206 cnp->cn_nameptr = NULL;
4209 static struct vnode *
4210 cache_fpl_handle_root(struct cache_fpl *fpl)
4212 struct nameidata *ndp;
4213 struct componentname *cnp;
4218 MPASS(*(cnp->cn_nameptr) == '/');
4220 cache_fpl_pathlen_dec(fpl);
4222 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4225 cache_fpl_pathlen_dec(fpl);
4226 } while (*(cnp->cn_nameptr) == '/');
4229 return (ndp->ni_rootdir);
4233 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
4236 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
4237 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
4241 cache_fpl_checkpoint(struct cache_fpl *fpl)
4245 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
4246 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4251 cache_fpl_restore_partial(struct cache_fpl *fpl)
4254 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4256 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4261 cache_fpl_restore_abort(struct cache_fpl *fpl)
4264 cache_fpl_restore_partial(fpl);
4266 * It is 0 on entry by API contract.
4268 fpl->ndp->ni_resflags = 0;
4269 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4270 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4274 #define cache_fpl_smr_assert_entered(fpl) ({ \
4275 struct cache_fpl *_fpl = (fpl); \
4276 MPASS(_fpl->in_smr == true); \
4277 VFS_SMR_ASSERT_ENTERED(); \
4279 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4280 struct cache_fpl *_fpl = (fpl); \
4281 MPASS(_fpl->in_smr == false); \
4282 VFS_SMR_ASSERT_NOT_ENTERED(); \
4285 cache_fpl_assert_status(struct cache_fpl *fpl)
4288 switch (fpl->status) {
4289 case CACHE_FPL_STATUS_UNSET:
4290 __assert_unreachable();
4292 case CACHE_FPL_STATUS_DESTROYED:
4293 case CACHE_FPL_STATUS_ABORTED:
4294 case CACHE_FPL_STATUS_PARTIAL:
4295 case CACHE_FPL_STATUS_HANDLED:
4300 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4301 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4302 #define cache_fpl_assert_status(fpl) do { } while (0)
4305 #define cache_fpl_smr_enter_initial(fpl) ({ \
4306 struct cache_fpl *_fpl = (fpl); \
4308 _fpl->in_smr = true; \
4311 #define cache_fpl_smr_enter(fpl) ({ \
4312 struct cache_fpl *_fpl = (fpl); \
4313 MPASS(_fpl->in_smr == false); \
4315 _fpl->in_smr = true; \
4318 #define cache_fpl_smr_exit(fpl) ({ \
4319 struct cache_fpl *_fpl = (fpl); \
4320 MPASS(_fpl->in_smr == true); \
4322 _fpl->in_smr = false; \
4326 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4329 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4330 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4331 ("%s: converting to abort from %d at %d, set at %d\n",
4332 __func__, fpl->status, line, fpl->line));
4334 cache_fpl_smr_assert_not_entered(fpl);
4335 fpl->status = CACHE_FPL_STATUS_ABORTED;
4337 return (CACHE_FPL_FAILED);
4340 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4342 static int __noinline
4343 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4345 struct nameidata *ndp;
4346 struct componentname *cnp;
4351 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4352 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4353 ("%s: converting to abort from %d at %d, set at %d\n",
4354 __func__, fpl->status, line, fpl->line));
4356 fpl->status = CACHE_FPL_STATUS_ABORTED;
4359 cache_fpl_smr_exit(fpl);
4360 cache_fpl_restore_abort(fpl);
4362 * Resolving symlinks overwrites data passed by the caller.
4365 if (ndp->ni_loopcnt > 0) {
4366 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4367 cache_fpl_cleanup_cnp(cnp);
4369 return (CACHE_FPL_FAILED);
4372 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4374 static int __noinline
4375 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4378 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4379 ("%s: setting to partial at %d, but already set to %d at %d\n",
4380 __func__, line, fpl->status, fpl->line));
4381 cache_fpl_smr_assert_entered(fpl);
4382 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4384 return (cache_fplookup_partial_setup(fpl));
4387 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4390 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4393 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4394 ("%s: setting to handled at %d, but already set to %d at %d\n",
4395 __func__, line, fpl->status, fpl->line));
4396 cache_fpl_smr_assert_not_entered(fpl);
4397 fpl->status = CACHE_FPL_STATUS_HANDLED;
4402 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4405 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4408 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4409 ("%s: setting to handled at %d, but already set to %d at %d\n",
4410 __func__, line, fpl->status, fpl->line));
4412 MPASS(error != CACHE_FPL_FAILED);
4413 cache_fpl_smr_assert_not_entered(fpl);
4414 fpl->status = CACHE_FPL_STATUS_HANDLED;
4421 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4424 cache_fpl_terminated(struct cache_fpl *fpl)
4427 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4430 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4431 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4432 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | ISRESTARTED | WILLBEDIR | \
4433 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | OPENREAD | \
4434 OPENWRITE | WANTIOCTLCAPS)
4436 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4437 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4439 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4440 "supported and internal flags overlap");
4443 cache_fpl_islastcn(struct nameidata *ndp)
4446 return (*ndp->ni_next == 0);
4450 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4453 MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4454 return (*(fpl->nulchar - 1) == '/');
4458 cache_fpl_isdotdot(struct componentname *cnp)
4461 if (cnp->cn_namelen == 2 &&
4462 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4468 cache_can_fplookup(struct cache_fpl *fpl)
4470 struct nameidata *ndp;
4471 struct componentname *cnp;
4478 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4479 cache_fpl_aborted_early(fpl);
4482 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4483 cache_fpl_aborted_early(fpl);
4486 if (IN_CAPABILITY_MODE(td)) {
4487 cache_fpl_aborted_early(fpl);
4490 if (AUDITING_TD(td)) {
4491 cache_fpl_aborted_early(fpl);
4494 if (ndp->ni_startdir != NULL) {
4495 cache_fpl_aborted_early(fpl);
4501 static int __noinline
4502 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4504 struct nameidata *ndp;
4505 struct componentname *cnp;
4512 error = fgetvp_lookup_smr(ndp, vpp, &fsearch);
4513 if (__predict_false(error != 0)) {
4514 return (cache_fpl_aborted(fpl));
4516 fpl->fsearch = fsearch;
4517 if ((*vpp)->v_type != VDIR) {
4518 if (!((cnp->cn_flags & EMPTYPATH) != 0 && cnp->cn_pnbuf[0] == '\0')) {
4519 cache_fpl_smr_exit(fpl);
4520 return (cache_fpl_handled_error(fpl, ENOTDIR));
4526 static int __noinline
4527 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4530 struct componentname *cnp;
4536 cache_fpl_smr_exit(fpl);
4537 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4538 return (cache_fpl_handled_error(fpl, ENOENT));
4540 return (cache_fpl_aborted(fpl));
4544 * The target vnode is not supported, prepare for the slow path to take over.
4546 static int __noinline
4547 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4549 struct nameidata *ndp;
4550 struct componentname *cnp;
4560 dvp_seqc = fpl->dvp_seqc;
4562 if (!pwd_hold_smr(pwd)) {
4563 return (cache_fpl_aborted(fpl));
4567 * Note that seqc is checked before the vnode is locked, so by
4568 * the time regular lookup gets to it it may have moved.
4570 * Ultimately this does not affect correctness, any lookup errors
4571 * are userspace racing with itself. It is guaranteed that any
4572 * path which ultimately gets found could also have been found
4573 * by regular lookup going all the way in absence of concurrent
4576 dvs = vget_prep_smr(dvp);
4577 cache_fpl_smr_exit(fpl);
4578 if (__predict_false(dvs == VGET_NONE)) {
4580 return (cache_fpl_aborted(fpl));
4583 vget_finish_ref(dvp, dvs);
4584 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4587 return (cache_fpl_aborted(fpl));
4590 cache_fpl_restore_partial(fpl);
4592 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4593 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4594 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4598 ndp->ni_startdir = dvp;
4599 cnp->cn_flags |= MAKEENTRY;
4600 if (cache_fpl_islastcn(ndp))
4601 cnp->cn_flags |= ISLASTCN;
4602 if (cache_fpl_isdotdot(cnp))
4603 cnp->cn_flags |= ISDOTDOT;
4606 * Skip potential extra slashes parsing did not take care of.
4607 * cache_fplookup_skip_slashes explains the mechanism.
4609 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4612 cache_fpl_pathlen_dec(fpl);
4613 } while (*(cnp->cn_nameptr) == '/');
4616 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4618 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4619 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4620 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4621 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4628 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4630 struct componentname *cnp;
4637 tvp_seqc = fpl->tvp_seqc;
4639 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4640 lkflags = LK_SHARED;
4641 if ((cnp->cn_flags & LOCKSHARED) == 0)
4642 lkflags = LK_EXCLUSIVE;
4643 error = vget_finish(tvp, lkflags, tvs);
4644 if (__predict_false(error != 0)) {
4645 return (cache_fpl_aborted(fpl));
4648 vget_finish_ref(tvp, tvs);
4651 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4652 if ((cnp->cn_flags & LOCKLEAF) != 0)
4656 return (cache_fpl_aborted(fpl));
4659 return (cache_fpl_handled(fpl));
4663 * They want to possibly modify the state of the namecache.
4665 static int __noinline
4666 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4668 struct nameidata *ndp __diagused;
4669 struct componentname *cnp;
4671 struct vnode *dvp, *tvp;
4680 dvp_seqc = fpl->dvp_seqc;
4682 MPASS(*(cnp->cn_nameptr) != '/');
4683 MPASS(cache_fpl_islastcn(ndp));
4684 if ((cnp->cn_flags & LOCKPARENT) == 0)
4685 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4686 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4687 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4688 cnp->cn_nameiop == RENAME);
4689 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4690 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4692 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4693 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4697 * Regular lookup nulifies the slash, which we don't do here.
4698 * Don't take chances with filesystem routines seeing it for
4701 if (cache_fpl_istrailingslash(fpl)) {
4702 return (cache_fpl_partial(fpl));
4705 mp = atomic_load_ptr(&dvp->v_mount);
4706 if (__predict_false(mp == NULL)) {
4707 return (cache_fpl_aborted(fpl));
4710 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4711 cache_fpl_smr_exit(fpl);
4713 * Original code keeps not checking for CREATE which
4714 * might be a bug. For now let the old lookup decide.
4716 if (cnp->cn_nameiop == CREATE) {
4717 return (cache_fpl_aborted(fpl));
4719 return (cache_fpl_handled_error(fpl, EROFS));
4722 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4723 cache_fpl_smr_exit(fpl);
4724 return (cache_fpl_handled_error(fpl, EEXIST));
4728 * Secure access to dvp; check cache_fplookup_partial_setup for
4731 * XXX At least UFS requires its lookup routine to be called for
4732 * the last path component, which leads to some level of complication
4734 * - the target routine always locks the target vnode, but our caller
4735 * may not need it locked
4736 * - some of the VOP machinery asserts that the parent is locked, which
4737 * once more may be not required
4739 * TODO: add a flag for filesystems which don't need this.
4741 dvs = vget_prep_smr(dvp);
4742 cache_fpl_smr_exit(fpl);
4743 if (__predict_false(dvs == VGET_NONE)) {
4744 return (cache_fpl_aborted(fpl));
4747 vget_finish_ref(dvp, dvs);
4748 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4750 return (cache_fpl_aborted(fpl));
4753 error = vn_lock(dvp, LK_EXCLUSIVE);
4754 if (__predict_false(error != 0)) {
4756 return (cache_fpl_aborted(fpl));
4760 cnp->cn_flags |= ISLASTCN;
4762 cnp->cn_flags |= MAKEENTRY;
4763 if (cache_fpl_isdotdot(cnp))
4764 cnp->cn_flags |= ISDOTDOT;
4765 cnp->cn_lkflags = LK_EXCLUSIVE;
4766 error = VOP_LOOKUP(dvp, &tvp, cnp);
4774 return (cache_fpl_handled_error(fpl, error));
4777 return (cache_fpl_aborted(fpl));
4783 MPASS(error == EJUSTRETURN);
4784 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4787 return (cache_fpl_handled(fpl));
4791 * There are very hairy corner cases concerning various flag combinations
4792 * and locking state. In particular here we only hold one lock instead of
4795 * Skip the complexity as it is of no significance for normal workloads.
4797 if (__predict_false(tvp == dvp)) {
4800 return (cache_fpl_aborted(fpl));
4804 * If they want the symlink itself we are fine, but if they want to
4805 * follow it regular lookup has to be engaged.
4807 if (tvp->v_type == VLNK) {
4808 if ((cnp->cn_flags & FOLLOW) != 0) {
4811 return (cache_fpl_aborted(fpl));
4816 * Since we expect this to be the terminal vnode it should almost never
4819 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4822 return (cache_fpl_aborted(fpl));
4825 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4828 return (cache_fpl_handled_error(fpl, EEXIST));
4831 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4835 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4839 return (cache_fpl_handled(fpl));
4842 static int __noinline
4843 cache_fplookup_modifying(struct cache_fpl *fpl)
4845 struct nameidata *ndp;
4849 if (!cache_fpl_islastcn(ndp)) {
4850 return (cache_fpl_partial(fpl));
4852 return (cache_fplookup_final_modifying(fpl));
4855 static int __noinline
4856 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4858 struct componentname *cnp;
4859 enum vgetstate dvs, tvs;
4860 struct vnode *dvp, *tvp;
4866 dvp_seqc = fpl->dvp_seqc;
4869 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4872 * This is less efficient than it can be for simplicity.
4874 dvs = vget_prep_smr(dvp);
4875 if (__predict_false(dvs == VGET_NONE)) {
4876 return (cache_fpl_aborted(fpl));
4878 tvs = vget_prep_smr(tvp);
4879 if (__predict_false(tvs == VGET_NONE)) {
4880 cache_fpl_smr_exit(fpl);
4881 vget_abort(dvp, dvs);
4882 return (cache_fpl_aborted(fpl));
4885 cache_fpl_smr_exit(fpl);
4887 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4888 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4889 if (__predict_false(error != 0)) {
4890 vget_abort(tvp, tvs);
4891 return (cache_fpl_aborted(fpl));
4894 vget_finish_ref(dvp, dvs);
4897 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4898 vget_abort(tvp, tvs);
4899 if ((cnp->cn_flags & LOCKPARENT) != 0)
4903 return (cache_fpl_aborted(fpl));
4906 error = cache_fplookup_final_child(fpl, tvs);
4907 if (__predict_false(error != 0)) {
4908 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4909 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4910 if ((cnp->cn_flags & LOCKPARENT) != 0)
4917 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4922 cache_fplookup_final(struct cache_fpl *fpl)
4924 struct componentname *cnp;
4926 struct vnode *dvp, *tvp;
4931 dvp_seqc = fpl->dvp_seqc;
4934 MPASS(*(cnp->cn_nameptr) != '/');
4936 if (cnp->cn_nameiop != LOOKUP) {
4937 return (cache_fplookup_final_modifying(fpl));
4940 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4941 return (cache_fplookup_final_withparent(fpl));
4943 tvs = vget_prep_smr(tvp);
4944 if (__predict_false(tvs == VGET_NONE)) {
4945 return (cache_fpl_partial(fpl));
4948 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4949 cache_fpl_smr_exit(fpl);
4950 vget_abort(tvp, tvs);
4951 return (cache_fpl_aborted(fpl));
4954 cache_fpl_smr_exit(fpl);
4955 return (cache_fplookup_final_child(fpl, tvs));
4959 * Comment from locked lookup:
4960 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4961 * directory, e.g. like "/." or ".".
4963 static int __noinline
4964 cache_fplookup_degenerate(struct cache_fpl *fpl)
4966 struct componentname *cnp;
4974 fpl->tvp = fpl->dvp;
4975 fpl->tvp_seqc = fpl->dvp_seqc;
4981 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4983 ("%s: encountered non-slash; string [%s]\n", __func__,
4988 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4989 cache_fpl_smr_exit(fpl);
4990 return (cache_fpl_handled_error(fpl, EISDIR));
4993 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4994 return (cache_fplookup_final_withparent(fpl));
4997 dvs = vget_prep_smr(dvp);
4998 cache_fpl_smr_exit(fpl);
4999 if (__predict_false(dvs == VGET_NONE)) {
5000 return (cache_fpl_aborted(fpl));
5003 if ((cnp->cn_flags & LOCKLEAF) != 0) {
5004 lkflags = LK_SHARED;
5005 if ((cnp->cn_flags & LOCKSHARED) == 0)
5006 lkflags = LK_EXCLUSIVE;
5007 error = vget_finish(dvp, lkflags, dvs);
5008 if (__predict_false(error != 0)) {
5009 return (cache_fpl_aborted(fpl));
5012 vget_finish_ref(dvp, dvs);
5014 return (cache_fpl_handled(fpl));
5017 static int __noinline
5018 cache_fplookup_emptypath(struct cache_fpl *fpl)
5020 struct nameidata *ndp;
5021 struct componentname *cnp;
5026 fpl->tvp = fpl->dvp;
5027 fpl->tvp_seqc = fpl->dvp_seqc;
5033 MPASS(*cnp->cn_pnbuf == '\0');
5035 if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
5036 cache_fpl_smr_exit(fpl);
5037 return (cache_fpl_handled_error(fpl, ENOENT));
5040 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
5042 tvs = vget_prep_smr(tvp);
5043 cache_fpl_smr_exit(fpl);
5044 if (__predict_false(tvs == VGET_NONE)) {
5045 return (cache_fpl_aborted(fpl));
5048 if ((cnp->cn_flags & LOCKLEAF) != 0) {
5049 lkflags = LK_SHARED;
5050 if ((cnp->cn_flags & LOCKSHARED) == 0)
5051 lkflags = LK_EXCLUSIVE;
5052 error = vget_finish(tvp, lkflags, tvs);
5053 if (__predict_false(error != 0)) {
5054 return (cache_fpl_aborted(fpl));
5057 vget_finish_ref(tvp, tvs);
5060 ndp->ni_resflags |= NIRES_EMPTYPATH;
5061 return (cache_fpl_handled(fpl));
5064 static int __noinline
5065 cache_fplookup_noentry(struct cache_fpl *fpl)
5067 struct nameidata *ndp;
5068 struct componentname *cnp;
5070 struct vnode *dvp, *tvp;
5077 dvp_seqc = fpl->dvp_seqc;
5079 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
5080 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
5081 if (cnp->cn_nameiop == LOOKUP)
5082 MPASS((cnp->cn_flags & NOCACHE) == 0);
5083 MPASS(!cache_fpl_isdotdot(cnp));
5086 * Hack: delayed name len checking.
5088 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5089 cache_fpl_smr_exit(fpl);
5090 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5093 if (cnp->cn_nameptr[0] == '/') {
5094 return (cache_fplookup_skip_slashes(fpl));
5097 if (cnp->cn_pnbuf[0] == '\0') {
5098 return (cache_fplookup_emptypath(fpl));
5101 if (cnp->cn_nameptr[0] == '\0') {
5102 if (fpl->tvp == NULL) {
5103 return (cache_fplookup_degenerate(fpl));
5105 return (cache_fplookup_trailingslash(fpl));
5108 if (cnp->cn_nameiop != LOOKUP) {
5110 return (cache_fplookup_modifying(fpl));
5114 * Only try to fill in the component if it is the last one,
5115 * otherwise not only there may be several to handle but the
5116 * walk may be complicated.
5118 if (!cache_fpl_islastcn(ndp)) {
5119 return (cache_fpl_partial(fpl));
5123 * Regular lookup nulifies the slash, which we don't do here.
5124 * Don't take chances with filesystem routines seeing it for
5127 if (cache_fpl_istrailingslash(fpl)) {
5128 return (cache_fpl_partial(fpl));
5132 * Secure access to dvp; check cache_fplookup_partial_setup for
5135 dvs = vget_prep_smr(dvp);
5136 cache_fpl_smr_exit(fpl);
5137 if (__predict_false(dvs == VGET_NONE)) {
5138 return (cache_fpl_aborted(fpl));
5141 vget_finish_ref(dvp, dvs);
5142 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5144 return (cache_fpl_aborted(fpl));
5147 error = vn_lock(dvp, LK_SHARED);
5148 if (__predict_false(error != 0)) {
5150 return (cache_fpl_aborted(fpl));
5155 * TODO: provide variants which don't require locking either vnode.
5157 cnp->cn_flags |= ISLASTCN | MAKEENTRY;
5158 cnp->cn_lkflags = LK_SHARED;
5159 if ((cnp->cn_flags & LOCKSHARED) == 0) {
5160 cnp->cn_lkflags = LK_EXCLUSIVE;
5162 error = VOP_LOOKUP(dvp, &tvp, cnp);
5170 return (cache_fpl_handled_error(fpl, error));
5173 return (cache_fpl_aborted(fpl));
5179 MPASS(error == EJUSTRETURN);
5180 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5182 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5185 return (cache_fpl_handled(fpl));
5188 if (tvp->v_type == VLNK) {
5189 if ((cnp->cn_flags & FOLLOW) != 0) {
5192 return (cache_fpl_aborted(fpl));
5196 if (__predict_false(cache_fplookup_is_mp(fpl))) {
5199 return (cache_fpl_aborted(fpl));
5202 if ((cnp->cn_flags & LOCKLEAF) == 0) {
5206 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5208 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5211 return (cache_fpl_handled(fpl));
5214 static int __noinline
5215 cache_fplookup_dot(struct cache_fpl *fpl)
5219 MPASS(!seqc_in_modify(fpl->dvp_seqc));
5221 if (__predict_false(fpl->dvp->v_type != VDIR)) {
5222 cache_fpl_smr_exit(fpl);
5223 return (cache_fpl_handled_error(fpl, ENOTDIR));
5227 * Just re-assign the value. seqc will be checked later for the first
5228 * non-dot path component in line and/or before deciding to return the
5231 fpl->tvp = fpl->dvp;
5232 fpl->tvp_seqc = fpl->dvp_seqc;
5234 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
5237 if (cache_fplookup_is_mp(fpl)) {
5238 error = cache_fplookup_cross_mount(fpl);
5243 static int __noinline
5244 cache_fplookup_dotdot(struct cache_fpl *fpl)
5246 struct nameidata *ndp;
5247 struct componentname *cnp;
5248 struct namecache *ncp;
5257 MPASS(cache_fpl_isdotdot(cnp));
5260 * XXX this is racy the same way regular lookup is
5262 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5264 if (dvp == pr->pr_root)
5267 if (dvp == ndp->ni_rootdir ||
5268 dvp == ndp->ni_topdir ||
5272 fpl->tvp_seqc = vn_seqc_read_any(dvp);
5273 if (seqc_in_modify(fpl->tvp_seqc)) {
5274 return (cache_fpl_aborted(fpl));
5279 if ((dvp->v_vflag & VV_ROOT) != 0) {
5282 * The opposite of climb mount is needed here.
5284 return (cache_fpl_partial(fpl));
5287 if (__predict_false(dvp->v_type != VDIR)) {
5288 cache_fpl_smr_exit(fpl);
5289 return (cache_fpl_handled_error(fpl, ENOTDIR));
5292 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5294 return (cache_fpl_aborted(fpl));
5297 nc_flag = atomic_load_char(&ncp->nc_flag);
5298 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5299 if ((nc_flag & NCF_NEGATIVE) != 0)
5300 return (cache_fpl_aborted(fpl));
5301 fpl->tvp = ncp->nc_vp;
5303 fpl->tvp = ncp->nc_dvp;
5306 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5307 if (seqc_in_modify(fpl->tvp_seqc)) {
5308 return (cache_fpl_partial(fpl));
5312 * Acquire fence provided by vn_seqc_read_any above.
5314 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5315 return (cache_fpl_aborted(fpl));
5318 if (!cache_ncp_canuse(ncp)) {
5319 return (cache_fpl_aborted(fpl));
5325 static int __noinline
5326 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5328 u_char nc_flag __diagused;
5332 nc_flag = atomic_load_char(&ncp->nc_flag);
5333 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5336 * If they want to create an entry we need to replace this one.
5338 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5340 return (cache_fplookup_modifying(fpl));
5342 neg_promote = cache_neg_hit_prep(ncp);
5343 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5344 cache_neg_hit_abort(ncp);
5345 return (cache_fpl_partial(fpl));
5348 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5350 cache_neg_hit_finish(ncp);
5351 cache_fpl_smr_exit(fpl);
5352 return (cache_fpl_handled_error(fpl, ENOENT));
5356 * Resolve a symlink. Called by filesystem-specific routines.
5359 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5362 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5364 struct nameidata *ndp;
5365 struct componentname *cnp;
5371 if (__predict_false(len == 0)) {
5375 if (__predict_false(len > MAXPATHLEN - 2)) {
5376 if (cache_fpl_istrailingslash(fpl)) {
5381 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5383 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5384 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5385 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5386 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5390 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5391 return (ENAMETOOLONG);
5394 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5399 if (ndp->ni_pathlen > 1) {
5400 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5402 if (cache_fpl_istrailingslash(fpl)) {
5404 cnp->cn_pnbuf[len] = '/';
5405 cnp->cn_pnbuf[len + 1] = '\0';
5407 cnp->cn_pnbuf[len] = '\0';
5410 bcopy(string, cnp->cn_pnbuf, len);
5412 ndp->ni_pathlen += adjust;
5413 cache_fpl_pathlen_add(fpl, adjust);
5414 cnp->cn_nameptr = cnp->cn_pnbuf;
5415 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5420 static int __noinline
5421 cache_fplookup_symlink(struct cache_fpl *fpl)
5424 struct nameidata *ndp;
5425 struct componentname *cnp;
5426 struct vnode *dvp, *tvp;
5436 if (cache_fpl_islastcn(ndp)) {
5437 if ((cnp->cn_flags & FOLLOW) == 0) {
5438 return (cache_fplookup_final(fpl));
5442 mp = atomic_load_ptr(&dvp->v_mount);
5443 if (__predict_false(mp == NULL)) {
5444 return (cache_fpl_aborted(fpl));
5448 * Note this check races against setting the flag just like regular
5451 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5452 cache_fpl_smr_exit(fpl);
5453 return (cache_fpl_handled_error(fpl, EACCES));
5456 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5457 if (__predict_false(error != 0)) {
5460 return (cache_fpl_partial(fpl));
5464 cache_fpl_smr_exit(fpl);
5465 return (cache_fpl_handled_error(fpl, error));
5467 return (cache_fpl_aborted(fpl));
5471 if (*(cnp->cn_nameptr) == '/') {
5472 fpl->dvp = cache_fpl_handle_root(fpl);
5473 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5474 if (seqc_in_modify(fpl->dvp_seqc)) {
5475 return (cache_fpl_aborted(fpl));
5478 * The main loop assumes that ->dvp points to a vnode belonging
5479 * to a filesystem which can do lockless lookup, but the absolute
5480 * symlink can be wandering off to one which does not.
5482 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5483 if (__predict_false(mp == NULL)) {
5484 return (cache_fpl_aborted(fpl));
5486 if (!cache_fplookup_mp_supported(mp)) {
5487 cache_fpl_checkpoint(fpl);
5488 return (cache_fpl_partial(fpl));
5490 if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir)) {
5491 return (cache_fpl_aborted(fpl));
5498 cache_fplookup_next(struct cache_fpl *fpl)
5500 struct componentname *cnp;
5501 struct namecache *ncp;
5502 struct vnode *dvp, *tvp;
5511 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5512 if (cnp->cn_namelen == 1) {
5513 return (cache_fplookup_dot(fpl));
5515 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5516 return (cache_fplookup_dotdot(fpl));
5520 MPASS(!cache_fpl_isdotdot(cnp));
5522 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5523 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5524 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5528 if (__predict_false(ncp == NULL)) {
5529 return (cache_fplookup_noentry(fpl));
5532 tvp = atomic_load_ptr(&ncp->nc_vp);
5533 nc_flag = atomic_load_char(&ncp->nc_flag);
5534 if ((nc_flag & NCF_NEGATIVE) != 0) {
5535 return (cache_fplookup_neg(fpl, ncp, hash));
5538 if (!cache_ncp_canuse(ncp)) {
5539 return (cache_fpl_partial(fpl));
5543 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5544 if (seqc_in_modify(fpl->tvp_seqc)) {
5545 return (cache_fpl_partial(fpl));
5548 counter_u64_add(numposhits, 1);
5549 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5552 if (cache_fplookup_is_mp(fpl)) {
5553 error = cache_fplookup_cross_mount(fpl);
5559 cache_fplookup_mp_supported(struct mount *mp)
5563 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5569 * Walk up the mount stack (if any).
5571 * Correctness is provided in the following ways:
5572 * - all vnodes are protected from freeing with SMR
5573 * - struct mount objects are type stable making them always safe to access
5574 * - stability of the particular mount is provided by busying it
5575 * - relationship between the vnode which is mounted on and the mount is
5576 * verified with the vnode sequence counter after busying
5577 * - association between root vnode of the mount and the mount is protected
5580 * From that point on we can read the sequence counter of the root vnode
5581 * and get the next mount on the stack (if any) using the same protection.
5583 * By the end of successful walk we are guaranteed the reached state was
5584 * indeed present at least at some point which matches the regular lookup.
5586 static int __noinline
5587 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5589 struct mount *mp, *prev_mp;
5590 struct mount_pcpu *mpcpu, *prev_mpcpu;
5595 vp_seqc = fpl->tvp_seqc;
5597 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5598 mp = atomic_load_ptr(&vp->v_mountedhere);
5599 if (__predict_false(mp == NULL)) {
5605 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5606 if (prev_mp != NULL)
5607 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5608 return (cache_fpl_partial(fpl));
5610 if (prev_mp != NULL)
5611 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5612 if (!vn_seqc_consistent(vp, vp_seqc)) {
5613 vfs_op_thread_exit_crit(mp, mpcpu);
5614 return (cache_fpl_partial(fpl));
5616 if (!cache_fplookup_mp_supported(mp)) {
5617 vfs_op_thread_exit_crit(mp, mpcpu);
5618 return (cache_fpl_partial(fpl));
5620 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5622 vfs_op_thread_exit_crit(mp, mpcpu);
5623 return (cache_fpl_partial(fpl));
5625 vp_seqc = vn_seqc_read_any(vp);
5626 if (seqc_in_modify(vp_seqc)) {
5627 vfs_op_thread_exit_crit(mp, mpcpu);
5628 return (cache_fpl_partial(fpl));
5632 mp = atomic_load_ptr(&vp->v_mountedhere);
5637 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5639 fpl->tvp_seqc = vp_seqc;
5643 static int __noinline
5644 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5647 struct mount_pcpu *mpcpu;
5652 vp_seqc = fpl->tvp_seqc;
5654 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5655 mp = atomic_load_ptr(&vp->v_mountedhere);
5656 if (__predict_false(mp == NULL)) {
5660 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5661 return (cache_fpl_partial(fpl));
5663 if (!vn_seqc_consistent(vp, vp_seqc)) {
5664 vfs_op_thread_exit_crit(mp, mpcpu);
5665 return (cache_fpl_partial(fpl));
5667 if (!cache_fplookup_mp_supported(mp)) {
5668 vfs_op_thread_exit_crit(mp, mpcpu);
5669 return (cache_fpl_partial(fpl));
5671 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5672 if (__predict_false(vp == NULL)) {
5673 vfs_op_thread_exit_crit(mp, mpcpu);
5674 return (cache_fpl_partial(fpl));
5676 vp_seqc = vn_seqc_read_any(vp);
5677 vfs_op_thread_exit_crit(mp, mpcpu);
5678 if (seqc_in_modify(vp_seqc)) {
5679 return (cache_fpl_partial(fpl));
5681 mp = atomic_load_ptr(&vp->v_mountedhere);
5682 if (__predict_false(mp != NULL)) {
5684 * There are possibly more mount points on top.
5685 * Normally this does not happen so for simplicity just start
5688 return (cache_fplookup_climb_mount(fpl));
5692 fpl->tvp_seqc = vp_seqc;
5697 * Check if a vnode is mounted on.
5700 cache_fplookup_is_mp(struct cache_fpl *fpl)
5705 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5711 * The code was originally copy-pasted from regular lookup and despite
5712 * clean ups leaves performance on the table. Any modifications here
5713 * must take into account that in case off fallback the resulting
5714 * nameidata state has to be compatible with the original.
5718 * Debug ni_pathlen tracking.
5722 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5725 fpl->debug.ni_pathlen += n;
5726 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5727 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5731 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5734 fpl->debug.ni_pathlen -= n;
5735 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5736 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5740 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5743 cache_fpl_pathlen_add(fpl, 1);
5747 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5750 cache_fpl_pathlen_sub(fpl, 1);
5754 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5759 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5764 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5769 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5775 cache_fplookup_parse(struct cache_fpl *fpl)
5777 struct nameidata *ndp;
5778 struct componentname *cnp;
5788 * Find the end of this path component, it is either / or nul.
5790 * Store / as a temporary sentinel so that we only have one character
5791 * to test for. Pathnames tend to be short so this should not be
5792 * resulting in cache misses.
5794 * TODO: fix this to be word-sized.
5796 MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5797 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5798 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5799 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5800 fpl->nulchar, cnp->cn_pnbuf));
5801 KASSERT(*fpl->nulchar == '\0',
5802 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5804 hash = cache_get_hash_iter_start(dvp);
5805 *fpl->nulchar = '/';
5806 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5807 KASSERT(*cp != '\0',
5808 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5810 hash = cache_get_hash_iter(*cp, hash);
5813 *fpl->nulchar = '\0';
5814 fpl->hash = cache_get_hash_iter_finish(hash);
5816 cnp->cn_namelen = cp - cnp->cn_nameptr;
5817 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5821 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5822 * we are going to fail this lookup with ENAMETOOLONG (see below).
5824 if (cnp->cn_namelen <= NAME_MAX) {
5825 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5826 panic("%s: mismatched hash for [%s] len %ld", __func__,
5827 cnp->cn_nameptr, cnp->cn_namelen);
5833 * Hack: we have to check if the found path component's length exceeds
5834 * NAME_MAX. However, the condition is very rarely true and check can
5835 * be elided in the common case -- if an entry was found in the cache,
5836 * then it could not have been too long to begin with.
5842 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5844 struct nameidata *ndp;
5845 struct componentname *cnp;
5850 cnp->cn_nameptr = ndp->ni_next;
5851 KASSERT(*(cnp->cn_nameptr) == '/',
5852 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5853 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5855 cache_fpl_pathlen_dec(fpl);
5859 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5861 * Lockless lookup tries to elide checking for spurious slashes and should they
5862 * be present is guaranteed to fail to find an entry. In this case the caller
5863 * must check if the name starts with a slash and call this routine. It is
5864 * going to fast forward across the spurious slashes and set the state up for
5867 static int __noinline
5868 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5870 struct nameidata *ndp;
5871 struct componentname *cnp;
5876 MPASS(*(cnp->cn_nameptr) == '/');
5879 cache_fpl_pathlen_dec(fpl);
5880 } while (*(cnp->cn_nameptr) == '/');
5883 * Go back to one slash so that cache_fplookup_parse_advance has
5884 * something to skip.
5887 cache_fpl_pathlen_inc(fpl);
5890 * cache_fplookup_parse_advance starts from ndp->ni_next
5892 ndp->ni_next = cnp->cn_nameptr;
5895 * See cache_fplookup_dot.
5897 fpl->tvp = fpl->dvp;
5898 fpl->tvp_seqc = fpl->dvp_seqc;
5904 * Handle trailing slashes (e.g., "foo/").
5906 * If a trailing slash is found the terminal vnode must be a directory.
5907 * Regular lookup shortens the path by nulifying the first trailing slash and
5908 * sets the TRAILINGSLASH flag to denote this took place. There are several
5909 * checks on it performed later.
5911 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5912 * manner relying on an invariant that a non-directory vnode will get a miss.
5913 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5915 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5916 * and denotes this is the last path component, which avoids looping back.
5918 * Only plain lookups are supported for now to restrict corner cases to handle.
5920 static int __noinline
5921 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5926 struct nameidata *ndp;
5927 struct componentname *cnp;
5928 struct namecache *ncp;
5930 char *cn_nameptr_orig, *cn_nameptr_slash;
5937 tvp_seqc = fpl->tvp_seqc;
5939 MPASS(fpl->dvp == fpl->tvp);
5940 KASSERT(cache_fpl_istrailingslash(fpl),
5941 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5943 KASSERT(cnp->cn_nameptr[0] == '\0',
5944 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5946 KASSERT(cnp->cn_namelen == 0,
5947 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5949 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5951 if (cnp->cn_nameiop != LOOKUP) {
5952 return (cache_fpl_aborted(fpl));
5955 if (__predict_false(tvp->v_type != VDIR)) {
5956 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5957 return (cache_fpl_aborted(fpl));
5959 cache_fpl_smr_exit(fpl);
5960 return (cache_fpl_handled_error(fpl, ENOTDIR));
5964 * Denote the last component.
5966 ndp->ni_next = &cnp->cn_nameptr[0];
5967 MPASS(cache_fpl_islastcn(ndp));
5970 * Unwind trailing slashes.
5972 cn_nameptr_orig = cnp->cn_nameptr;
5973 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5975 if (cnp->cn_nameptr[0] != '/') {
5981 * Unwind to the beginning of the path component.
5983 * Note the path may or may not have started with a slash.
5985 cn_nameptr_slash = cnp->cn_nameptr;
5986 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5988 if (cnp->cn_nameptr[0] == '/') {
5992 if (cnp->cn_nameptr[0] == '/') {
5996 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5997 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5998 cache_fpl_checkpoint(fpl);
6001 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
6002 if (ni_pathlen != fpl->debug.ni_pathlen) {
6003 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
6004 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
6005 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
6010 * If this was a "./" lookup the parent directory is already correct.
6012 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
6017 * Otherwise we need to look it up.
6020 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
6021 if (__predict_false(ncp == NULL)) {
6022 return (cache_fpl_aborted(fpl));
6024 nc_flag = atomic_load_char(&ncp->nc_flag);
6025 if ((nc_flag & NCF_ISDOTDOT) != 0) {
6026 return (cache_fpl_aborted(fpl));
6028 fpl->dvp = ncp->nc_dvp;
6029 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
6030 if (seqc_in_modify(fpl->dvp_seqc)) {
6031 return (cache_fpl_aborted(fpl));
6037 * See the API contract for VOP_FPLOOKUP_VEXEC.
6039 static int __noinline
6040 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
6042 struct componentname *cnp;
6048 dvp_seqc = fpl->dvp_seqc;
6051 * Hack: delayed empty path checking.
6053 if (cnp->cn_pnbuf[0] == '\0') {
6054 return (cache_fplookup_emptypath(fpl));
6058 * TODO: Due to ignoring trailing slashes lookup will perform a
6059 * permission check on the last dir when it should not be doing it. It
6060 * may fail, but said failure should be ignored. It is possible to fix
6061 * it up fully without resorting to regular lookup, but for now just
6064 if (cache_fpl_istrailingslash(fpl)) {
6065 return (cache_fpl_aborted(fpl));
6069 * Hack: delayed degenerate path checking.
6071 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
6072 return (cache_fplookup_degenerate(fpl));
6076 * Hack: delayed name len checking.
6078 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
6079 cache_fpl_smr_exit(fpl);
6080 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
6084 * Hack: they may be looking up foo/bar, where foo is not a directory.
6085 * In such a case we need to return ENOTDIR, but we may happen to get
6086 * here with a different error.
6088 if (dvp->v_type != VDIR) {
6093 * Hack: handle O_SEARCH.
6095 * Open Group Base Specifications Issue 7, 2018 edition states:
6097 * If the access mode of the open file description associated with the
6098 * file descriptor is not O_SEARCH, the function shall check whether
6099 * directory searches are permitted using the current permissions of
6100 * the directory underlying the file descriptor. If the access mode is
6101 * O_SEARCH, the function shall not perform the check.
6104 * Regular lookup tests for the NOEXECCHECK flag for every path
6105 * component to decide whether to do the permission check. However,
6106 * since most lookups never have the flag (and when they do it is only
6107 * present for the first path component), lockless lookup only acts on
6108 * it if there is a permission problem. Here the flag is represented
6109 * with a boolean so that we don't have to clear it on the way out.
6111 * For simplicity this always aborts.
6112 * TODO: check if this is the first lookup and ignore the permission
6113 * problem. Note the flag has to survive fallback (if it happens to be
6117 return (cache_fpl_aborted(fpl));
6122 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6123 error = cache_fpl_aborted(fpl);
6125 cache_fpl_partial(fpl);
6129 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6130 error = cache_fpl_aborted(fpl);
6132 cache_fpl_smr_exit(fpl);
6133 cache_fpl_handled_error(fpl, error);
6141 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
6143 struct nameidata *ndp;
6144 struct componentname *cnp;
6151 cache_fpl_checkpoint(fpl);
6154 * The vnode at hand is almost always stable, skip checking for it.
6155 * Worst case this postpones the check towards the end of the iteration
6159 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
6161 mp = atomic_load_ptr(&dvp->v_mount);
6162 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
6163 return (cache_fpl_aborted(fpl));
6166 MPASS(fpl->tvp == NULL);
6169 cache_fplookup_parse(fpl);
6171 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
6172 if (__predict_false(error != 0)) {
6173 error = cache_fplookup_failed_vexec(fpl, error);
6177 error = cache_fplookup_next(fpl);
6178 if (__predict_false(cache_fpl_terminated(fpl))) {
6182 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
6184 if (fpl->tvp->v_type == VLNK) {
6185 error = cache_fplookup_symlink(fpl);
6186 if (cache_fpl_terminated(fpl)) {
6190 if (cache_fpl_islastcn(ndp)) {
6191 error = cache_fplookup_final(fpl);
6195 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
6196 error = cache_fpl_aborted(fpl);
6200 fpl->dvp = fpl->tvp;
6201 fpl->dvp_seqc = fpl->tvp_seqc;
6202 cache_fplookup_parse_advance(fpl);
6205 cache_fpl_checkpoint(fpl);
6212 * Fast path lookup protected with SMR and sequence counters.
6214 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
6216 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
6219 * Traditional vnode lookup conceptually looks like this:
6225 * vn_unlock(current);
6232 * Each jump to the next vnode is safe memory-wise and atomic with respect to
6233 * any modifications thanks to holding respective locks.
6235 * The same guarantee can be provided with a combination of safe memory
6236 * reclamation and sequence counters instead. If all operations which affect
6237 * the relationship between the current vnode and the one we are looking for
6238 * also modify the counter, we can verify whether all the conditions held as
6239 * we made the jump. This includes things like permissions, mount points etc.
6240 * Counter modification is provided by enclosing relevant places in
6241 * vn_seqc_write_begin()/end() calls.
6243 * Thus this translates to:
6246 * dvp_seqc = seqc_read_any(dvp);
6247 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
6251 * tvp_seqc = seqc_read_any(tvp);
6252 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6254 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6256 * dvp = tvp; // we know nothing of importance has changed
6257 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6261 * vget(); // secure the vnode
6262 * if (!seqc_consistent(tvp, tvp_seqc) // final check
6264 * // at this point we know nothing has changed for any parent<->child pair
6265 * // as they were crossed during the lookup, meaning we matched the guarantee
6266 * // of the locked variant
6269 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6270 * - they are called while within vfs_smr protection which they must never exit
6271 * - EAGAIN can be returned to denote checking could not be performed, it is
6272 * always valid to return it
6273 * - if the sequence counter has not changed the result must be valid
6274 * - if the sequence counter has changed both false positives and false negatives
6275 * are permitted (since the result will be rejected later)
6276 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6278 * Caveats to watch out for:
6279 * - vnodes are passed unlocked and unreferenced with nothing stopping
6280 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6281 * to use atomic_load_ptr to fetch it.
6282 * - the aforementioned object can also get freed, meaning absent other means it
6283 * should be protected with vfs_smr
6284 * - either safely checking permissions as they are modified or guaranteeing
6285 * their stability is left to the routine
6288 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6291 struct cache_fpl fpl;
6294 struct componentname *cnp;
6297 fpl.status = CACHE_FPL_STATUS_UNSET;
6300 fpl.cnp = cnp = &ndp->ni_cnd;
6301 MPASS(ndp->ni_lcf == 0);
6302 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6303 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6305 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6306 MPASS(ndp->ni_resflags == 0);
6308 if (__predict_false(!cache_can_fplookup(&fpl))) {
6309 *status = fpl.status;
6310 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6311 return (EOPNOTSUPP);
6314 cache_fpl_checkpoint_outer(&fpl);
6316 cache_fpl_smr_enter_initial(&fpl);
6318 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6320 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6321 fpl.fsearch = false;
6322 fpl.tvp = NULL; /* for degenerate path handling */
6324 pwd = pwd_get_smr();
6326 namei_setup_rootdir(ndp, cnp, pwd);
6327 ndp->ni_topdir = pwd->pwd_jdir;
6329 if (cnp->cn_pnbuf[0] == '/') {
6330 dvp = cache_fpl_handle_root(&fpl);
6331 ndp->ni_resflags = NIRES_ABS;
6333 if (ndp->ni_dirfd == AT_FDCWD) {
6334 dvp = pwd->pwd_cdir;
6336 error = cache_fplookup_dirfd(&fpl, &dvp);
6337 if (__predict_false(error != 0)) {
6343 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6344 error = cache_fplookup_impl(dvp, &fpl);
6346 cache_fpl_smr_assert_not_entered(&fpl);
6347 cache_fpl_assert_status(&fpl);
6348 *status = fpl.status;
6349 if (SDT_PROBES_ENABLED()) {
6350 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6351 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6352 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6356 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6357 MPASS(error != CACHE_FPL_FAILED);
6359 cache_fpl_cleanup_cnp(fpl.cnp);
6360 MPASS(fpl.dvp == NULL);
6361 MPASS(fpl.tvp == NULL);
6363 ndp->ni_dvp = fpl.dvp;
6364 ndp->ni_vp = fpl.tvp;