2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993, 1995
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Poul-Henning Kamp of the FreeBSD Project.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
41 #include "opt_ktrace.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/capsicum.h>
46 #include <sys/counter.h>
47 #include <sys/filedesc.h>
48 #include <sys/fnv_hash.h>
49 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/fcntl.h>
55 #include <sys/mount.h>
56 #include <sys/namei.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysproto.h>
65 #include <sys/vnode.h>
68 #include <sys/ktrace.h>
71 #include <machine/_inttypes.h>
74 #include <sys/capsicum.h>
76 #include <security/audit/audit.h>
77 #include <security/mac/mac_framework.h>
86 * High level overview of name caching in the VFS layer.
88 * Originally caching was implemented as part of UFS, later extracted to allow
89 * use by other filesystems. A decision was made to make it optional and
90 * completely detached from the rest of the kernel, which comes with limitations
91 * outlined near the end of this comment block.
93 * This fundamental choice needs to be revisited. In the meantime, the current
94 * state is described below. Significance of all notable routines is explained
95 * in comments placed above their implementation. Scattered thoroughout the
96 * file are TODO comments indicating shortcomings which can be fixed without
97 * reworking everything (most of the fixes will likely be reusable). Various
98 * details are omitted from this explanation to not clutter the overview, they
99 * have to be checked by reading the code and associated commentary.
101 * Keep in mind that it's individual path components which are cached, not full
102 * paths. That is, for a fully cached path "foo/bar/baz" there are 3 entries,
105 * I. Data organization
107 * Entries are described by "struct namecache" objects and stored in a hash
108 * table. See cache_get_hash for more information.
110 * "struct vnode" contains pointers to source entries (names which can be found
111 * when traversing through said vnode), destination entries (names of that
112 * vnode (see "Limitations" for a breakdown on the subject) and a pointer to
115 * The (directory vnode; name) tuple reliably determines the target entry if
118 * Since there are no small locks at this time (all are 32 bytes in size on
119 * LP64), the code works around the problem by introducing lock arrays to
120 * protect hash buckets and vnode lists.
122 * II. Filesystem integration
124 * Filesystems participating in name caching do the following:
125 * - set vop_lookup routine to vfs_cache_lookup
126 * - set vop_cachedlookup to whatever can perform the lookup if the above fails
127 * - if they support lockless lookup (see below), vop_fplookup_vexec and
128 * vop_fplookup_symlink are set along with the MNTK_FPLOOKUP flag on the
130 * - call cache_purge or cache_vop_* routines to eliminate stale entries as
132 * - call cache_enter to add entries depending on the MAKEENTRY flag
134 * With the above in mind, there are 2 entry points when doing lookups:
135 * - ... -> namei -> cache_fplookup -- this is the default
136 * - ... -> VOP_LOOKUP -> vfs_cache_lookup -- normally only called by namei
137 * should the above fail
139 * Example code flow how an entry is added:
140 * ... -> namei -> cache_fplookup -> cache_fplookup_noentry -> VOP_LOOKUP ->
141 * vfs_cache_lookup -> VOP_CACHEDLOOKUP -> ufs_lookup_ino -> cache_enter
143 * III. Performance considerations
145 * For lockless case forward lookup avoids any writes to shared areas apart
146 * from the terminal path component. In other words non-modifying lookups of
147 * different files don't suffer any scalability problems in the namecache.
148 * Looking up the same file is limited by VFS and goes beyond the scope of this
151 * At least on amd64 the single-threaded bottleneck for long paths is hashing
152 * (see cache_get_hash). There are cases where the code issues acquire fence
153 * multiple times, they can be combined on architectures which suffer from it.
155 * For locked case each encountered vnode has to be referenced and locked in
156 * order to be handed out to the caller (normally that's namei). This
157 * introduces significant hit single-threaded and serialization multi-threaded.
159 * Reverse lookup (e.g., "getcwd") fully scales provided it is fully cached --
160 * avoids any writes to shared areas to any components.
162 * Unrelated insertions are partially serialized on updating the global entry
163 * counter and possibly serialized on colliding bucket or vnode locks.
167 * Note not everything has an explicit dtrace probe nor it should have, thus
168 * some of the one-liners below depend on implementation details.
172 * # Check what lookups failed to be handled in a lockless manner. Column 1 is
173 * # line number, column 2 is status code (see cache_fpl_status)
174 * dtrace -n 'vfs:fplookup:lookup:done { @[arg1, arg2] = count(); }'
176 * # Lengths of names added by binary name
177 * dtrace -n 'fbt::cache_enter_time:entry { @[execname] = quantize(args[2]->cn_namelen); }'
179 * # Same as above but only those which exceed 64 characters
180 * dtrace -n 'fbt::cache_enter_time:entry /args[2]->cn_namelen > 64/ { @[execname] = quantize(args[2]->cn_namelen); }'
182 * # Who is performing lookups with spurious slashes (e.g., "foo//bar") and what
184 * dtrace -n 'fbt::cache_fplookup_skip_slashes:entry { @[execname, stringof(args[0]->cnp->cn_pnbuf)] = count(); }'
186 * V. Limitations and implementation defects
188 * - since it is possible there is no entry for an open file, tools like
189 * "procstat" may fail to resolve fd -> vnode -> path to anything
190 * - even if a filesystem adds an entry, it may get purged (e.g., due to memory
191 * shortage) in which case the above problem applies
192 * - hardlinks are not tracked, thus if a vnode is reachable in more than one
193 * way, resolving a name may return a different path than the one used to
194 * open it (even if said path is still valid)
195 * - by default entries are not added for newly created files
196 * - adding an entry may need to evict negative entry first, which happens in 2
197 * distinct places (evicting on lookup, adding in a later VOP) making it
198 * impossible to simply reuse it
199 * - there is a simple scheme to evict negative entries as the cache is approaching
200 * its capacity, but it is very unclear if doing so is a good idea to begin with
201 * - vnodes are subject to being recycled even if target inode is left in memory,
202 * which loses the name cache entries when it perhaps should not. in case of tmpfs
203 * names get duplicated -- kept by filesystem itself and namecache separately
204 * - struct namecache has a fixed size and comes in 2 variants, often wasting space.
205 * now hard to replace with malloc due to dependence on SMR.
206 * - lack of better integration with the kernel also turns nullfs into a layered
207 * filesystem instead of something which can take advantage of caching
210 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
213 SDT_PROVIDER_DECLARE(vfs);
214 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
216 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
218 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
220 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
222 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
223 "struct namecache *", "int", "int");
224 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
225 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
226 "char *", "struct vnode *");
227 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
228 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
229 "struct vnode *", "char *");
230 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
232 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
233 "struct vnode *", "char *");
234 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
236 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
237 "struct componentname *");
238 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
239 "struct componentname *");
240 SDT_PROBE_DEFINE3(vfs, namecache, purge, done, "struct vnode *", "size_t", "size_t");
241 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
242 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
243 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
244 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
246 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
248 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
250 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
252 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
253 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
254 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
257 * This structure describes the elements in the cache of recent
258 * names looked up by namei.
264 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
265 "the state must fit in a union with a pointer without growing it");
268 LIST_ENTRY(namecache) nc_src; /* source vnode list */
269 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
270 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
271 struct vnode *nc_dvp; /* vnode of parent of name */
273 struct vnode *nu_vp; /* vnode the name refers to */
274 struct negstate nu_neg;/* negative entry state */
276 u_char nc_flag; /* flag bits */
277 u_char nc_nlen; /* length of name */
278 char nc_name[0]; /* segment name + nul */
282 * struct namecache_ts repeats struct namecache layout up to the
284 * struct namecache_ts is used in place of struct namecache when time(s) need
285 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
286 * both a non-dotdot directory name plus dotdot for the directory's
289 * See below for alignment requirement.
291 struct namecache_ts {
292 struct timespec nc_time; /* timespec provided by fs */
293 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
294 int nc_ticks; /* ticks value when entry was added */
296 struct namecache nc_nc;
299 TAILQ_HEAD(cache_freebatch, namecache);
302 * At least mips n32 performs 64-bit accesses to timespec as found
303 * in namecache_ts and requires them to be aligned. Since others
304 * may be in the same spot suffer a little bit and enforce the
305 * alignment for everyone. Note this is a nop for 64-bit platforms.
307 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
310 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
311 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
312 * smaller and the value was bumped to retain the total size, but it
313 * was never re-evaluated for suitability. A simple test counting
314 * lengths during package building shows that the value of 45 covers
315 * about 86% of all added entries, reaching 99% at 65.
317 * Regardless of the above, use of dedicated zones instead of malloc may be
318 * inducing additional waste. This may be hard to address as said zones are
319 * tied to VFS SMR. Even if retaining them, the current split should be
323 #define CACHE_PATH_CUTOFF 45
324 #define CACHE_LARGE_PAD 6
326 #define CACHE_PATH_CUTOFF 41
327 #define CACHE_LARGE_PAD 2
330 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
331 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
332 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
333 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
335 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
336 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
337 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
338 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
340 #define nc_vp n_un.nu_vp
341 #define nc_neg n_un.nu_neg
344 * Flags in namecache.nc_flag
346 #define NCF_WHITE 0x01
347 #define NCF_ISDOTDOT 0x02
350 #define NCF_DVDROP 0x10
351 #define NCF_NEGATIVE 0x20
352 #define NCF_INVALID 0x40
356 * Flags in negstate.neg_flag
360 static bool cache_neg_evict_cond(u_long lnumcache);
363 * Mark an entry as invalid.
365 * This is called before it starts getting deconstructed.
368 cache_ncp_invalidate(struct namecache *ncp)
371 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
372 ("%s: entry %p already invalid", __func__, ncp));
373 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
374 atomic_thread_fence_rel();
378 * Check whether the entry can be safely used.
380 * All places which elide locks are supposed to call this after they are
381 * done with reading from an entry.
383 #define cache_ncp_canuse(ncp) ({ \
384 struct namecache *_ncp = (ncp); \
387 atomic_thread_fence_acq(); \
388 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
389 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0); \
393 * Like the above but also checks NCF_WHITE.
395 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
396 struct namecache *_ncp = (ncp); \
399 atomic_thread_fence_acq(); \
400 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
401 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
406 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
407 "Name cache parameters");
409 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
410 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
411 "Total namecache capacity");
413 u_int ncsizefactor = 2;
414 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
415 "Size factor for namecache");
417 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
418 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
419 "Ratio of negative namecache entries");
422 * Negative entry % of namecache capacity above which automatic eviction is allowed.
424 * Check cache_neg_evict_cond for details.
426 static u_int ncnegminpct = 3;
428 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
429 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
430 "Negative entry count above which automatic eviction is allowed");
433 * Structures associated with name caching.
435 #define NCHHASH(hash) \
436 (&nchashtbl[(hash) & nchash])
437 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
438 static u_long __read_mostly nchash; /* size of hash table */
439 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
440 "Size of namecache hash table");
441 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
442 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
444 struct nchstats nchstats; /* cache effectiveness statistics */
446 static bool __read_frequently cache_fast_revlookup = true;
447 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
448 &cache_fast_revlookup, 0, "");
450 static bool __read_mostly cache_rename_add = true;
451 SYSCTL_BOOL(_vfs, OID_AUTO, cache_rename_add, CTLFLAG_RW,
452 &cache_rename_add, 0, "");
454 static u_int __exclusive_cache_line neg_cycle;
457 #define numneglists (ncneghash + 1)
460 struct mtx nl_evict_lock;
461 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
462 TAILQ_HEAD(, namecache) nl_list;
463 TAILQ_HEAD(, namecache) nl_hotlist;
465 } __aligned(CACHE_LINE_SIZE);
467 static struct neglist neglists[numneglists];
469 static inline struct neglist *
470 NCP2NEGLIST(struct namecache *ncp)
473 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
476 static inline struct negstate *
477 NCP2NEGSTATE(struct namecache *ncp)
480 MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
481 return (&ncp->nc_neg);
484 #define numbucketlocks (ncbuckethash + 1)
485 static u_int __read_mostly ncbuckethash;
486 static struct mtx_padalign __read_mostly *bucketlocks;
487 #define HASH2BUCKETLOCK(hash) \
488 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
490 #define numvnodelocks (ncvnodehash + 1)
491 static u_int __read_mostly ncvnodehash;
492 static struct mtx __read_mostly *vnodelocks;
493 static inline struct mtx *
494 VP2VNODELOCK(struct vnode *vp)
497 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
501 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
503 struct namecache_ts *ncp_ts;
505 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
506 (tsp == NULL && ticksp == NULL),
512 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
513 *tsp = ncp_ts->nc_time;
514 *ticksp = ncp_ts->nc_ticks;
518 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
519 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
520 "VFS namecache enabled");
523 /* Export size information to userland */
524 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
525 sizeof(struct namecache), "sizeof(struct namecache)");
528 * The new name cache statistics
530 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
531 "Name cache statistics");
533 #define STATNODE_ULONG(name, varname, descr) \
534 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
535 #define STATNODE_COUNTER(name, varname, descr) \
536 static COUNTER_U64_DEFINE_EARLY(varname); \
537 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
539 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
540 STATNODE_ULONG(count, numcache, "Number of cache entries");
541 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
542 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
543 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
544 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
545 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
546 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
547 STATNODE_COUNTER(posszaps, numposzaps,
548 "Number of cache hits (positive) we do not want to cache");
549 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
550 STATNODE_COUNTER(negzaps, numnegzaps,
551 "Number of cache hits (negative) we do not want to cache");
552 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
553 /* These count for vn_getcwd(), too. */
554 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
555 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
556 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
557 "Number of fullpath search errors (VOP_VPTOCNP failures)");
558 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
559 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
560 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
563 * Debug or developer statistics.
565 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
566 "Name cache debugging");
567 #define DEBUGNODE_ULONG(name, varname, descr) \
568 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
569 #define DEBUGNODE_COUNTER(name, varname, descr) \
570 static COUNTER_U64_DEFINE_EARLY(varname); \
571 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
573 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
574 "Number of successful removals after relocking");
575 static long zap_bucket_fail;
576 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
577 static long zap_bucket_fail2;
578 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
579 static long cache_lock_vnodes_cel_3_failures;
580 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
581 "Number of times 3-way vnode locking failed");
583 static void cache_zap_locked(struct namecache *ncp);
584 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
585 char **freebuf, size_t *buflen);
586 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
587 char **retbuf, size_t *buflen, size_t addend);
588 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
589 char **retbuf, size_t *buflen);
590 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
591 char **retbuf, size_t *len, size_t addend);
593 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
596 cache_assert_vlp_locked(struct mtx *vlp)
600 mtx_assert(vlp, MA_OWNED);
604 cache_assert_vnode_locked(struct vnode *vp)
608 vlp = VP2VNODELOCK(vp);
609 cache_assert_vlp_locked(vlp);
613 * Directory vnodes with entries are held for two reasons:
614 * 1. make them less of a target for reclamation in vnlru
615 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
617 * It will be feasible to stop doing it altogether if all filesystems start
618 * supporting lockless lookup.
621 cache_hold_vnode(struct vnode *vp)
624 cache_assert_vnode_locked(vp);
625 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
627 counter_u64_add(numcachehv, 1);
631 cache_drop_vnode(struct vnode *vp)
635 * Called after all locks are dropped, meaning we can't assert
636 * on the state of v_cache_src.
639 counter_u64_add(numcachehv, -1);
645 static uma_zone_t __read_mostly cache_zone_small;
646 static uma_zone_t __read_mostly cache_zone_small_ts;
647 static uma_zone_t __read_mostly cache_zone_large;
648 static uma_zone_t __read_mostly cache_zone_large_ts;
651 cache_symlink_alloc(size_t size, int flags)
654 if (size < CACHE_ZONE_SMALL_SIZE) {
655 return (uma_zalloc_smr(cache_zone_small, flags));
657 if (size < CACHE_ZONE_LARGE_SIZE) {
658 return (uma_zalloc_smr(cache_zone_large, flags));
660 counter_u64_add(symlinktoobig, 1);
661 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
666 cache_symlink_free(char *string, size_t size)
669 MPASS(string != NULL);
670 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
671 ("%s: size %zu too big", __func__, size));
673 if (size < CACHE_ZONE_SMALL_SIZE) {
674 uma_zfree_smr(cache_zone_small, string);
677 if (size < CACHE_ZONE_LARGE_SIZE) {
678 uma_zfree_smr(cache_zone_large, string);
681 __assert_unreachable();
684 static struct namecache *
685 cache_alloc_uma(int len, bool ts)
687 struct namecache_ts *ncp_ts;
688 struct namecache *ncp;
690 if (__predict_false(ts)) {
691 if (len <= CACHE_PATH_CUTOFF)
692 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
694 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
695 ncp = &ncp_ts->nc_nc;
697 if (len <= CACHE_PATH_CUTOFF)
698 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
700 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
706 cache_free_uma(struct namecache *ncp)
708 struct namecache_ts *ncp_ts;
710 if (__predict_false(ncp->nc_flag & NCF_TS)) {
711 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
712 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
713 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
715 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
717 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
718 uma_zfree_smr(cache_zone_small, ncp);
720 uma_zfree_smr(cache_zone_large, ncp);
724 static struct namecache *
725 cache_alloc(int len, bool ts)
730 * Avoid blowout in namecache entries.
733 * 1. filesystems may end up trying to add an already existing entry
734 * (for example this can happen after a cache miss during concurrent
735 * lookup), in which case we will call cache_neg_evict despite not
737 * 2. the routine may fail to free anything and no provisions are made
738 * to make it try harder (see the inside for failure modes)
739 * 3. it only ever looks at negative entries.
741 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
742 if (cache_neg_evict_cond(lnumcache)) {
743 lnumcache = atomic_load_long(&numcache);
745 if (__predict_false(lnumcache >= ncsize)) {
746 atomic_subtract_long(&numcache, 1);
747 counter_u64_add(numdrops, 1);
750 return (cache_alloc_uma(len, ts));
754 cache_free(struct namecache *ncp)
758 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
759 cache_drop_vnode(ncp->nc_dvp);
762 atomic_subtract_long(&numcache, 1);
766 cache_free_batch(struct cache_freebatch *batch)
768 struct namecache *ncp, *nnp;
772 if (TAILQ_EMPTY(batch))
774 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
775 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
776 cache_drop_vnode(ncp->nc_dvp);
781 atomic_subtract_long(&numcache, i);
783 SDT_PROBE1(vfs, namecache, purge, batch, i);
789 * The code was made to use FNV in 2001 and this choice needs to be revisited.
791 * Short summary of the difficulty:
792 * The longest name which can be inserted is NAME_MAX characters in length (or
793 * 255 at the time of writing this comment), while majority of names used in
794 * practice are significantly shorter (mostly below 10). More importantly
795 * majority of lookups performed find names are even shorter than that.
797 * This poses a problem where hashes which do better than FNV past word size
798 * (or so) tend to come with additional overhead when finalizing the result,
799 * making them noticeably slower for the most commonly used range.
801 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
803 * When looking it up the most time consuming part by a large margin (at least
804 * on amd64) is hashing. Replacing FNV with something which pessimizes short
805 * input would make the slowest part stand out even more.
809 * TODO: With the value stored we can do better than computing the hash based
813 cache_prehash(struct vnode *vp)
816 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
820 cache_get_hash(char *name, u_char len, struct vnode *dvp)
823 return (fnv_32_buf(name, len, dvp->v_nchash));
827 cache_get_hash_iter_start(struct vnode *dvp)
830 return (dvp->v_nchash);
834 cache_get_hash_iter(char c, uint32_t hash)
837 return (fnv_32_buf(&c, 1, hash));
841 cache_get_hash_iter_finish(uint32_t hash)
847 static inline struct nchashhead *
848 NCP2BUCKET(struct namecache *ncp)
852 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
853 return (NCHHASH(hash));
856 static inline struct mtx *
857 NCP2BUCKETLOCK(struct namecache *ncp)
861 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
862 return (HASH2BUCKETLOCK(hash));
867 cache_assert_bucket_locked(struct namecache *ncp)
871 blp = NCP2BUCKETLOCK(ncp);
872 mtx_assert(blp, MA_OWNED);
876 cache_assert_bucket_unlocked(struct namecache *ncp)
880 blp = NCP2BUCKETLOCK(ncp);
881 mtx_assert(blp, MA_NOTOWNED);
884 #define cache_assert_bucket_locked(x) do { } while (0)
885 #define cache_assert_bucket_unlocked(x) do { } while (0)
888 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
890 _cache_sort_vnodes(void **p1, void **p2)
894 MPASS(*p1 != NULL || *p2 != NULL);
904 cache_lock_all_buckets(void)
908 for (i = 0; i < numbucketlocks; i++)
909 mtx_lock(&bucketlocks[i]);
913 cache_unlock_all_buckets(void)
917 for (i = 0; i < numbucketlocks; i++)
918 mtx_unlock(&bucketlocks[i]);
922 cache_lock_all_vnodes(void)
926 for (i = 0; i < numvnodelocks; i++)
927 mtx_lock(&vnodelocks[i]);
931 cache_unlock_all_vnodes(void)
935 for (i = 0; i < numvnodelocks; i++)
936 mtx_unlock(&vnodelocks[i]);
940 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
943 cache_sort_vnodes(&vlp1, &vlp2);
946 if (!mtx_trylock(vlp1))
949 if (!mtx_trylock(vlp2)) {
959 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
962 MPASS(vlp1 != NULL || vlp2 != NULL);
972 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
975 MPASS(vlp1 != NULL || vlp2 != NULL);
984 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
986 struct nchstats snap;
988 if (req->oldptr == NULL)
989 return (SYSCTL_OUT(req, 0, sizeof(snap)));
992 snap.ncs_goodhits = counter_u64_fetch(numposhits);
993 snap.ncs_neghits = counter_u64_fetch(numneghits);
994 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
995 counter_u64_fetch(numnegzaps);
996 snap.ncs_miss = counter_u64_fetch(nummisszap) +
997 counter_u64_fetch(nummiss);
999 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
1001 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
1002 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
1003 "VFS cache effectiveness statistics");
1006 cache_recalc_neg_min(u_int val)
1009 neg_min = (ncsize * val) / 100;
1013 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1019 error = sysctl_handle_int(oidp, &val, 0, req);
1020 if (error != 0 || req->newptr == NULL)
1023 if (val == ncnegminpct)
1025 if (val < 0 || val > 99)
1028 cache_recalc_neg_min(val);
1032 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1033 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1034 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1038 * Grab an atomic snapshot of the name cache hash chain lengths
1040 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1041 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1042 "hash table stats");
1045 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1047 struct nchashhead *ncpp;
1048 struct namecache *ncp;
1049 int i, error, n_nchash, *cntbuf;
1052 n_nchash = nchash + 1; /* nchash is max index, not count */
1053 if (req->oldptr == NULL)
1054 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1055 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1056 cache_lock_all_buckets();
1057 if (n_nchash != nchash + 1) {
1058 cache_unlock_all_buckets();
1059 free(cntbuf, M_TEMP);
1062 /* Scan hash tables counting entries */
1063 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1064 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1066 cache_unlock_all_buckets();
1067 for (error = 0, i = 0; i < n_nchash; i++)
1068 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1070 free(cntbuf, M_TEMP);
1073 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1074 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1075 "nchash chain lengths");
1078 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1081 struct nchashhead *ncpp;
1082 struct namecache *ncp;
1084 int count, maxlength, used, pct;
1087 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1089 cache_lock_all_buckets();
1090 n_nchash = nchash + 1; /* nchash is max index, not count */
1094 /* Scan hash tables for applicable entries */
1095 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1097 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1102 if (maxlength < count)
1105 n_nchash = nchash + 1;
1106 cache_unlock_all_buckets();
1107 pct = (used * 100) / (n_nchash / 100);
1108 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1111 error = SYSCTL_OUT(req, &used, sizeof(used));
1114 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1117 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1122 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1123 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1124 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1128 * Negative entries management
1130 * Various workloads create plenty of negative entries and barely use them
1131 * afterwards. Moreover malicious users can keep performing bogus lookups
1132 * adding even more entries. For example "make tinderbox" as of writing this
1133 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1136 * As such, a rather aggressive eviction method is needed. The currently
1137 * employed method is a placeholder.
1139 * Entries are split over numneglists separate lists, each of which is further
1140 * split into hot and cold entries. Entries get promoted after getting a hit.
1141 * Eviction happens on addition of new entry.
1143 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1144 "Name cache negative entry statistics");
1146 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1147 "Number of negative cache entries");
1149 static COUNTER_U64_DEFINE_EARLY(neg_created);
1150 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1151 "Number of created negative entries");
1153 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1154 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1155 "Number of evicted negative entries");
1157 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1158 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1159 &neg_evict_skipped_empty,
1160 "Number of times evicting failed due to lack of entries");
1162 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1163 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1164 &neg_evict_skipped_missed,
1165 "Number of times evicting failed due to target entry disappearing");
1167 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1168 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1169 &neg_evict_skipped_contended,
1170 "Number of times evicting failed due to contention");
1172 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1173 "Number of cache hits (negative)");
1176 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1181 for (i = 0; i < numneglists; i++)
1182 out += neglists[i].nl_hotnum;
1184 return (SYSCTL_OUT(req, &out, sizeof(out)));
1186 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1187 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1188 "Number of hot negative entries");
1191 cache_neg_init(struct namecache *ncp)
1193 struct negstate *ns;
1195 ncp->nc_flag |= NCF_NEGATIVE;
1196 ns = NCP2NEGSTATE(ncp);
1199 counter_u64_add(neg_created, 1);
1202 #define CACHE_NEG_PROMOTION_THRESH 2
1205 cache_neg_hit_prep(struct namecache *ncp)
1207 struct negstate *ns;
1210 ns = NCP2NEGSTATE(ncp);
1211 n = atomic_load_char(&ns->neg_hit);
1213 if (n >= CACHE_NEG_PROMOTION_THRESH)
1215 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1218 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1222 * Nothing to do here but it is provided for completeness as some
1223 * cache_neg_hit_prep callers may end up returning without even
1224 * trying to promote.
1226 #define cache_neg_hit_abort(ncp) do { } while (0)
1229 cache_neg_hit_finish(struct namecache *ncp)
1232 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1233 counter_u64_add(numneghits, 1);
1237 * Move a negative entry to the hot list.
1240 cache_neg_promote_locked(struct namecache *ncp)
1243 struct negstate *ns;
1245 ns = NCP2NEGSTATE(ncp);
1246 nl = NCP2NEGLIST(ncp);
1247 mtx_assert(&nl->nl_lock, MA_OWNED);
1248 if ((ns->neg_flag & NEG_HOT) == 0) {
1249 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1250 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1252 ns->neg_flag |= NEG_HOT;
1257 * Move a hot negative entry to the cold list.
1260 cache_neg_demote_locked(struct namecache *ncp)
1263 struct negstate *ns;
1265 ns = NCP2NEGSTATE(ncp);
1266 nl = NCP2NEGLIST(ncp);
1267 mtx_assert(&nl->nl_lock, MA_OWNED);
1268 MPASS(ns->neg_flag & NEG_HOT);
1269 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1270 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1272 ns->neg_flag &= ~NEG_HOT;
1273 atomic_store_char(&ns->neg_hit, 0);
1277 * Move a negative entry to the hot list if it matches the lookup.
1279 * We have to take locks, but they may be contended and in the worst
1280 * case we may need to go off CPU. We don't want to spin within the
1281 * smr section and we can't block with it. Exiting the section means
1282 * the found entry could have been evicted. We are going to look it
1286 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1287 struct namecache *oncp, uint32_t hash)
1289 struct namecache *ncp;
1293 nl = NCP2NEGLIST(oncp);
1295 mtx_lock(&nl->nl_lock);
1297 * For hash iteration.
1302 * Avoid all surprises by only succeeding if we got the same entry and
1303 * bailing completely otherwise.
1304 * XXX There are no provisions to keep the vnode around, meaning we may
1305 * end up promoting a negative entry for a *new* vnode and returning
1306 * ENOENT on its account. This is the error we want to return anyway
1307 * and promotion is harmless.
1309 * In particular at this point there can be a new ncp which matches the
1310 * search but hashes to a different neglist.
1312 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1318 * No match to begin with.
1320 if (__predict_false(ncp == NULL)) {
1325 * The newly found entry may be something different...
1327 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1328 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1333 * ... and not even negative.
1335 nc_flag = atomic_load_char(&ncp->nc_flag);
1336 if ((nc_flag & NCF_NEGATIVE) == 0) {
1340 if (!cache_ncp_canuse(ncp)) {
1344 cache_neg_promote_locked(ncp);
1345 cache_neg_hit_finish(ncp);
1347 mtx_unlock(&nl->nl_lock);
1351 mtx_unlock(&nl->nl_lock);
1356 cache_neg_promote(struct namecache *ncp)
1360 nl = NCP2NEGLIST(ncp);
1361 mtx_lock(&nl->nl_lock);
1362 cache_neg_promote_locked(ncp);
1363 mtx_unlock(&nl->nl_lock);
1367 cache_neg_insert(struct namecache *ncp)
1371 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1372 cache_assert_bucket_locked(ncp);
1373 nl = NCP2NEGLIST(ncp);
1374 mtx_lock(&nl->nl_lock);
1375 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1376 mtx_unlock(&nl->nl_lock);
1377 atomic_add_long(&numneg, 1);
1381 cache_neg_remove(struct namecache *ncp)
1384 struct negstate *ns;
1386 cache_assert_bucket_locked(ncp);
1387 nl = NCP2NEGLIST(ncp);
1388 ns = NCP2NEGSTATE(ncp);
1389 mtx_lock(&nl->nl_lock);
1390 if ((ns->neg_flag & NEG_HOT) != 0) {
1391 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1394 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1396 mtx_unlock(&nl->nl_lock);
1397 atomic_subtract_long(&numneg, 1);
1400 static struct neglist *
1401 cache_neg_evict_select_list(void)
1406 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1407 nl = &neglists[c % numneglists];
1408 if (!mtx_trylock(&nl->nl_evict_lock)) {
1409 counter_u64_add(neg_evict_skipped_contended, 1);
1415 static struct namecache *
1416 cache_neg_evict_select_entry(struct neglist *nl)
1418 struct namecache *ncp, *lncp;
1419 struct negstate *ns, *lns;
1422 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1423 mtx_assert(&nl->nl_lock, MA_OWNED);
1424 ncp = TAILQ_FIRST(&nl->nl_list);
1428 lns = NCP2NEGSTATE(lncp);
1429 for (i = 1; i < 4; i++) {
1430 ncp = TAILQ_NEXT(ncp, nc_dst);
1433 ns = NCP2NEGSTATE(ncp);
1434 if (ns->neg_hit < lns->neg_hit) {
1443 cache_neg_evict(void)
1445 struct namecache *ncp, *ncp2;
1454 nl = cache_neg_evict_select_list();
1459 mtx_lock(&nl->nl_lock);
1460 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1462 cache_neg_demote_locked(ncp);
1464 ncp = cache_neg_evict_select_entry(nl);
1466 counter_u64_add(neg_evict_skipped_empty, 1);
1467 mtx_unlock(&nl->nl_lock);
1468 mtx_unlock(&nl->nl_evict_lock);
1471 nlen = ncp->nc_nlen;
1473 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1474 dvlp = VP2VNODELOCK(dvp);
1475 blp = HASH2BUCKETLOCK(hash);
1476 mtx_unlock(&nl->nl_lock);
1477 mtx_unlock(&nl->nl_evict_lock);
1481 * Note that since all locks were dropped above, the entry may be
1482 * gone or reallocated to be something else.
1484 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1485 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1486 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1490 counter_u64_add(neg_evict_skipped_missed, 1);
1494 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1495 MPASS(blp == NCP2BUCKETLOCK(ncp));
1496 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1498 cache_zap_locked(ncp);
1499 counter_u64_add(neg_evicted, 1);
1510 * Maybe evict a negative entry to create more room.
1512 * The ncnegfactor parameter limits what fraction of the total count
1513 * can comprise of negative entries. However, if the cache is just
1514 * warming up this leads to excessive evictions. As such, ncnegminpct
1515 * (recomputed to neg_min) dictates whether the above should be
1518 * Try evicting if the cache is close to full capacity regardless of
1519 * other considerations.
1522 cache_neg_evict_cond(u_long lnumcache)
1526 if (ncsize - 1000 < lnumcache)
1528 lnumneg = atomic_load_long(&numneg);
1529 if (lnumneg < neg_min)
1531 if (lnumneg * ncnegfactor < lnumcache)
1534 return (cache_neg_evict());
1538 * cache_zap_locked():
1540 * Removes a namecache entry from cache, whether it contains an actual
1541 * pointer to a vnode or if it is just a negative cache entry.
1544 cache_zap_locked(struct namecache *ncp)
1546 struct nchashhead *ncpp;
1547 struct vnode *dvp, *vp;
1552 if (!(ncp->nc_flag & NCF_NEGATIVE))
1553 cache_assert_vnode_locked(vp);
1554 cache_assert_vnode_locked(dvp);
1555 cache_assert_bucket_locked(ncp);
1557 cache_ncp_invalidate(ncp);
1559 ncpp = NCP2BUCKET(ncp);
1560 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1561 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1562 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1563 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1564 if (ncp == vp->v_cache_dd) {
1565 atomic_store_ptr(&vp->v_cache_dd, NULL);
1568 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1569 cache_neg_remove(ncp);
1571 if (ncp->nc_flag & NCF_ISDOTDOT) {
1572 if (ncp == dvp->v_cache_dd) {
1573 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1576 LIST_REMOVE(ncp, nc_src);
1577 if (LIST_EMPTY(&dvp->v_cache_src)) {
1578 ncp->nc_flag |= NCF_DVDROP;
1584 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1588 MPASS(ncp->nc_dvp == vp);
1589 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1590 cache_assert_vnode_locked(vp);
1592 blp = NCP2BUCKETLOCK(ncp);
1594 cache_zap_locked(ncp);
1599 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1602 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1605 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1606 cache_assert_vnode_locked(vp);
1608 if (ncp->nc_flag & NCF_NEGATIVE) {
1609 if (*vlpp != NULL) {
1613 cache_zap_negative_locked_vnode_kl(ncp, vp);
1617 pvlp = VP2VNODELOCK(vp);
1618 blp = NCP2BUCKETLOCK(ncp);
1619 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1620 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1622 if (*vlpp == vlp1 || *vlpp == vlp2) {
1626 if (*vlpp != NULL) {
1630 cache_sort_vnodes(&vlp1, &vlp2);
1635 if (!mtx_trylock(vlp1))
1641 cache_zap_locked(ncp);
1643 if (to_unlock != NULL)
1644 mtx_unlock(to_unlock);
1651 MPASS(*vlpp == NULL);
1657 * If trylocking failed we can get here. We know enough to take all needed locks
1658 * in the right order and re-lookup the entry.
1661 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1662 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1665 struct namecache *rncp;
1667 cache_assert_bucket_unlocked(ncp);
1669 cache_sort_vnodes(&dvlp, &vlp);
1670 cache_lock_vnodes(dvlp, vlp);
1672 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1673 if (rncp == ncp && rncp->nc_dvp == dvp &&
1674 rncp->nc_nlen == cnp->cn_namelen &&
1675 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1679 cache_zap_locked(rncp);
1681 cache_unlock_vnodes(dvlp, vlp);
1682 counter_u64_add(zap_bucket_relock_success, 1);
1687 cache_unlock_vnodes(dvlp, vlp);
1691 static int __noinline
1692 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1693 uint32_t hash, struct mtx *blp)
1695 struct mtx *dvlp, *vlp;
1698 cache_assert_bucket_locked(ncp);
1700 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1702 if (!(ncp->nc_flag & NCF_NEGATIVE))
1703 vlp = VP2VNODELOCK(ncp->nc_vp);
1704 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1705 cache_zap_locked(ncp);
1707 cache_unlock_vnodes(dvlp, vlp);
1713 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1716 static __noinline int
1717 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1719 struct namecache *ncp;
1721 struct mtx *dvlp, *dvlp2;
1725 if (cnp->cn_namelen == 2 &&
1726 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1727 dvlp = VP2VNODELOCK(dvp);
1731 ncp = dvp->v_cache_dd;
1736 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1739 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1740 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1742 MPASS(dvp->v_cache_dd == NULL);
1748 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1753 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1757 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1758 blp = HASH2BUCKETLOCK(hash);
1760 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1765 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1766 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1767 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1776 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1777 if (__predict_false(error != 0)) {
1781 counter_u64_add(numposzaps, 1);
1782 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1786 counter_u64_add(nummisszap, 1);
1787 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1791 static int __noinline
1792 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1793 struct timespec *tsp, int *ticksp)
1798 counter_u64_add(dothits, 1);
1799 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1806 * When we lookup "." we still can be asked to lock it
1809 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1810 if (ltype != VOP_ISLOCKED(*vpp)) {
1811 if (ltype == LK_EXCLUSIVE) {
1812 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1813 if (VN_IS_DOOMED((*vpp))) {
1814 /* forced unmount */
1820 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1825 static int __noinline
1826 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1827 struct timespec *tsp, int *ticksp)
1829 struct namecache_ts *ncp_ts;
1830 struct namecache *ncp;
1836 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1838 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1839 cache_remove_cnp(dvp, cnp);
1843 counter_u64_add(dotdothits, 1);
1845 dvlp = VP2VNODELOCK(dvp);
1847 ncp = dvp->v_cache_dd;
1849 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1853 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1854 if (ncp->nc_flag & NCF_NEGATIVE)
1861 goto negative_success;
1862 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1863 cache_out_ts(ncp, tsp, ticksp);
1864 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1865 NCF_DTS && tsp != NULL) {
1866 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1867 *tsp = ncp_ts->nc_dotdottime;
1871 ltype = VOP_ISLOCKED(dvp);
1873 vs = vget_prep(*vpp);
1875 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1876 vn_lock(dvp, ltype | LK_RETRY);
1877 if (VN_IS_DOOMED(dvp)) {
1889 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1890 if (cnp->cn_flags & ISLASTCN) {
1891 counter_u64_add(numnegzaps, 1);
1892 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1899 whiteout = (ncp->nc_flag & NCF_WHITE);
1900 cache_out_ts(ncp, tsp, ticksp);
1901 if (cache_neg_hit_prep(ncp))
1902 cache_neg_promote(ncp);
1904 cache_neg_hit_finish(ncp);
1907 cnp->cn_flags |= ISWHITEOUT;
1912 * Lookup a name in the name cache
1916 * - dvp: Parent directory in which to search.
1917 * - vpp: Return argument. Will contain desired vnode on cache hit.
1918 * - cnp: Parameters of the name search. The most interesting bits of
1919 * the cn_flags field have the following meanings:
1920 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1922 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1923 * - tsp: Return storage for cache timestamp. On a successful (positive
1924 * or negative) lookup, tsp will be filled with any timespec that
1925 * was stored when this cache entry was created. However, it will
1926 * be clear for "." entries.
1927 * - ticks: Return storage for alternate cache timestamp. On a successful
1928 * (positive or negative) lookup, it will contain the ticks value
1929 * that was current when the cache entry was created, unless cnp
1932 * Either both tsp and ticks have to be provided or neither of them.
1936 * - -1: A positive cache hit. vpp will contain the desired vnode.
1937 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1938 * to a forced unmount. vpp will not be modified. If the entry
1939 * is a whiteout, then the ISWHITEOUT flag will be set in
1941 * - 0: A cache miss. vpp will not be modified.
1945 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1946 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1947 * lock is not recursively acquired.
1949 static int __noinline
1950 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1951 struct timespec *tsp, int *ticksp)
1953 struct namecache *ncp;
1960 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1961 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1964 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1965 blp = HASH2BUCKETLOCK(hash);
1968 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1969 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1970 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1974 if (__predict_false(ncp == NULL)) {
1976 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
1977 counter_u64_add(nummiss, 1);
1981 if (ncp->nc_flag & NCF_NEGATIVE)
1982 goto negative_success;
1984 counter_u64_add(numposhits, 1);
1986 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1987 cache_out_ts(ncp, tsp, ticksp);
1989 vs = vget_prep(*vpp);
1991 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1999 * We don't get here with regular lookup apart from corner cases.
2001 if (__predict_true(cnp->cn_nameiop == CREATE)) {
2002 if (cnp->cn_flags & ISLASTCN) {
2003 counter_u64_add(numnegzaps, 1);
2004 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2005 if (__predict_false(error != 0)) {
2014 whiteout = (ncp->nc_flag & NCF_WHITE);
2015 cache_out_ts(ncp, tsp, ticksp);
2016 if (cache_neg_hit_prep(ncp))
2017 cache_neg_promote(ncp);
2019 cache_neg_hit_finish(ncp);
2022 cnp->cn_flags |= ISWHITEOUT;
2027 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2028 struct timespec *tsp, int *ticksp)
2030 struct namecache *ncp;
2034 bool whiteout, neg_promote;
2037 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2040 if (__predict_false(!doingcache)) {
2041 cnp->cn_flags &= ~MAKEENTRY;
2046 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2047 if (cnp->cn_namelen == 1)
2048 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2049 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2050 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2053 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2055 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2056 cache_remove_cnp(dvp, cnp);
2060 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2063 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2064 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2065 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2069 if (__predict_false(ncp == NULL)) {
2071 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2072 counter_u64_add(nummiss, 1);
2076 nc_flag = atomic_load_char(&ncp->nc_flag);
2077 if (nc_flag & NCF_NEGATIVE)
2078 goto negative_success;
2080 counter_u64_add(numposhits, 1);
2082 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2083 cache_out_ts(ncp, tsp, ticksp);
2085 if (!cache_ncp_canuse(ncp)) {
2090 vs = vget_prep_smr(*vpp);
2092 if (__predict_false(vs == VGET_NONE)) {
2096 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2103 if (cnp->cn_nameiop == CREATE) {
2104 if (cnp->cn_flags & ISLASTCN) {
2110 cache_out_ts(ncp, tsp, ticksp);
2111 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2112 neg_promote = cache_neg_hit_prep(ncp);
2113 if (!cache_ncp_canuse(ncp)) {
2114 cache_neg_hit_abort(ncp);
2120 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2123 cache_neg_hit_finish(ncp);
2127 cnp->cn_flags |= ISWHITEOUT;
2130 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2133 struct celockstate {
2137 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2138 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2141 cache_celockstate_init(struct celockstate *cel)
2144 bzero(cel, sizeof(*cel));
2148 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2151 struct mtx *vlp1, *vlp2;
2153 MPASS(cel->vlp[0] == NULL);
2154 MPASS(cel->vlp[1] == NULL);
2155 MPASS(cel->vlp[2] == NULL);
2157 MPASS(vp != NULL || dvp != NULL);
2159 vlp1 = VP2VNODELOCK(vp);
2160 vlp2 = VP2VNODELOCK(dvp);
2161 cache_sort_vnodes(&vlp1, &vlp2);
2172 cache_unlock_vnodes_cel(struct celockstate *cel)
2175 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2177 if (cel->vlp[0] != NULL)
2178 mtx_unlock(cel->vlp[0]);
2179 if (cel->vlp[1] != NULL)
2180 mtx_unlock(cel->vlp[1]);
2181 if (cel->vlp[2] != NULL)
2182 mtx_unlock(cel->vlp[2]);
2186 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2191 cache_assert_vlp_locked(cel->vlp[0]);
2192 cache_assert_vlp_locked(cel->vlp[1]);
2193 MPASS(cel->vlp[2] == NULL);
2196 vlp = VP2VNODELOCK(vp);
2199 if (vlp >= cel->vlp[1]) {
2202 if (mtx_trylock(vlp))
2204 cache_lock_vnodes_cel_3_failures++;
2205 cache_unlock_vnodes_cel(cel);
2206 if (vlp < cel->vlp[0]) {
2208 mtx_lock(cel->vlp[0]);
2209 mtx_lock(cel->vlp[1]);
2211 if (cel->vlp[0] != NULL)
2212 mtx_lock(cel->vlp[0]);
2214 mtx_lock(cel->vlp[1]);
2224 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2228 MPASS(cel->blp[0] == NULL);
2229 MPASS(cel->blp[1] == NULL);
2231 cache_sort_vnodes(&blp1, &blp2);
2242 cache_unlock_buckets_cel(struct celockstate *cel)
2245 if (cel->blp[0] != NULL)
2246 mtx_unlock(cel->blp[0]);
2247 mtx_unlock(cel->blp[1]);
2251 * Lock part of the cache affected by the insertion.
2253 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2254 * However, insertion can result in removal of an old entry. In this
2255 * case we have an additional vnode and bucketlock pair to lock.
2257 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2258 * preserving the locking order (smaller address first).
2261 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2264 struct namecache *ncp;
2265 struct mtx *blps[2];
2268 blps[0] = HASH2BUCKETLOCK(hash);
2271 cache_lock_vnodes_cel(cel, dvp, vp);
2272 if (vp == NULL || vp->v_type != VDIR)
2274 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2277 nc_flag = atomic_load_char(&ncp->nc_flag);
2278 if ((nc_flag & NCF_ISDOTDOT) == 0)
2280 MPASS(ncp->nc_dvp == vp);
2281 blps[1] = NCP2BUCKETLOCK(ncp);
2282 if ((nc_flag & NCF_NEGATIVE) != 0)
2284 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2287 * All vnodes got re-locked. Re-validate the state and if
2288 * nothing changed we are done. Otherwise restart.
2290 if (ncp == vp->v_cache_dd &&
2291 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2292 blps[1] == NCP2BUCKETLOCK(ncp) &&
2293 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2295 cache_unlock_vnodes_cel(cel);
2300 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2304 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2307 struct namecache *ncp;
2308 struct mtx *blps[2];
2311 blps[0] = HASH2BUCKETLOCK(hash);
2314 cache_lock_vnodes_cel(cel, dvp, vp);
2315 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2318 nc_flag = atomic_load_char(&ncp->nc_flag);
2319 if ((nc_flag & NCF_ISDOTDOT) == 0)
2321 MPASS(ncp->nc_dvp == dvp);
2322 blps[1] = NCP2BUCKETLOCK(ncp);
2323 if ((nc_flag & NCF_NEGATIVE) != 0)
2325 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2327 if (ncp == dvp->v_cache_dd &&
2328 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2329 blps[1] == NCP2BUCKETLOCK(ncp) &&
2330 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2332 cache_unlock_vnodes_cel(cel);
2337 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2341 cache_enter_unlock(struct celockstate *cel)
2344 cache_unlock_buckets_cel(cel);
2345 cache_unlock_vnodes_cel(cel);
2348 static void __noinline
2349 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2350 struct componentname *cnp)
2352 struct celockstate cel;
2353 struct namecache *ncp;
2357 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2359 len = cnp->cn_namelen;
2360 cache_celockstate_init(&cel);
2361 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2362 cache_enter_lock_dd(&cel, dvp, vp, hash);
2363 ncp = dvp->v_cache_dd;
2364 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2365 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2366 cache_zap_locked(ncp);
2370 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2371 cache_enter_unlock(&cel);
2377 * Add an entry to the cache.
2380 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2381 struct timespec *tsp, struct timespec *dtsp)
2383 struct celockstate cel;
2384 struct namecache *ncp, *n2, *ndd;
2385 struct namecache_ts *ncp_ts;
2386 struct nchashhead *ncpp;
2391 KASSERT(cnp->cn_namelen <= NAME_MAX,
2392 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2396 * Not everything doing this is weeded out yet.
2398 VNPASS(dvp != vp, dvp);
2400 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2401 VNPASS(dvp->v_type != VNON, dvp);
2403 VNPASS(!VN_IS_DOOMED(vp), vp);
2404 VNPASS(vp->v_type != VNON, vp);
2408 if (__predict_false(!doingcache))
2413 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2414 if (cnp->cn_namelen == 1)
2416 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2417 cache_enter_dotdot_prep(dvp, vp, cnp);
2418 flag = NCF_ISDOTDOT;
2422 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2426 cache_celockstate_init(&cel);
2431 * Calculate the hash key and setup as much of the new
2432 * namecache entry as possible before acquiring the lock.
2434 ncp->nc_flag = flag | NCF_WIP;
2437 cache_neg_init(ncp);
2440 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2441 ncp_ts->nc_time = *tsp;
2442 ncp_ts->nc_ticks = ticks;
2443 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2445 ncp_ts->nc_dotdottime = *dtsp;
2446 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2449 len = ncp->nc_nlen = cnp->cn_namelen;
2450 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2451 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2452 ncp->nc_name[len] = '\0';
2453 cache_enter_lock(&cel, dvp, vp, hash);
2456 * See if this vnode or negative entry is already in the cache
2457 * with this name. This can happen with concurrent lookups of
2458 * the same path name.
2460 ncpp = NCHHASH(hash);
2461 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2462 if (n2->nc_dvp == dvp &&
2463 n2->nc_nlen == cnp->cn_namelen &&
2464 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2465 MPASS(cache_ncp_canuse(n2));
2466 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2468 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2469 __func__, NULL, vp, cnp->cn_nameptr));
2471 KASSERT(n2->nc_vp == vp,
2472 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2473 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2475 * Entries are supposed to be immutable unless in the
2476 * process of getting destroyed. Accommodating for
2477 * changing timestamps is possible but not worth it.
2478 * This should be harmless in terms of correctness, in
2479 * the worst case resulting in an earlier expiration.
2480 * Alternatively, the found entry can be replaced
2483 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2486 KASSERT((n2->nc_flag & NCF_TS) != 0,
2488 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2489 n2_ts->nc_time = ncp_ts->nc_time;
2490 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2492 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2493 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2497 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2499 goto out_unlock_free;
2503 if (flag == NCF_ISDOTDOT) {
2505 * See if we are trying to add .. entry, but some other lookup
2506 * has populated v_cache_dd pointer already.
2508 if (dvp->v_cache_dd != NULL)
2509 goto out_unlock_free;
2510 KASSERT(vp == NULL || vp->v_type == VDIR,
2511 ("wrong vnode type %p", vp));
2512 atomic_thread_fence_rel();
2513 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2517 if (flag != NCF_ISDOTDOT) {
2519 * For this case, the cache entry maps both the
2520 * directory name in it and the name ".." for the
2521 * directory's parent.
2523 if ((ndd = vp->v_cache_dd) != NULL) {
2524 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2525 cache_zap_locked(ndd);
2529 atomic_thread_fence_rel();
2530 atomic_store_ptr(&vp->v_cache_dd, ncp);
2531 } else if (vp->v_type != VDIR) {
2532 if (vp->v_cache_dd != NULL) {
2533 atomic_store_ptr(&vp->v_cache_dd, NULL);
2538 if (flag != NCF_ISDOTDOT) {
2539 if (LIST_EMPTY(&dvp->v_cache_src)) {
2540 cache_hold_vnode(dvp);
2542 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2546 * If the entry is "negative", we place it into the
2547 * "negative" cache queue, otherwise, we place it into the
2548 * destination vnode's cache entries queue.
2551 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2552 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2555 if (cnp->cn_flags & ISWHITEOUT)
2556 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2557 cache_neg_insert(ncp);
2558 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2563 * Insert the new namecache entry into the appropriate chain
2564 * within the cache entries table.
2566 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2568 atomic_thread_fence_rel();
2570 * Mark the entry as fully constructed.
2571 * It is immutable past this point until its removal.
2573 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2575 cache_enter_unlock(&cel);
2580 cache_enter_unlock(&cel);
2586 * A variant of the above accepting flags.
2588 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2590 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2591 * happens to match and it is doing it in an inefficient manner. It was added
2592 * to accomodate NFS which runs into a case where the target for a given name
2593 * may change from under it. Note this does nothing to solve the following
2594 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2595 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2598 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2599 struct timespec *tsp, struct timespec *dtsp, int flags)
2602 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2604 if (flags & VFS_CACHE_DROPOLD)
2605 cache_remove_cnp(dvp, cnp);
2606 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2610 cache_roundup_2(u_int val)
2614 for (res = 1; res <= val; res <<= 1)
2620 static struct nchashhead *
2621 nchinittbl(u_long elements, u_long *hashmask)
2623 struct nchashhead *hashtbl;
2626 hashsize = cache_roundup_2(elements) / 2;
2628 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2629 for (i = 0; i < hashsize; i++)
2630 CK_SLIST_INIT(&hashtbl[i]);
2631 *hashmask = hashsize - 1;
2636 ncfreetbl(struct nchashhead *hashtbl)
2639 free(hashtbl, M_VFSCACHE);
2643 * Name cache initialization, from vfs_init() when we are booting
2646 nchinit(void *dummy __unused)
2650 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2651 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2652 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2653 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2654 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2655 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2656 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2657 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2659 VFS_SMR_ZONE_SET(cache_zone_small);
2660 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2661 VFS_SMR_ZONE_SET(cache_zone_large);
2662 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2664 ncsize = desiredvnodes * ncsizefactor;
2665 cache_recalc_neg_min(ncnegminpct);
2666 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2667 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2668 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2670 if (ncbuckethash > nchash)
2671 ncbuckethash = nchash;
2672 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2674 for (i = 0; i < numbucketlocks; i++)
2675 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2676 ncvnodehash = ncbuckethash;
2677 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2679 for (i = 0; i < numvnodelocks; i++)
2680 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2682 for (i = 0; i < numneglists; i++) {
2683 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2684 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2685 TAILQ_INIT(&neglists[i].nl_list);
2686 TAILQ_INIT(&neglists[i].nl_hotlist);
2689 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2692 cache_vnode_init(struct vnode *vp)
2695 LIST_INIT(&vp->v_cache_src);
2696 TAILQ_INIT(&vp->v_cache_dst);
2697 vp->v_cache_dd = NULL;
2702 * Induce transient cache misses for lockless operation in cache_lookup() by
2703 * using a temporary hash table.
2705 * This will force a fs lookup.
2707 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2708 * to observe all CPUs not performing the lookup.
2711 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2714 MPASS(temphash < nchash);
2716 * Change the size. The new size is smaller and can safely be used
2717 * against the existing table. All lookups which now hash wrong will
2718 * result in a cache miss, which all callers are supposed to know how
2721 atomic_store_long(&nchash, temphash);
2722 atomic_thread_fence_rel();
2723 vfs_smr_synchronize();
2725 * At this point everyone sees the updated hash value, but they still
2726 * see the old table.
2728 atomic_store_ptr(&nchashtbl, temptbl);
2729 atomic_thread_fence_rel();
2730 vfs_smr_synchronize();
2732 * At this point everyone sees the updated table pointer and size pair.
2737 * Set the new hash table.
2739 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2740 * lockless operation in cache_lookup().
2743 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2746 MPASS(nchash < new_hash);
2748 * Change the pointer first. This wont result in out of bounds access
2749 * since the temporary table is guaranteed to be smaller.
2751 atomic_store_ptr(&nchashtbl, new_tbl);
2752 atomic_thread_fence_rel();
2753 vfs_smr_synchronize();
2755 * At this point everyone sees the updated pointer value, but they
2756 * still see the old size.
2758 atomic_store_long(&nchash, new_hash);
2759 atomic_thread_fence_rel();
2760 vfs_smr_synchronize();
2762 * At this point everyone sees the updated table pointer and size pair.
2767 cache_changesize(u_long newmaxvnodes)
2769 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2770 u_long new_nchash, old_nchash, temphash;
2771 struct namecache *ncp;
2776 newncsize = newmaxvnodes * ncsizefactor;
2777 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2778 if (newmaxvnodes < numbucketlocks)
2779 newmaxvnodes = numbucketlocks;
2781 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2782 /* If same hash table size, nothing to do */
2783 if (nchash == new_nchash) {
2784 ncfreetbl(new_nchashtbl);
2788 temptbl = nchinittbl(1, &temphash);
2791 * Move everything from the old hash table to the new table.
2792 * None of the namecache entries in the table can be removed
2793 * because to do so, they have to be removed from the hash table.
2795 cache_lock_all_vnodes();
2796 cache_lock_all_buckets();
2797 old_nchashtbl = nchashtbl;
2798 old_nchash = nchash;
2799 cache_changesize_set_temp(temptbl, temphash);
2800 for (i = 0; i <= old_nchash; i++) {
2801 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2802 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2804 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2805 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2809 cache_recalc_neg_min(ncnegminpct);
2810 cache_changesize_set_new(new_nchashtbl, new_nchash);
2811 cache_unlock_all_buckets();
2812 cache_unlock_all_vnodes();
2813 ncfreetbl(old_nchashtbl);
2818 * Remove all entries from and to a particular vnode.
2821 cache_purge_impl(struct vnode *vp)
2823 struct cache_freebatch batch;
2824 struct namecache *ncp;
2825 struct mtx *vlp, *vlp2;
2828 vlp = VP2VNODELOCK(vp);
2832 while (!LIST_EMPTY(&vp->v_cache_src)) {
2833 ncp = LIST_FIRST(&vp->v_cache_src);
2834 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2836 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2838 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2839 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2840 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2842 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2844 ncp = vp->v_cache_dd;
2846 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2847 ("lost dotdot link"));
2848 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2850 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2852 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2856 cache_free_batch(&batch);
2860 * Opportunistic check to see if there is anything to do.
2863 cache_has_entries(struct vnode *vp)
2866 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2867 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2873 cache_purge(struct vnode *vp)
2876 SDT_PROBE1(vfs, namecache, purge, done, vp);
2877 if (!cache_has_entries(vp))
2879 cache_purge_impl(vp);
2883 * Only to be used by vgone.
2886 cache_purge_vgone(struct vnode *vp)
2890 VNPASS(VN_IS_DOOMED(vp), vp);
2891 if (cache_has_entries(vp)) {
2892 cache_purge_impl(vp);
2897 * Serialize against a potential thread doing cache_purge.
2899 vlp = VP2VNODELOCK(vp);
2900 mtx_wait_unlocked(vlp);
2901 if (cache_has_entries(vp)) {
2902 cache_purge_impl(vp);
2909 * Remove all negative entries for a particular directory vnode.
2912 cache_purge_negative(struct vnode *vp)
2914 struct cache_freebatch batch;
2915 struct namecache *ncp, *nnp;
2918 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2919 if (LIST_EMPTY(&vp->v_cache_src))
2922 vlp = VP2VNODELOCK(vp);
2924 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2925 if (!(ncp->nc_flag & NCF_NEGATIVE))
2927 cache_zap_negative_locked_vnode_kl(ncp, vp);
2928 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2931 cache_free_batch(&batch);
2935 * Entry points for modifying VOP operations.
2938 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2939 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2942 ASSERT_VOP_IN_SEQC(fdvp);
2943 ASSERT_VOP_IN_SEQC(fvp);
2944 ASSERT_VOP_IN_SEQC(tdvp);
2946 ASSERT_VOP_IN_SEQC(tvp);
2951 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2952 ("%s: lingering negative entry", __func__));
2954 cache_remove_cnp(tdvp, tcnp);
2960 * Historically renaming was always purging all revelang entries,
2961 * but that's quite wasteful. In particular turns out that in many cases
2962 * the target file is immediately accessed after rename, inducing a cache
2965 * Recode this to reduce relocking and reuse the existing entry (if any)
2966 * instead of just removing it above and allocating a new one here.
2968 if (cache_rename_add) {
2969 cache_enter(tdvp, fvp, tcnp);
2974 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2977 ASSERT_VOP_IN_SEQC(dvp);
2978 ASSERT_VOP_IN_SEQC(vp);
2984 * Validate that if an entry exists it matches.
2987 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2989 struct namecache *ncp;
2993 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2994 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2996 blp = HASH2BUCKETLOCK(hash);
2998 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2999 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3000 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
3001 if (ncp->nc_vp != vp)
3002 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
3003 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3011 * Flush all entries referencing a particular filesystem.
3014 cache_purgevfs(struct mount *mp)
3016 struct vnode *vp, *mvp;
3017 size_t visited, purged;
3019 visited = purged = 0;
3021 * Somewhat wasteful iteration over all vnodes. Would be better to
3022 * support filtering and avoid the interlock to begin with.
3024 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3026 if (!cache_has_entries(vp)) {
3037 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3041 * Perform canonical checks and cache lookup and pass on to filesystem
3042 * through the vop_cachedlookup only if needed.
3046 vfs_cache_lookup(struct vop_lookup_args *ap)
3050 struct vnode **vpp = ap->a_vpp;
3051 struct componentname *cnp = ap->a_cnp;
3052 int flags = cnp->cn_flags;
3057 if (dvp->v_type != VDIR)
3060 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3061 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3064 error = vn_dir_check_exec(dvp, cnp);
3068 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3070 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3076 /* Implementation of the getcwd syscall. */
3078 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3084 buflen = uap->buflen;
3085 if (__predict_false(buflen < 2))
3087 if (buflen > MAXPATHLEN)
3088 buflen = MAXPATHLEN;
3090 buf = uma_zalloc(namei_zone, M_WAITOK);
3091 error = vn_getcwd(buf, &retbuf, &buflen);
3093 error = copyout(retbuf, uap->buf, buflen);
3094 uma_zfree(namei_zone, buf);
3099 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3105 pwd = pwd_get_smr();
3106 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3108 VFS_SMR_ASSERT_NOT_ENTERED();
3110 pwd = pwd_hold(curthread);
3111 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3117 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3124 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3125 size_t size, int flags, enum uio_seg pathseg)
3127 struct nameidata nd;
3128 char *retbuf, *freebuf;
3133 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
3134 pathseg, path, fd, &cap_fstat_rights, td);
3135 if ((error = namei(&nd)) != 0)
3137 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
3139 error = copyout(retbuf, buf, size);
3140 free(freebuf, M_TEMP);
3147 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3150 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3151 uap->flags, UIO_USERSPACE));
3155 * Retrieve the full filesystem path that correspond to a vnode from the name
3156 * cache (if available)
3159 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3166 if (__predict_false(vp == NULL))
3169 buflen = MAXPATHLEN;
3170 buf = malloc(buflen, M_TEMP, M_WAITOK);
3172 pwd = pwd_get_smr();
3173 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3174 VFS_SMR_ASSERT_NOT_ENTERED();
3176 pwd = pwd_hold(curthread);
3177 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3188 * This function is similar to vn_fullpath, but it attempts to lookup the
3189 * pathname relative to the global root mount point. This is required for the
3190 * auditing sub-system, as audited pathnames must be absolute, relative to the
3191 * global root mount point.
3194 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3200 if (__predict_false(vp == NULL))
3202 buflen = MAXPATHLEN;
3203 buf = malloc(buflen, M_TEMP, M_WAITOK);
3205 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3206 VFS_SMR_ASSERT_NOT_ENTERED();
3208 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3217 static struct namecache *
3218 vn_dd_from_dst(struct vnode *vp)
3220 struct namecache *ncp;
3222 cache_assert_vnode_locked(vp);
3223 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3224 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3231 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3234 struct namecache *ncp;
3238 vlp = VP2VNODELOCK(*vp);
3240 ncp = (*vp)->v_cache_dd;
3241 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3242 KASSERT(ncp == vn_dd_from_dst(*vp),
3243 ("%s: mismatch for dd entry (%p != %p)", __func__,
3244 ncp, vn_dd_from_dst(*vp)));
3246 ncp = vn_dd_from_dst(*vp);
3249 if (*buflen < ncp->nc_nlen) {
3252 counter_u64_add(numfullpathfail4, 1);
3254 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3258 *buflen -= ncp->nc_nlen;
3259 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3260 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3269 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3272 vn_lock(*vp, LK_SHARED | LK_RETRY);
3273 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3276 counter_u64_add(numfullpathfail2, 1);
3277 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3282 if (VN_IS_DOOMED(dvp)) {
3283 /* forced unmount */
3286 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3290 * *vp has its use count incremented still.
3297 * Resolve a directory to a pathname.
3299 * The name of the directory can always be found in the namecache or fetched
3300 * from the filesystem. There is also guaranteed to be only one parent, meaning
3301 * we can just follow vnodes up until we find the root.
3303 * The vnode must be referenced.
3306 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3307 size_t *len, size_t addend)
3309 #ifdef KDTRACE_HOOKS
3310 struct vnode *startvp = vp;
3315 bool slash_prefixed;
3317 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3318 VNPASS(vp->v_usecount > 0, vp);
3322 slash_prefixed = true;
3327 slash_prefixed = false;
3332 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3333 counter_u64_add(numfullpathcalls, 1);
3334 while (vp != rdir && vp != rootvnode) {
3336 * The vp vnode must be already fully constructed,
3337 * since it is either found in namecache or obtained
3338 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3339 * without obtaining the vnode lock.
3341 if ((vp->v_vflag & VV_ROOT) != 0) {
3342 vn_lock(vp, LK_RETRY | LK_SHARED);
3345 * With the vnode locked, check for races with
3346 * unmount, forced or not. Note that we
3347 * already verified that vp is not equal to
3348 * the root vnode, which means that
3349 * mnt_vnodecovered can be NULL only for the
3352 if (VN_IS_DOOMED(vp) ||
3353 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3354 vp1->v_mountedhere != vp->v_mount) {
3357 SDT_PROBE3(vfs, namecache, fullpath, return,
3367 if (vp->v_type != VDIR) {
3369 counter_u64_add(numfullpathfail1, 1);
3371 SDT_PROBE3(vfs, namecache, fullpath, return,
3375 error = vn_vptocnp(&vp, buf, &buflen);
3381 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3385 buf[--buflen] = '/';
3386 slash_prefixed = true;
3390 if (!slash_prefixed) {
3393 counter_u64_add(numfullpathfail4, 1);
3394 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3398 buf[--buflen] = '/';
3400 counter_u64_add(numfullpathfound, 1);
3403 *retbuf = buf + buflen;
3404 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3411 * Resolve an arbitrary vnode to a pathname.
3414 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3415 * resolve to a different path than the one used to find it
3416 * - namecache is not mandatory, meaning names are not guaranteed to be added
3417 * (in which case resolving fails)
3419 static void __inline
3420 cache_rev_failed_impl(int *reason, int line)
3425 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3428 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3429 char **retbuf, size_t *buflen, size_t addend)
3431 #ifdef KDTRACE_HOOKS
3432 struct vnode *startvp = vp;
3436 struct namecache *ncp;
3440 #ifdef KDTRACE_HOOKS
3443 seqc_t vp_seqc, tvp_seqc;
3446 VFS_SMR_ASSERT_ENTERED();
3448 if (!cache_fast_revlookup) {
3453 orig_buflen = *buflen;
3456 MPASS(*buflen >= 2);
3458 buf[*buflen] = '\0';
3461 if (vp == rdir || vp == rootvnode) {
3469 #ifdef KDTRACE_HOOKS
3473 ncp = NULL; /* for sdt probe down below */
3474 vp_seqc = vn_seqc_read_any(vp);
3475 if (seqc_in_modify(vp_seqc)) {
3476 cache_rev_failed(&reason);
3481 #ifdef KDTRACE_HOOKS
3484 if ((vp->v_vflag & VV_ROOT) != 0) {
3485 mp = atomic_load_ptr(&vp->v_mount);
3487 cache_rev_failed(&reason);
3490 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3491 tvp_seqc = vn_seqc_read_any(tvp);
3492 if (seqc_in_modify(tvp_seqc)) {
3493 cache_rev_failed(&reason);
3496 if (!vn_seqc_consistent(vp, vp_seqc)) {
3497 cache_rev_failed(&reason);
3504 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3506 cache_rev_failed(&reason);
3509 nc_flag = atomic_load_char(&ncp->nc_flag);
3510 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3511 cache_rev_failed(&reason);
3514 if (ncp->nc_nlen >= *buflen) {
3515 cache_rev_failed(&reason);
3519 *buflen -= ncp->nc_nlen;
3520 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3524 tvp_seqc = vn_seqc_read_any(tvp);
3525 if (seqc_in_modify(tvp_seqc)) {
3526 cache_rev_failed(&reason);
3529 if (!vn_seqc_consistent(vp, vp_seqc)) {
3530 cache_rev_failed(&reason);
3534 * Acquire fence provided by vn_seqc_read_any above.
3536 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3537 cache_rev_failed(&reason);
3540 if (!cache_ncp_canuse(ncp)) {
3541 cache_rev_failed(&reason);
3546 if (vp == rdir || vp == rootvnode)
3551 *retbuf = buf + *buflen;
3552 *buflen = orig_buflen - *buflen + addend;
3553 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3557 *buflen = orig_buflen;
3558 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3564 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3567 size_t orig_buflen, addend;
3573 orig_buflen = *buflen;
3577 if (vp->v_type != VDIR) {
3579 buf[*buflen] = '\0';
3580 error = vn_vptocnp(&vp, buf, buflen);
3589 addend = orig_buflen - *buflen;
3592 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3596 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3598 * Since the namecache does not track hardlinks, the caller is expected to first
3599 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3601 * Then we have 2 cases:
3602 * - if the found vnode is a directory, the path can be constructed just by
3603 * following names up the chain
3604 * - otherwise we populate the buffer with the saved name and start resolving
3608 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3613 struct componentname *cnp;
3621 if (*buflen > MAXPATHLEN)
3622 *buflen = MAXPATHLEN;
3624 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3629 * Check for VBAD to work around the vp_crossmp bug in lookup().
3631 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3632 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3633 * If the type is VDIR (like in this very case) we can skip looking
3634 * at ni_dvp in the first place. However, since vnodes get passed here
3635 * unlocked the target may transition to doomed state (type == VBAD)
3636 * before we get to evaluate the condition. If this happens, we will
3637 * populate part of the buffer and descend to vn_fullpath_dir with
3638 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3640 * This should be atomic_load(&vp->v_type) but it is illegal to take
3641 * an address of a bit field, even if said field is sized to char.
3642 * Work around the problem by reading the value into a full-sized enum
3643 * and then re-reading it with atomic_load which will still prevent
3644 * the compiler from re-reading down the road.
3647 type = atomic_load_int(&type);
3654 addend = cnp->cn_namelen + 2;
3655 if (*buflen < addend) {
3660 tmpbuf = buf + *buflen;
3662 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3663 tmpbuf[addend - 1] = '\0';
3668 pwd = pwd_get_smr();
3669 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3671 VFS_SMR_ASSERT_NOT_ENTERED();
3673 pwd = pwd_hold(curthread);
3675 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3691 vn_dir_dd_ino(struct vnode *vp)
3693 struct namecache *ncp;
3698 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3699 vlp = VP2VNODELOCK(vp);
3701 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3702 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3705 vs = vget_prep(ddvp);
3707 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3716 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3718 struct namecache *ncp;
3722 vlp = VP2VNODELOCK(vp);
3724 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3725 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3731 l = min(ncp->nc_nlen, buflen - 1);
3732 memcpy(buf, ncp->nc_name, l);
3739 * This function updates path string to vnode's full global path
3740 * and checks the size of the new path string against the pathlen argument.
3742 * Requires a locked, referenced vnode.
3743 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3745 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3746 * because it falls back to the ".." lookup if the namecache lookup fails.
3749 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3752 struct nameidata nd;
3757 ASSERT_VOP_ELOCKED(vp, __func__);
3759 /* Construct global filesystem path from vp. */
3761 error = vn_fullpath_global(vp, &rpath, &fbuf);
3768 if (strlen(rpath) >= pathlen) {
3770 error = ENAMETOOLONG;
3775 * Re-lookup the vnode by path to detect a possible rename.
3776 * As a side effect, the vnode is relocked.
3777 * If vnode was renamed, return ENOENT.
3779 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3780 UIO_SYSSPACE, path, td);
3786 NDFREE(&nd, NDF_ONLY_PNBUF);
3790 strcpy(path, rpath);
3803 db_print_vpath(struct vnode *vp)
3806 while (vp != NULL) {
3807 db_printf("%p: ", vp);
3808 if (vp == rootvnode) {
3812 if (vp->v_vflag & VV_ROOT) {
3813 db_printf("<mount point>");
3814 vp = vp->v_mount->mnt_vnodecovered;
3816 struct namecache *ncp;
3820 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3823 for (i = 0; i < ncp->nc_nlen; i++)
3824 db_printf("%c", *ncn++);
3837 DB_SHOW_COMMAND(vpath, db_show_vpath)
3842 db_printf("usage: show vpath <struct vnode *>\n");
3846 vp = (struct vnode *)addr;
3852 static int cache_fast_lookup = 1;
3853 static char __read_frequently cache_fast_lookup_enabled = true;
3855 #define CACHE_FPL_FAILED -2020
3858 cache_fast_lookup_enabled_recalc(void)
3864 mac_on = mac_vnode_check_lookup_enabled();
3865 mac_on |= mac_vnode_check_readlink_enabled();
3870 lookup_flag = atomic_load_int(&cache_fast_lookup);
3871 if (lookup_flag && !mac_on) {
3872 atomic_store_char(&cache_fast_lookup_enabled, true);
3874 atomic_store_char(&cache_fast_lookup_enabled, false);
3879 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
3883 old = atomic_load_int(&cache_fast_lookup);
3884 error = sysctl_handle_int(oidp, arg1, arg2, req);
3885 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
3886 cache_fast_lookup_enabled_recalc();
3889 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
3890 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
3893 * Components of nameidata (or objects it can point to) which may
3894 * need restoring in case fast path lookup fails.
3896 struct nameidata_outer {
3901 struct nameidata_saved {
3909 struct cache_fpl_debug {
3915 struct nameidata *ndp;
3916 struct componentname *cnp;
3923 struct nameidata_saved snd;
3924 struct nameidata_outer snd_outer;
3926 enum cache_fpl_status status:8;
3932 struct cache_fpl_debug debug;
3936 static bool cache_fplookup_mp_supported(struct mount *mp);
3937 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
3938 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
3939 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
3940 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
3941 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
3942 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
3943 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
3944 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
3945 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
3948 cache_fpl_cleanup_cnp(struct componentname *cnp)
3951 uma_zfree(namei_zone, cnp->cn_pnbuf);
3953 cnp->cn_pnbuf = NULL;
3954 cnp->cn_nameptr = NULL;
3958 static struct vnode *
3959 cache_fpl_handle_root(struct cache_fpl *fpl)
3961 struct nameidata *ndp;
3962 struct componentname *cnp;
3967 MPASS(*(cnp->cn_nameptr) == '/');
3969 cache_fpl_pathlen_dec(fpl);
3971 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
3974 cache_fpl_pathlen_dec(fpl);
3975 } while (*(cnp->cn_nameptr) == '/');
3978 return (ndp->ni_rootdir);
3982 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
3985 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
3986 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
3990 cache_fpl_checkpoint(struct cache_fpl *fpl)
3994 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3995 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4000 cache_fpl_restore_partial(struct cache_fpl *fpl)
4003 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4005 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4010 cache_fpl_restore_abort(struct cache_fpl *fpl)
4013 cache_fpl_restore_partial(fpl);
4015 * It is 0 on entry by API contract.
4017 fpl->ndp->ni_resflags = 0;
4018 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4019 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4023 #define cache_fpl_smr_assert_entered(fpl) ({ \
4024 struct cache_fpl *_fpl = (fpl); \
4025 MPASS(_fpl->in_smr == true); \
4026 VFS_SMR_ASSERT_ENTERED(); \
4028 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4029 struct cache_fpl *_fpl = (fpl); \
4030 MPASS(_fpl->in_smr == false); \
4031 VFS_SMR_ASSERT_NOT_ENTERED(); \
4034 cache_fpl_assert_status(struct cache_fpl *fpl)
4037 switch (fpl->status) {
4038 case CACHE_FPL_STATUS_UNSET:
4039 __assert_unreachable();
4041 case CACHE_FPL_STATUS_DESTROYED:
4042 case CACHE_FPL_STATUS_ABORTED:
4043 case CACHE_FPL_STATUS_PARTIAL:
4044 case CACHE_FPL_STATUS_HANDLED:
4049 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4050 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4051 #define cache_fpl_assert_status(fpl) do { } while (0)
4054 #define cache_fpl_smr_enter_initial(fpl) ({ \
4055 struct cache_fpl *_fpl = (fpl); \
4057 _fpl->in_smr = true; \
4060 #define cache_fpl_smr_enter(fpl) ({ \
4061 struct cache_fpl *_fpl = (fpl); \
4062 MPASS(_fpl->in_smr == false); \
4064 _fpl->in_smr = true; \
4067 #define cache_fpl_smr_exit(fpl) ({ \
4068 struct cache_fpl *_fpl = (fpl); \
4069 MPASS(_fpl->in_smr == true); \
4071 _fpl->in_smr = false; \
4075 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4078 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4079 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4080 ("%s: converting to abort from %d at %d, set at %d\n",
4081 __func__, fpl->status, line, fpl->line));
4083 cache_fpl_smr_assert_not_entered(fpl);
4084 fpl->status = CACHE_FPL_STATUS_ABORTED;
4086 return (CACHE_FPL_FAILED);
4089 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4091 static int __noinline
4092 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4094 struct nameidata *ndp;
4095 struct componentname *cnp;
4100 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4101 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4102 ("%s: converting to abort from %d at %d, set at %d\n",
4103 __func__, fpl->status, line, fpl->line));
4105 fpl->status = CACHE_FPL_STATUS_ABORTED;
4108 cache_fpl_smr_exit(fpl);
4109 cache_fpl_restore_abort(fpl);
4111 * Resolving symlinks overwrites data passed by the caller.
4114 if (ndp->ni_loopcnt > 0) {
4115 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4116 cache_fpl_cleanup_cnp(cnp);
4118 return (CACHE_FPL_FAILED);
4121 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4123 static int __noinline
4124 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4127 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4128 ("%s: setting to partial at %d, but already set to %d at %d\n",
4129 __func__, line, fpl->status, fpl->line));
4130 cache_fpl_smr_assert_entered(fpl);
4131 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4133 return (cache_fplookup_partial_setup(fpl));
4136 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4139 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4142 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4143 ("%s: setting to handled at %d, but already set to %d at %d\n",
4144 __func__, line, fpl->status, fpl->line));
4145 cache_fpl_smr_assert_not_entered(fpl);
4146 fpl->status = CACHE_FPL_STATUS_HANDLED;
4151 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4154 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4157 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4158 ("%s: setting to handled at %d, but already set to %d at %d\n",
4159 __func__, line, fpl->status, fpl->line));
4161 MPASS(error != CACHE_FPL_FAILED);
4162 cache_fpl_smr_assert_not_entered(fpl);
4163 fpl->status = CACHE_FPL_STATUS_HANDLED;
4167 fpl->savename = false;
4171 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4174 cache_fpl_terminated(struct cache_fpl *fpl)
4177 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4180 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4181 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4182 FAILIFEXISTS | FOLLOW | LOCKSHARED | SAVENAME | SAVESTART | WILLBEDIR | \
4183 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
4185 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4186 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4188 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4189 "supported and internal flags overlap");
4192 cache_fpl_islastcn(struct nameidata *ndp)
4195 return (*ndp->ni_next == 0);
4199 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4202 return (*(fpl->nulchar - 1) == '/');
4206 cache_fpl_isdotdot(struct componentname *cnp)
4209 if (cnp->cn_namelen == 2 &&
4210 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4216 cache_can_fplookup(struct cache_fpl *fpl)
4218 struct nameidata *ndp;
4219 struct componentname *cnp;
4224 td = cnp->cn_thread;
4226 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4227 cache_fpl_aborted_early(fpl);
4230 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4231 cache_fpl_aborted_early(fpl);
4234 if (IN_CAPABILITY_MODE(td)) {
4235 cache_fpl_aborted_early(fpl);
4238 if (AUDITING_TD(td)) {
4239 cache_fpl_aborted_early(fpl);
4242 if (ndp->ni_startdir != NULL) {
4243 cache_fpl_aborted_early(fpl);
4250 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4252 struct nameidata *ndp;
4257 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4258 if (__predict_false(error != 0)) {
4259 return (cache_fpl_aborted(fpl));
4261 fpl->fsearch = fsearch;
4265 static int __noinline
4266 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4269 struct componentname *cnp;
4275 cache_fpl_smr_exit(fpl);
4276 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4277 return (cache_fpl_handled_error(fpl, ENOENT));
4279 return (cache_fpl_aborted(fpl));
4283 * The target vnode is not supported, prepare for the slow path to take over.
4285 static int __noinline
4286 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4288 struct nameidata *ndp;
4289 struct componentname *cnp;
4299 dvp_seqc = fpl->dvp_seqc;
4301 if (!pwd_hold_smr(pwd)) {
4302 return (cache_fpl_aborted(fpl));
4306 * Note that seqc is checked before the vnode is locked, so by
4307 * the time regular lookup gets to it it may have moved.
4309 * Ultimately this does not affect correctness, any lookup errors
4310 * are userspace racing with itself. It is guaranteed that any
4311 * path which ultimately gets found could also have been found
4312 * by regular lookup going all the way in absence of concurrent
4315 dvs = vget_prep_smr(dvp);
4316 cache_fpl_smr_exit(fpl);
4317 if (__predict_false(dvs == VGET_NONE)) {
4319 return (cache_fpl_aborted(fpl));
4322 vget_finish_ref(dvp, dvs);
4323 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4326 return (cache_fpl_aborted(fpl));
4329 cache_fpl_restore_partial(fpl);
4331 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4332 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4333 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4337 ndp->ni_startdir = dvp;
4338 cnp->cn_flags |= MAKEENTRY;
4339 if (cache_fpl_islastcn(ndp))
4340 cnp->cn_flags |= ISLASTCN;
4341 if (cache_fpl_isdotdot(cnp))
4342 cnp->cn_flags |= ISDOTDOT;
4345 * Skip potential extra slashes parsing did not take care of.
4346 * cache_fplookup_skip_slashes explains the mechanism.
4348 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4351 cache_fpl_pathlen_dec(fpl);
4352 } while (*(cnp->cn_nameptr) == '/');
4355 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4357 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4358 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4359 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4360 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4367 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4369 struct componentname *cnp;
4376 tvp_seqc = fpl->tvp_seqc;
4378 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4379 lkflags = LK_SHARED;
4380 if ((cnp->cn_flags & LOCKSHARED) == 0)
4381 lkflags = LK_EXCLUSIVE;
4382 error = vget_finish(tvp, lkflags, tvs);
4383 if (__predict_false(error != 0)) {
4384 return (cache_fpl_aborted(fpl));
4387 vget_finish_ref(tvp, tvs);
4390 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4391 if ((cnp->cn_flags & LOCKLEAF) != 0)
4395 return (cache_fpl_aborted(fpl));
4398 return (cache_fpl_handled(fpl));
4402 * They want to possibly modify the state of the namecache.
4404 static int __noinline
4405 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4407 struct nameidata *ndp;
4408 struct componentname *cnp;
4410 struct vnode *dvp, *tvp;
4419 dvp_seqc = fpl->dvp_seqc;
4421 MPASS(*(cnp->cn_nameptr) != '/');
4422 MPASS(cache_fpl_islastcn(ndp));
4423 if ((cnp->cn_flags & LOCKPARENT) == 0)
4424 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4425 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4426 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4427 cnp->cn_nameiop == RENAME);
4428 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4429 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4431 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4432 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4436 * Regular lookup nulifies the slash, which we don't do here.
4437 * Don't take chances with filesystem routines seeing it for
4440 if (cache_fpl_istrailingslash(fpl)) {
4441 return (cache_fpl_partial(fpl));
4444 mp = atomic_load_ptr(&dvp->v_mount);
4445 if (__predict_false(mp == NULL)) {
4446 return (cache_fpl_aborted(fpl));
4449 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4450 cache_fpl_smr_exit(fpl);
4452 * Original code keeps not checking for CREATE which
4453 * might be a bug. For now let the old lookup decide.
4455 if (cnp->cn_nameiop == CREATE) {
4456 return (cache_fpl_aborted(fpl));
4458 return (cache_fpl_handled_error(fpl, EROFS));
4461 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4462 cache_fpl_smr_exit(fpl);
4463 return (cache_fpl_handled_error(fpl, EEXIST));
4467 * Secure access to dvp; check cache_fplookup_partial_setup for
4470 * XXX At least UFS requires its lookup routine to be called for
4471 * the last path component, which leads to some level of complication
4473 * - the target routine always locks the target vnode, but our caller
4474 * may not need it locked
4475 * - some of the VOP machinery asserts that the parent is locked, which
4476 * once more may be not required
4478 * TODO: add a flag for filesystems which don't need this.
4480 dvs = vget_prep_smr(dvp);
4481 cache_fpl_smr_exit(fpl);
4482 if (__predict_false(dvs == VGET_NONE)) {
4483 return (cache_fpl_aborted(fpl));
4486 vget_finish_ref(dvp, dvs);
4487 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4489 return (cache_fpl_aborted(fpl));
4492 error = vn_lock(dvp, LK_EXCLUSIVE);
4493 if (__predict_false(error != 0)) {
4495 return (cache_fpl_aborted(fpl));
4499 cnp->cn_flags |= ISLASTCN;
4501 cnp->cn_flags |= MAKEENTRY;
4502 if (cache_fpl_isdotdot(cnp))
4503 cnp->cn_flags |= ISDOTDOT;
4504 cnp->cn_lkflags = LK_EXCLUSIVE;
4505 error = VOP_LOOKUP(dvp, &tvp, cnp);
4513 return (cache_fpl_handled_error(fpl, error));
4516 return (cache_fpl_aborted(fpl));
4520 fpl->savename = (cnp->cn_flags & SAVENAME) != 0;
4523 if ((cnp->cn_flags & SAVESTART) != 0) {
4524 ndp->ni_startdir = dvp;
4525 vrefact(ndp->ni_startdir);
4526 cnp->cn_flags |= SAVENAME;
4527 fpl->savename = true;
4529 MPASS(error == EJUSTRETURN);
4530 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4533 return (cache_fpl_handled(fpl));
4537 * There are very hairy corner cases concerning various flag combinations
4538 * and locking state. In particular here we only hold one lock instead of
4541 * Skip the complexity as it is of no significance for normal workloads.
4543 if (__predict_false(tvp == dvp)) {
4546 return (cache_fpl_aborted(fpl));
4550 * If they want the symlink itself we are fine, but if they want to
4551 * follow it regular lookup has to be engaged.
4553 if (tvp->v_type == VLNK) {
4554 if ((cnp->cn_flags & FOLLOW) != 0) {
4557 return (cache_fpl_aborted(fpl));
4562 * Since we expect this to be the terminal vnode it should almost never
4565 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4568 return (cache_fpl_aborted(fpl));
4571 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4574 return (cache_fpl_handled_error(fpl, EEXIST));
4577 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4581 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4585 if ((cnp->cn_flags & SAVESTART) != 0) {
4586 ndp->ni_startdir = dvp;
4587 vrefact(ndp->ni_startdir);
4588 cnp->cn_flags |= SAVENAME;
4589 fpl->savename = true;
4592 return (cache_fpl_handled(fpl));
4595 static int __noinline
4596 cache_fplookup_modifying(struct cache_fpl *fpl)
4598 struct nameidata *ndp;
4602 if (!cache_fpl_islastcn(ndp)) {
4603 return (cache_fpl_partial(fpl));
4605 return (cache_fplookup_final_modifying(fpl));
4608 static int __noinline
4609 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4611 struct componentname *cnp;
4612 enum vgetstate dvs, tvs;
4613 struct vnode *dvp, *tvp;
4619 dvp_seqc = fpl->dvp_seqc;
4622 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4625 * This is less efficient than it can be for simplicity.
4627 dvs = vget_prep_smr(dvp);
4628 if (__predict_false(dvs == VGET_NONE)) {
4629 return (cache_fpl_aborted(fpl));
4631 tvs = vget_prep_smr(tvp);
4632 if (__predict_false(tvs == VGET_NONE)) {
4633 cache_fpl_smr_exit(fpl);
4634 vget_abort(dvp, dvs);
4635 return (cache_fpl_aborted(fpl));
4638 cache_fpl_smr_exit(fpl);
4640 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4641 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4642 if (__predict_false(error != 0)) {
4643 vget_abort(tvp, tvs);
4644 return (cache_fpl_aborted(fpl));
4647 vget_finish_ref(dvp, dvs);
4650 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4651 vget_abort(tvp, tvs);
4652 if ((cnp->cn_flags & LOCKPARENT) != 0)
4656 return (cache_fpl_aborted(fpl));
4659 error = cache_fplookup_final_child(fpl, tvs);
4660 if (__predict_false(error != 0)) {
4661 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4662 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4663 if ((cnp->cn_flags & LOCKPARENT) != 0)
4670 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4675 cache_fplookup_final(struct cache_fpl *fpl)
4677 struct componentname *cnp;
4679 struct vnode *dvp, *tvp;
4684 dvp_seqc = fpl->dvp_seqc;
4687 MPASS(*(cnp->cn_nameptr) != '/');
4689 if (cnp->cn_nameiop != LOOKUP) {
4690 return (cache_fplookup_final_modifying(fpl));
4693 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4694 return (cache_fplookup_final_withparent(fpl));
4696 tvs = vget_prep_smr(tvp);
4697 if (__predict_false(tvs == VGET_NONE)) {
4698 return (cache_fpl_partial(fpl));
4701 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4702 cache_fpl_smr_exit(fpl);
4703 vget_abort(tvp, tvs);
4704 return (cache_fpl_aborted(fpl));
4707 cache_fpl_smr_exit(fpl);
4708 return (cache_fplookup_final_child(fpl, tvs));
4712 * Comment from locked lookup:
4713 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4714 * directory, e.g. like "/." or ".".
4716 static int __noinline
4717 cache_fplookup_degenerate(struct cache_fpl *fpl)
4719 struct componentname *cnp;
4727 fpl->tvp = fpl->dvp;
4728 fpl->tvp_seqc = fpl->dvp_seqc;
4734 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4736 ("%s: encountered non-slash; string [%s]\n", __func__,
4741 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4742 cache_fpl_smr_exit(fpl);
4743 return (cache_fpl_handled_error(fpl, EISDIR));
4746 MPASS((cnp->cn_flags & SAVESTART) == 0);
4748 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4749 return (cache_fplookup_final_withparent(fpl));
4752 dvs = vget_prep_smr(dvp);
4753 cache_fpl_smr_exit(fpl);
4754 if (__predict_false(dvs == VGET_NONE)) {
4755 return (cache_fpl_aborted(fpl));
4758 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4759 lkflags = LK_SHARED;
4760 if ((cnp->cn_flags & LOCKSHARED) == 0)
4761 lkflags = LK_EXCLUSIVE;
4762 error = vget_finish(dvp, lkflags, dvs);
4763 if (__predict_false(error != 0)) {
4764 return (cache_fpl_aborted(fpl));
4767 vget_finish_ref(dvp, dvs);
4769 return (cache_fpl_handled(fpl));
4772 static int __noinline
4773 cache_fplookup_noentry(struct cache_fpl *fpl)
4775 struct nameidata *ndp;
4776 struct componentname *cnp;
4778 struct vnode *dvp, *tvp;
4786 dvp_seqc = fpl->dvp_seqc;
4788 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4789 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4790 MPASS(!cache_fpl_isdotdot(cnp));
4793 * Hack: delayed name len checking.
4795 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4796 cache_fpl_smr_exit(fpl);
4797 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
4800 if (cnp->cn_nameptr[0] == '/') {
4801 return (cache_fplookup_skip_slashes(fpl));
4804 if (cnp->cn_nameptr[0] == '\0') {
4805 if (fpl->tvp == NULL) {
4806 return (cache_fplookup_degenerate(fpl));
4808 return (cache_fplookup_trailingslash(fpl));
4811 if (cnp->cn_nameiop != LOOKUP) {
4813 return (cache_fplookup_modifying(fpl));
4816 MPASS((cnp->cn_flags & SAVESTART) == 0);
4819 * Only try to fill in the component if it is the last one,
4820 * otherwise not only there may be several to handle but the
4821 * walk may be complicated.
4823 if (!cache_fpl_islastcn(ndp)) {
4824 return (cache_fpl_partial(fpl));
4828 * Regular lookup nulifies the slash, which we don't do here.
4829 * Don't take chances with filesystem routines seeing it for
4832 if (cache_fpl_istrailingslash(fpl)) {
4833 return (cache_fpl_partial(fpl));
4837 * Secure access to dvp; check cache_fplookup_partial_setup for
4840 dvs = vget_prep_smr(dvp);
4841 cache_fpl_smr_exit(fpl);
4842 if (__predict_false(dvs == VGET_NONE)) {
4843 return (cache_fpl_aborted(fpl));
4846 vget_finish_ref(dvp, dvs);
4847 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4849 return (cache_fpl_aborted(fpl));
4852 error = vn_lock(dvp, LK_SHARED);
4853 if (__predict_false(error != 0)) {
4855 return (cache_fpl_aborted(fpl));
4860 * TODO: provide variants which don't require locking either vnode.
4862 cnp->cn_flags |= ISLASTCN;
4863 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4865 cnp->cn_flags |= MAKEENTRY;
4866 cnp->cn_lkflags = LK_SHARED;
4867 if ((cnp->cn_flags & LOCKSHARED) == 0) {
4868 cnp->cn_lkflags = LK_EXCLUSIVE;
4870 error = VOP_LOOKUP(dvp, &tvp, cnp);
4878 return (cache_fpl_handled_error(fpl, error));
4881 return (cache_fpl_aborted(fpl));
4885 if (!fpl->savename) {
4886 MPASS((cnp->cn_flags & SAVENAME) == 0);
4890 MPASS(error == EJUSTRETURN);
4891 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4893 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4896 return (cache_fpl_handled(fpl));
4899 if (tvp->v_type == VLNK) {
4900 if ((cnp->cn_flags & FOLLOW) != 0) {
4903 return (cache_fpl_aborted(fpl));
4907 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4910 return (cache_fpl_aborted(fpl));
4913 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4917 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4919 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4922 return (cache_fpl_handled(fpl));
4925 static int __noinline
4926 cache_fplookup_dot(struct cache_fpl *fpl)
4930 MPASS(!seqc_in_modify(fpl->dvp_seqc));
4932 * Just re-assign the value. seqc will be checked later for the first
4933 * non-dot path component in line and/or before deciding to return the
4936 fpl->tvp = fpl->dvp;
4937 fpl->tvp_seqc = fpl->dvp_seqc;
4939 counter_u64_add(dothits, 1);
4940 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
4943 if (cache_fplookup_is_mp(fpl)) {
4944 error = cache_fplookup_cross_mount(fpl);
4949 static int __noinline
4950 cache_fplookup_dotdot(struct cache_fpl *fpl)
4952 struct nameidata *ndp;
4953 struct componentname *cnp;
4954 struct namecache *ncp;
4963 MPASS(cache_fpl_isdotdot(cnp));
4966 * XXX this is racy the same way regular lookup is
4968 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
4970 if (dvp == pr->pr_root)
4973 if (dvp == ndp->ni_rootdir ||
4974 dvp == ndp->ni_topdir ||
4978 fpl->tvp_seqc = vn_seqc_read_any(dvp);
4979 if (seqc_in_modify(fpl->tvp_seqc)) {
4980 return (cache_fpl_aborted(fpl));
4985 if ((dvp->v_vflag & VV_ROOT) != 0) {
4988 * The opposite of climb mount is needed here.
4990 return (cache_fpl_partial(fpl));
4993 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
4995 return (cache_fpl_aborted(fpl));
4998 nc_flag = atomic_load_char(&ncp->nc_flag);
4999 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5000 if ((nc_flag & NCF_NEGATIVE) != 0)
5001 return (cache_fpl_aborted(fpl));
5002 fpl->tvp = ncp->nc_vp;
5004 fpl->tvp = ncp->nc_dvp;
5007 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5008 if (seqc_in_modify(fpl->tvp_seqc)) {
5009 return (cache_fpl_partial(fpl));
5013 * Acquire fence provided by vn_seqc_read_any above.
5015 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5016 return (cache_fpl_aborted(fpl));
5019 if (!cache_ncp_canuse(ncp)) {
5020 return (cache_fpl_aborted(fpl));
5023 counter_u64_add(dotdothits, 1);
5027 static int __noinline
5028 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5033 nc_flag = atomic_load_char(&ncp->nc_flag);
5034 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5036 * If they want to create an entry we need to replace this one.
5038 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5040 return (cache_fplookup_modifying(fpl));
5042 neg_promote = cache_neg_hit_prep(ncp);
5043 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5044 cache_neg_hit_abort(ncp);
5045 return (cache_fpl_partial(fpl));
5048 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5050 cache_neg_hit_finish(ncp);
5051 cache_fpl_smr_exit(fpl);
5052 return (cache_fpl_handled_error(fpl, ENOENT));
5056 * Resolve a symlink. Called by filesystem-specific routines.
5059 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5062 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5064 struct nameidata *ndp;
5065 struct componentname *cnp;
5071 if (__predict_false(len == 0)) {
5075 if (__predict_false(len > MAXPATHLEN - 2)) {
5076 if (cache_fpl_istrailingslash(fpl)) {
5081 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5083 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5084 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5085 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5086 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5090 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5091 return (ENAMETOOLONG);
5094 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5099 if (ndp->ni_pathlen > 1) {
5100 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5102 if (cache_fpl_istrailingslash(fpl)) {
5104 cnp->cn_pnbuf[len] = '/';
5105 cnp->cn_pnbuf[len + 1] = '\0';
5107 cnp->cn_pnbuf[len] = '\0';
5110 bcopy(string, cnp->cn_pnbuf, len);
5112 ndp->ni_pathlen += adjust;
5113 cache_fpl_pathlen_add(fpl, adjust);
5114 cnp->cn_nameptr = cnp->cn_pnbuf;
5115 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5120 static int __noinline
5121 cache_fplookup_symlink(struct cache_fpl *fpl)
5124 struct nameidata *ndp;
5125 struct componentname *cnp;
5126 struct vnode *dvp, *tvp;
5134 if (cache_fpl_islastcn(ndp)) {
5135 if ((cnp->cn_flags & FOLLOW) == 0) {
5136 return (cache_fplookup_final(fpl));
5140 mp = atomic_load_ptr(&dvp->v_mount);
5141 if (__predict_false(mp == NULL)) {
5142 return (cache_fpl_aborted(fpl));
5146 * Note this check races against setting the flag just like regular
5149 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5150 cache_fpl_smr_exit(fpl);
5151 return (cache_fpl_handled_error(fpl, EACCES));
5154 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5155 if (__predict_false(error != 0)) {
5158 return (cache_fpl_partial(fpl));
5162 cache_fpl_smr_exit(fpl);
5163 return (cache_fpl_handled_error(fpl, error));
5165 return (cache_fpl_aborted(fpl));
5169 if (*(cnp->cn_nameptr) == '/') {
5170 fpl->dvp = cache_fpl_handle_root(fpl);
5171 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5172 if (seqc_in_modify(fpl->dvp_seqc)) {
5173 return (cache_fpl_aborted(fpl));
5176 * The main loop assumes that ->dvp points to a vnode belonging
5177 * to a filesystem which can do lockless lookup, but the absolute
5178 * symlink can be wandering off to one which does not.
5180 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5181 if (__predict_false(mp == NULL)) {
5182 return (cache_fpl_aborted(fpl));
5184 if (!cache_fplookup_mp_supported(mp)) {
5185 cache_fpl_checkpoint(fpl);
5186 return (cache_fpl_partial(fpl));
5193 cache_fplookup_next(struct cache_fpl *fpl)
5195 struct componentname *cnp;
5196 struct namecache *ncp;
5197 struct vnode *dvp, *tvp;
5206 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5207 if (cnp->cn_namelen == 1) {
5208 return (cache_fplookup_dot(fpl));
5210 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5211 return (cache_fplookup_dotdot(fpl));
5215 MPASS(!cache_fpl_isdotdot(cnp));
5217 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5218 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5219 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5223 if (__predict_false(ncp == NULL)) {
5224 return (cache_fplookup_noentry(fpl));
5227 tvp = atomic_load_ptr(&ncp->nc_vp);
5228 nc_flag = atomic_load_char(&ncp->nc_flag);
5229 if ((nc_flag & NCF_NEGATIVE) != 0) {
5230 return (cache_fplookup_neg(fpl, ncp, hash));
5233 if (!cache_ncp_canuse(ncp)) {
5234 return (cache_fpl_partial(fpl));
5238 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5239 if (seqc_in_modify(fpl->tvp_seqc)) {
5240 return (cache_fpl_partial(fpl));
5243 counter_u64_add(numposhits, 1);
5244 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5247 if (cache_fplookup_is_mp(fpl)) {
5248 error = cache_fplookup_cross_mount(fpl);
5254 cache_fplookup_mp_supported(struct mount *mp)
5258 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5264 * Walk up the mount stack (if any).
5266 * Correctness is provided in the following ways:
5267 * - all vnodes are protected from freeing with SMR
5268 * - struct mount objects are type stable making them always safe to access
5269 * - stability of the particular mount is provided by busying it
5270 * - relationship between the vnode which is mounted on and the mount is
5271 * verified with the vnode sequence counter after busying
5272 * - association between root vnode of the mount and the mount is protected
5275 * From that point on we can read the sequence counter of the root vnode
5276 * and get the next mount on the stack (if any) using the same protection.
5278 * By the end of successful walk we are guaranteed the reached state was
5279 * indeed present at least at some point which matches the regular lookup.
5281 static int __noinline
5282 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5284 struct mount *mp, *prev_mp;
5285 struct mount_pcpu *mpcpu, *prev_mpcpu;
5290 vp_seqc = fpl->tvp_seqc;
5292 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5293 mp = atomic_load_ptr(&vp->v_mountedhere);
5294 if (__predict_false(mp == NULL)) {
5300 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5301 if (prev_mp != NULL)
5302 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5303 return (cache_fpl_partial(fpl));
5305 if (prev_mp != NULL)
5306 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5307 if (!vn_seqc_consistent(vp, vp_seqc)) {
5308 vfs_op_thread_exit_crit(mp, mpcpu);
5309 return (cache_fpl_partial(fpl));
5311 if (!cache_fplookup_mp_supported(mp)) {
5312 vfs_op_thread_exit_crit(mp, mpcpu);
5313 return (cache_fpl_partial(fpl));
5315 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5317 vfs_op_thread_exit_crit(mp, mpcpu);
5318 return (cache_fpl_partial(fpl));
5320 vp_seqc = vn_seqc_read_any(vp);
5321 if (seqc_in_modify(vp_seqc)) {
5322 vfs_op_thread_exit_crit(mp, mpcpu);
5323 return (cache_fpl_partial(fpl));
5327 mp = atomic_load_ptr(&vp->v_mountedhere);
5332 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5334 fpl->tvp_seqc = vp_seqc;
5338 static int __noinline
5339 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5342 struct mount_pcpu *mpcpu;
5347 vp_seqc = fpl->tvp_seqc;
5349 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5350 mp = atomic_load_ptr(&vp->v_mountedhere);
5351 if (__predict_false(mp == NULL)) {
5355 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5356 return (cache_fpl_partial(fpl));
5358 if (!vn_seqc_consistent(vp, vp_seqc)) {
5359 vfs_op_thread_exit_crit(mp, mpcpu);
5360 return (cache_fpl_partial(fpl));
5362 if (!cache_fplookup_mp_supported(mp)) {
5363 vfs_op_thread_exit_crit(mp, mpcpu);
5364 return (cache_fpl_partial(fpl));
5366 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5367 if (__predict_false(vp == NULL)) {
5368 vfs_op_thread_exit_crit(mp, mpcpu);
5369 return (cache_fpl_partial(fpl));
5371 vp_seqc = vn_seqc_read_any(vp);
5372 vfs_op_thread_exit_crit(mp, mpcpu);
5373 if (seqc_in_modify(vp_seqc)) {
5374 return (cache_fpl_partial(fpl));
5376 mp = atomic_load_ptr(&vp->v_mountedhere);
5377 if (__predict_false(mp != NULL)) {
5379 * There are possibly more mount points on top.
5380 * Normally this does not happen so for simplicity just start
5383 return (cache_fplookup_climb_mount(fpl));
5387 fpl->tvp_seqc = vp_seqc;
5392 * Check if a vnode is mounted on.
5395 cache_fplookup_is_mp(struct cache_fpl *fpl)
5400 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5406 * The code was originally copy-pasted from regular lookup and despite
5407 * clean ups leaves performance on the table. Any modifications here
5408 * must take into account that in case off fallback the resulting
5409 * nameidata state has to be compatible with the original.
5413 * Debug ni_pathlen tracking.
5417 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5420 fpl->debug.ni_pathlen += n;
5421 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5422 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5426 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5429 fpl->debug.ni_pathlen -= n;
5430 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5431 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5435 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5438 cache_fpl_pathlen_add(fpl, 1);
5442 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5445 cache_fpl_pathlen_sub(fpl, 1);
5449 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5454 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5459 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5464 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5470 cache_fplookup_parse(struct cache_fpl *fpl)
5472 struct nameidata *ndp;
5473 struct componentname *cnp;
5483 * Find the end of this path component, it is either / or nul.
5485 * Store / as a temporary sentinel so that we only have one character
5486 * to test for. Pathnames tend to be short so this should not be
5487 * resulting in cache misses.
5489 * TODO: fix this to be word-sized.
5491 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5492 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5493 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5494 fpl->nulchar, cnp->cn_pnbuf));
5495 KASSERT(*fpl->nulchar == '\0',
5496 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5498 hash = cache_get_hash_iter_start(dvp);
5499 *fpl->nulchar = '/';
5500 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5501 KASSERT(*cp != '\0',
5502 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5504 hash = cache_get_hash_iter(*cp, hash);
5507 *fpl->nulchar = '\0';
5508 fpl->hash = cache_get_hash_iter_finish(hash);
5510 cnp->cn_namelen = cp - cnp->cn_nameptr;
5511 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5515 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5516 * we are going to fail this lookup with ENAMETOOLONG (see below).
5518 if (cnp->cn_namelen <= NAME_MAX) {
5519 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5520 panic("%s: mismatched hash for [%s] len %ld", __func__,
5521 cnp->cn_nameptr, cnp->cn_namelen);
5527 * Hack: we have to check if the found path component's length exceeds
5528 * NAME_MAX. However, the condition is very rarely true and check can
5529 * be elided in the common case -- if an entry was found in the cache,
5530 * then it could not have been too long to begin with.
5536 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5538 struct nameidata *ndp;
5539 struct componentname *cnp;
5544 cnp->cn_nameptr = ndp->ni_next;
5545 KASSERT(*(cnp->cn_nameptr) == '/',
5546 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5547 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5549 cache_fpl_pathlen_dec(fpl);
5553 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5555 * Lockless lookup tries to elide checking for spurious slashes and should they
5556 * be present is guaranteed to fail to find an entry. In this case the caller
5557 * must check if the name starts with a slash and call this routine. It is
5558 * going to fast forward across the spurious slashes and set the state up for
5561 static int __noinline
5562 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5564 struct nameidata *ndp;
5565 struct componentname *cnp;
5570 MPASS(*(cnp->cn_nameptr) == '/');
5573 cache_fpl_pathlen_dec(fpl);
5574 } while (*(cnp->cn_nameptr) == '/');
5577 * Go back to one slash so that cache_fplookup_parse_advance has
5578 * something to skip.
5581 cache_fpl_pathlen_inc(fpl);
5584 * cache_fplookup_parse_advance starts from ndp->ni_next
5586 ndp->ni_next = cnp->cn_nameptr;
5589 * See cache_fplookup_dot.
5591 fpl->tvp = fpl->dvp;
5592 fpl->tvp_seqc = fpl->dvp_seqc;
5598 * Handle trailing slashes (e.g., "foo/").
5600 * If a trailing slash is found the terminal vnode must be a directory.
5601 * Regular lookup shortens the path by nulifying the first trailing slash and
5602 * sets the TRAILINGSLASH flag to denote this took place. There are several
5603 * checks on it performed later.
5605 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5606 * manner relying on an invariant that a non-directory vnode will get a miss.
5607 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5609 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5610 * and denotes this is the last path component, which avoids looping back.
5612 * Only plain lookups are supported for now to restrict corner cases to handle.
5614 static int __noinline
5615 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5620 struct nameidata *ndp;
5621 struct componentname *cnp;
5622 struct namecache *ncp;
5624 char *cn_nameptr_orig, *cn_nameptr_slash;
5631 tvp_seqc = fpl->tvp_seqc;
5633 MPASS(fpl->dvp == fpl->tvp);
5634 KASSERT(cache_fpl_istrailingslash(fpl),
5635 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5637 KASSERT(cnp->cn_nameptr[0] == '\0',
5638 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5640 KASSERT(cnp->cn_namelen == 0,
5641 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5643 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5645 if (cnp->cn_nameiop != LOOKUP) {
5646 return (cache_fpl_aborted(fpl));
5649 if (__predict_false(tvp->v_type != VDIR)) {
5650 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5651 return (cache_fpl_aborted(fpl));
5653 cache_fpl_smr_exit(fpl);
5654 return (cache_fpl_handled_error(fpl, ENOTDIR));
5658 * Denote the last component.
5660 ndp->ni_next = &cnp->cn_nameptr[0];
5661 MPASS(cache_fpl_islastcn(ndp));
5664 * Unwind trailing slashes.
5666 cn_nameptr_orig = cnp->cn_nameptr;
5667 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5669 if (cnp->cn_nameptr[0] != '/') {
5675 * Unwind to the beginning of the path component.
5677 * Note the path may or may not have started with a slash.
5679 cn_nameptr_slash = cnp->cn_nameptr;
5680 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5682 if (cnp->cn_nameptr[0] == '/') {
5686 if (cnp->cn_nameptr[0] == '/') {
5690 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5691 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5692 cache_fpl_checkpoint(fpl);
5695 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5696 if (ni_pathlen != fpl->debug.ni_pathlen) {
5697 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5698 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5699 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5704 * If this was a "./" lookup the parent directory is already correct.
5706 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5711 * Otherwise we need to look it up.
5714 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5715 if (__predict_false(ncp == NULL)) {
5716 return (cache_fpl_aborted(fpl));
5718 nc_flag = atomic_load_char(&ncp->nc_flag);
5719 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5720 return (cache_fpl_aborted(fpl));
5722 fpl->dvp = ncp->nc_dvp;
5723 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5724 if (seqc_in_modify(fpl->dvp_seqc)) {
5725 return (cache_fpl_aborted(fpl));
5731 * See the API contract for VOP_FPLOOKUP_VEXEC.
5733 static int __noinline
5734 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5736 struct componentname *cnp;
5742 dvp_seqc = fpl->dvp_seqc;
5745 * TODO: Due to ignoring trailing slashes lookup will perform a
5746 * permission check on the last dir when it should not be doing it. It
5747 * may fail, but said failure should be ignored. It is possible to fix
5748 * it up fully without resorting to regular lookup, but for now just
5751 if (cache_fpl_istrailingslash(fpl)) {
5752 return (cache_fpl_aborted(fpl));
5756 * Hack: delayed degenerate path checking.
5758 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5759 return (cache_fplookup_degenerate(fpl));
5763 * Hack: delayed name len checking.
5765 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5766 cache_fpl_smr_exit(fpl);
5767 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5771 * Hack: they may be looking up foo/bar, where foo is not a directory.
5772 * In such a case we need to return ENOTDIR, but we may happen to get
5773 * here with a different error.
5775 if (dvp->v_type != VDIR) {
5780 * Hack: handle O_SEARCH.
5782 * Open Group Base Specifications Issue 7, 2018 edition states:
5784 * If the access mode of the open file description associated with the
5785 * file descriptor is not O_SEARCH, the function shall check whether
5786 * directory searches are permitted using the current permissions of
5787 * the directory underlying the file descriptor. If the access mode is
5788 * O_SEARCH, the function shall not perform the check.
5791 * Regular lookup tests for the NOEXECCHECK flag for every path
5792 * component to decide whether to do the permission check. However,
5793 * since most lookups never have the flag (and when they do it is only
5794 * present for the first path component), lockless lookup only acts on
5795 * it if there is a permission problem. Here the flag is represented
5796 * with a boolean so that we don't have to clear it on the way out.
5798 * For simplicity this always aborts.
5799 * TODO: check if this is the first lookup and ignore the permission
5800 * problem. Note the flag has to survive fallback (if it happens to be
5804 return (cache_fpl_aborted(fpl));
5809 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5810 error = cache_fpl_aborted(fpl);
5812 cache_fpl_partial(fpl);
5816 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5817 error = cache_fpl_aborted(fpl);
5819 cache_fpl_smr_exit(fpl);
5820 cache_fpl_handled_error(fpl, error);
5828 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
5830 struct nameidata *ndp;
5831 struct componentname *cnp;
5838 cache_fpl_checkpoint(fpl);
5841 * The vnode at hand is almost always stable, skip checking for it.
5842 * Worst case this postpones the check towards the end of the iteration
5846 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
5848 mp = atomic_load_ptr(&dvp->v_mount);
5849 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
5850 return (cache_fpl_aborted(fpl));
5853 MPASS(fpl->tvp == NULL);
5856 cache_fplookup_parse(fpl);
5858 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
5859 if (__predict_false(error != 0)) {
5860 error = cache_fplookup_failed_vexec(fpl, error);
5864 error = cache_fplookup_next(fpl);
5865 if (__predict_false(cache_fpl_terminated(fpl))) {
5869 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
5871 if (fpl->tvp->v_type == VLNK) {
5872 error = cache_fplookup_symlink(fpl);
5873 if (cache_fpl_terminated(fpl)) {
5877 if (cache_fpl_islastcn(ndp)) {
5878 error = cache_fplookup_final(fpl);
5882 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
5883 error = cache_fpl_aborted(fpl);
5887 fpl->dvp = fpl->tvp;
5888 fpl->dvp_seqc = fpl->tvp_seqc;
5889 cache_fplookup_parse_advance(fpl);
5892 cache_fpl_checkpoint(fpl);
5899 * Fast path lookup protected with SMR and sequence counters.
5901 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
5903 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
5906 * Traditional vnode lookup conceptually looks like this:
5912 * vn_unlock(current);
5919 * Each jump to the next vnode is safe memory-wise and atomic with respect to
5920 * any modifications thanks to holding respective locks.
5922 * The same guarantee can be provided with a combination of safe memory
5923 * reclamation and sequence counters instead. If all operations which affect
5924 * the relationship between the current vnode and the one we are looking for
5925 * also modify the counter, we can verify whether all the conditions held as
5926 * we made the jump. This includes things like permissions, mount points etc.
5927 * Counter modification is provided by enclosing relevant places in
5928 * vn_seqc_write_begin()/end() calls.
5930 * Thus this translates to:
5933 * dvp_seqc = seqc_read_any(dvp);
5934 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
5938 * tvp_seqc = seqc_read_any(tvp);
5939 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
5941 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
5943 * dvp = tvp; // we know nothing of importance has changed
5944 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
5948 * vget(); // secure the vnode
5949 * if (!seqc_consistent(tvp, tvp_seqc) // final check
5951 * // at this point we know nothing has changed for any parent<->child pair
5952 * // as they were crossed during the lookup, meaning we matched the guarantee
5953 * // of the locked variant
5956 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
5957 * - they are called while within vfs_smr protection which they must never exit
5958 * - EAGAIN can be returned to denote checking could not be performed, it is
5959 * always valid to return it
5960 * - if the sequence counter has not changed the result must be valid
5961 * - if the sequence counter has changed both false positives and false negatives
5962 * are permitted (since the result will be rejected later)
5963 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
5965 * Caveats to watch out for:
5966 * - vnodes are passed unlocked and unreferenced with nothing stopping
5967 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
5968 * to use atomic_load_ptr to fetch it.
5969 * - the aforementioned object can also get freed, meaning absent other means it
5970 * should be protected with vfs_smr
5971 * - either safely checking permissions as they are modified or guaranteeing
5972 * their stability is left to the routine
5975 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
5978 struct cache_fpl fpl;
5981 struct componentname *cnp;
5984 fpl.status = CACHE_FPL_STATUS_UNSET;
5987 fpl.cnp = cnp = &ndp->ni_cnd;
5988 MPASS(ndp->ni_lcf == 0);
5989 MPASS(curthread == cnp->cn_thread);
5990 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
5991 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
5993 if ((cnp->cn_flags & SAVESTART) != 0) {
5994 MPASS(cnp->cn_nameiop != LOOKUP);
5996 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
5998 if (__predict_false(!cache_can_fplookup(&fpl))) {
5999 *status = fpl.status;
6000 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6001 return (EOPNOTSUPP);
6004 cache_fpl_checkpoint_outer(&fpl);
6006 cache_fpl_smr_enter_initial(&fpl);
6008 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6010 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6011 fpl.fsearch = false;
6012 fpl.savename = (cnp->cn_flags & SAVENAME) != 0;
6013 fpl.tvp = NULL; /* for degenerate path handling */
6015 pwd = pwd_get_smr();
6017 ndp->ni_rootdir = pwd->pwd_rdir;
6018 ndp->ni_topdir = pwd->pwd_jdir;
6020 if (cnp->cn_pnbuf[0] == '/') {
6021 dvp = cache_fpl_handle_root(&fpl);
6022 MPASS(ndp->ni_resflags == 0);
6023 ndp->ni_resflags = NIRES_ABS;
6025 if (ndp->ni_dirfd == AT_FDCWD) {
6026 dvp = pwd->pwd_cdir;
6028 error = cache_fplookup_dirfd(&fpl, &dvp);
6029 if (__predict_false(error != 0)) {
6035 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6036 error = cache_fplookup_impl(dvp, &fpl);
6038 cache_fpl_smr_assert_not_entered(&fpl);
6039 cache_fpl_assert_status(&fpl);
6040 *status = fpl.status;
6041 if (SDT_PROBES_ENABLED()) {
6042 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6043 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6044 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6048 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6049 MPASS(error != CACHE_FPL_FAILED);
6051 MPASS(fpl.dvp == NULL);
6052 MPASS(fpl.tvp == NULL);
6053 MPASS(fpl.savename == false);
6055 ndp->ni_dvp = fpl.dvp;
6056 ndp->ni_vp = fpl.tvp;
6058 cnp->cn_flags |= HASBUF;
6060 cache_fpl_cleanup_cnp(cnp);