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_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
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_fplookup_lockout(void);
584 static void cache_fplookup_restore(void);
586 static void cache_zap_locked(struct namecache *ncp);
587 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
588 char **freebuf, size_t *buflen);
589 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
590 char **retbuf, size_t *buflen, size_t addend);
591 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
592 char **retbuf, size_t *buflen);
593 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
594 char **retbuf, size_t *len, size_t addend);
596 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
599 cache_assert_vlp_locked(struct mtx *vlp)
603 mtx_assert(vlp, MA_OWNED);
607 cache_assert_vnode_locked(struct vnode *vp)
611 vlp = VP2VNODELOCK(vp);
612 cache_assert_vlp_locked(vlp);
616 * Directory vnodes with entries are held for two reasons:
617 * 1. make them less of a target for reclamation in vnlru
618 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
620 * It will be feasible to stop doing it altogether if all filesystems start
621 * supporting lockless lookup.
624 cache_hold_vnode(struct vnode *vp)
627 cache_assert_vnode_locked(vp);
628 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
630 counter_u64_add(numcachehv, 1);
634 cache_drop_vnode(struct vnode *vp)
638 * Called after all locks are dropped, meaning we can't assert
639 * on the state of v_cache_src.
642 counter_u64_add(numcachehv, -1);
648 static uma_zone_t __read_mostly cache_zone_small;
649 static uma_zone_t __read_mostly cache_zone_small_ts;
650 static uma_zone_t __read_mostly cache_zone_large;
651 static uma_zone_t __read_mostly cache_zone_large_ts;
654 cache_symlink_alloc(size_t size, int flags)
657 if (size < CACHE_ZONE_SMALL_SIZE) {
658 return (uma_zalloc_smr(cache_zone_small, flags));
660 if (size < CACHE_ZONE_LARGE_SIZE) {
661 return (uma_zalloc_smr(cache_zone_large, flags));
663 counter_u64_add(symlinktoobig, 1);
664 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
669 cache_symlink_free(char *string, size_t size)
672 MPASS(string != NULL);
673 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
674 ("%s: size %zu too big", __func__, size));
676 if (size < CACHE_ZONE_SMALL_SIZE) {
677 uma_zfree_smr(cache_zone_small, string);
680 if (size < CACHE_ZONE_LARGE_SIZE) {
681 uma_zfree_smr(cache_zone_large, string);
684 __assert_unreachable();
687 static struct namecache *
688 cache_alloc_uma(int len, bool ts)
690 struct namecache_ts *ncp_ts;
691 struct namecache *ncp;
693 if (__predict_false(ts)) {
694 if (len <= CACHE_PATH_CUTOFF)
695 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
697 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
698 ncp = &ncp_ts->nc_nc;
700 if (len <= CACHE_PATH_CUTOFF)
701 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
703 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
709 cache_free_uma(struct namecache *ncp)
711 struct namecache_ts *ncp_ts;
713 if (__predict_false(ncp->nc_flag & NCF_TS)) {
714 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
715 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
716 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
718 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
720 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
721 uma_zfree_smr(cache_zone_small, ncp);
723 uma_zfree_smr(cache_zone_large, ncp);
727 static struct namecache *
728 cache_alloc(int len, bool ts)
733 * Avoid blowout in namecache entries.
736 * 1. filesystems may end up trying to add an already existing entry
737 * (for example this can happen after a cache miss during concurrent
738 * lookup), in which case we will call cache_neg_evict despite not
740 * 2. the routine may fail to free anything and no provisions are made
741 * to make it try harder (see the inside for failure modes)
742 * 3. it only ever looks at negative entries.
744 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
745 if (cache_neg_evict_cond(lnumcache)) {
746 lnumcache = atomic_load_long(&numcache);
748 if (__predict_false(lnumcache >= ncsize)) {
749 atomic_subtract_long(&numcache, 1);
750 counter_u64_add(numdrops, 1);
753 return (cache_alloc_uma(len, ts));
757 cache_free(struct namecache *ncp)
761 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
762 cache_drop_vnode(ncp->nc_dvp);
765 atomic_subtract_long(&numcache, 1);
769 cache_free_batch(struct cache_freebatch *batch)
771 struct namecache *ncp, *nnp;
775 if (TAILQ_EMPTY(batch))
777 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
778 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
779 cache_drop_vnode(ncp->nc_dvp);
784 atomic_subtract_long(&numcache, i);
786 SDT_PROBE1(vfs, namecache, purge, batch, i);
792 * The code was made to use FNV in 2001 and this choice needs to be revisited.
794 * Short summary of the difficulty:
795 * The longest name which can be inserted is NAME_MAX characters in length (or
796 * 255 at the time of writing this comment), while majority of names used in
797 * practice are significantly shorter (mostly below 10). More importantly
798 * majority of lookups performed find names are even shorter than that.
800 * This poses a problem where hashes which do better than FNV past word size
801 * (or so) tend to come with additional overhead when finalizing the result,
802 * making them noticeably slower for the most commonly used range.
804 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
806 * When looking it up the most time consuming part by a large margin (at least
807 * on amd64) is hashing. Replacing FNV with something which pessimizes short
808 * input would make the slowest part stand out even more.
812 * TODO: With the value stored we can do better than computing the hash based
816 cache_prehash(struct vnode *vp)
819 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
823 cache_get_hash(char *name, u_char len, struct vnode *dvp)
826 return (fnv_32_buf(name, len, dvp->v_nchash));
830 cache_get_hash_iter_start(struct vnode *dvp)
833 return (dvp->v_nchash);
837 cache_get_hash_iter(char c, uint32_t hash)
840 return (fnv_32_buf(&c, 1, hash));
844 cache_get_hash_iter_finish(uint32_t hash)
850 static inline struct nchashhead *
851 NCP2BUCKET(struct namecache *ncp)
855 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
856 return (NCHHASH(hash));
859 static inline struct mtx *
860 NCP2BUCKETLOCK(struct namecache *ncp)
864 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
865 return (HASH2BUCKETLOCK(hash));
870 cache_assert_bucket_locked(struct namecache *ncp)
874 blp = NCP2BUCKETLOCK(ncp);
875 mtx_assert(blp, MA_OWNED);
879 cache_assert_bucket_unlocked(struct namecache *ncp)
883 blp = NCP2BUCKETLOCK(ncp);
884 mtx_assert(blp, MA_NOTOWNED);
887 #define cache_assert_bucket_locked(x) do { } while (0)
888 #define cache_assert_bucket_unlocked(x) do { } while (0)
891 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
893 _cache_sort_vnodes(void **p1, void **p2)
897 MPASS(*p1 != NULL || *p2 != NULL);
907 cache_lock_all_buckets(void)
911 for (i = 0; i < numbucketlocks; i++)
912 mtx_lock(&bucketlocks[i]);
916 cache_unlock_all_buckets(void)
920 for (i = 0; i < numbucketlocks; i++)
921 mtx_unlock(&bucketlocks[i]);
925 cache_lock_all_vnodes(void)
929 for (i = 0; i < numvnodelocks; i++)
930 mtx_lock(&vnodelocks[i]);
934 cache_unlock_all_vnodes(void)
938 for (i = 0; i < numvnodelocks; i++)
939 mtx_unlock(&vnodelocks[i]);
943 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
946 cache_sort_vnodes(&vlp1, &vlp2);
949 if (!mtx_trylock(vlp1))
952 if (!mtx_trylock(vlp2)) {
962 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
965 MPASS(vlp1 != NULL || vlp2 != NULL);
975 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
978 MPASS(vlp1 != NULL || vlp2 != NULL);
987 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
989 struct nchstats snap;
991 if (req->oldptr == NULL)
992 return (SYSCTL_OUT(req, 0, sizeof(snap)));
995 snap.ncs_goodhits = counter_u64_fetch(numposhits);
996 snap.ncs_neghits = counter_u64_fetch(numneghits);
997 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
998 counter_u64_fetch(numnegzaps);
999 snap.ncs_miss = counter_u64_fetch(nummisszap) +
1000 counter_u64_fetch(nummiss);
1002 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
1004 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
1005 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
1006 "VFS cache effectiveness statistics");
1009 cache_recalc_neg_min(u_int val)
1012 neg_min = (ncsize * val) / 100;
1016 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1022 error = sysctl_handle_int(oidp, &val, 0, req);
1023 if (error != 0 || req->newptr == NULL)
1026 if (val == ncnegminpct)
1028 if (val < 0 || val > 99)
1031 cache_recalc_neg_min(val);
1035 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1036 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1037 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1041 * Grab an atomic snapshot of the name cache hash chain lengths
1043 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1044 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1045 "hash table stats");
1048 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1050 struct nchashhead *ncpp;
1051 struct namecache *ncp;
1052 int i, error, n_nchash, *cntbuf;
1055 n_nchash = nchash + 1; /* nchash is max index, not count */
1056 if (req->oldptr == NULL)
1057 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1058 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1059 cache_lock_all_buckets();
1060 if (n_nchash != nchash + 1) {
1061 cache_unlock_all_buckets();
1062 free(cntbuf, M_TEMP);
1065 /* Scan hash tables counting entries */
1066 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1067 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1069 cache_unlock_all_buckets();
1070 for (error = 0, i = 0; i < n_nchash; i++)
1071 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1073 free(cntbuf, M_TEMP);
1076 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1077 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1078 "nchash chain lengths");
1081 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1084 struct nchashhead *ncpp;
1085 struct namecache *ncp;
1087 int count, maxlength, used, pct;
1090 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1092 cache_lock_all_buckets();
1093 n_nchash = nchash + 1; /* nchash is max index, not count */
1097 /* Scan hash tables for applicable entries */
1098 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1100 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1105 if (maxlength < count)
1108 n_nchash = nchash + 1;
1109 cache_unlock_all_buckets();
1110 pct = (used * 100) / (n_nchash / 100);
1111 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1114 error = SYSCTL_OUT(req, &used, sizeof(used));
1117 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1120 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1125 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1126 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1127 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1131 * Negative entries management
1133 * Various workloads create plenty of negative entries and barely use them
1134 * afterwards. Moreover malicious users can keep performing bogus lookups
1135 * adding even more entries. For example "make tinderbox" as of writing this
1136 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1139 * As such, a rather aggressive eviction method is needed. The currently
1140 * employed method is a placeholder.
1142 * Entries are split over numneglists separate lists, each of which is further
1143 * split into hot and cold entries. Entries get promoted after getting a hit.
1144 * Eviction happens on addition of new entry.
1146 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1147 "Name cache negative entry statistics");
1149 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1150 "Number of negative cache entries");
1152 static COUNTER_U64_DEFINE_EARLY(neg_created);
1153 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1154 "Number of created negative entries");
1156 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1157 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1158 "Number of evicted negative entries");
1160 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1161 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1162 &neg_evict_skipped_empty,
1163 "Number of times evicting failed due to lack of entries");
1165 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1166 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1167 &neg_evict_skipped_missed,
1168 "Number of times evicting failed due to target entry disappearing");
1170 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1171 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1172 &neg_evict_skipped_contended,
1173 "Number of times evicting failed due to contention");
1175 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1176 "Number of cache hits (negative)");
1179 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1184 for (i = 0; i < numneglists; i++)
1185 out += neglists[i].nl_hotnum;
1187 return (SYSCTL_OUT(req, &out, sizeof(out)));
1189 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1190 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1191 "Number of hot negative entries");
1194 cache_neg_init(struct namecache *ncp)
1196 struct negstate *ns;
1198 ncp->nc_flag |= NCF_NEGATIVE;
1199 ns = NCP2NEGSTATE(ncp);
1202 counter_u64_add(neg_created, 1);
1205 #define CACHE_NEG_PROMOTION_THRESH 2
1208 cache_neg_hit_prep(struct namecache *ncp)
1210 struct negstate *ns;
1213 ns = NCP2NEGSTATE(ncp);
1214 n = atomic_load_char(&ns->neg_hit);
1216 if (n >= CACHE_NEG_PROMOTION_THRESH)
1218 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1221 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1225 * Nothing to do here but it is provided for completeness as some
1226 * cache_neg_hit_prep callers may end up returning without even
1227 * trying to promote.
1229 #define cache_neg_hit_abort(ncp) do { } while (0)
1232 cache_neg_hit_finish(struct namecache *ncp)
1235 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1236 counter_u64_add(numneghits, 1);
1240 * Move a negative entry to the hot list.
1243 cache_neg_promote_locked(struct namecache *ncp)
1246 struct negstate *ns;
1248 ns = NCP2NEGSTATE(ncp);
1249 nl = NCP2NEGLIST(ncp);
1250 mtx_assert(&nl->nl_lock, MA_OWNED);
1251 if ((ns->neg_flag & NEG_HOT) == 0) {
1252 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1253 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1255 ns->neg_flag |= NEG_HOT;
1260 * Move a hot negative entry to the cold list.
1263 cache_neg_demote_locked(struct namecache *ncp)
1266 struct negstate *ns;
1268 ns = NCP2NEGSTATE(ncp);
1269 nl = NCP2NEGLIST(ncp);
1270 mtx_assert(&nl->nl_lock, MA_OWNED);
1271 MPASS(ns->neg_flag & NEG_HOT);
1272 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1273 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1275 ns->neg_flag &= ~NEG_HOT;
1276 atomic_store_char(&ns->neg_hit, 0);
1280 * Move a negative entry to the hot list if it matches the lookup.
1282 * We have to take locks, but they may be contended and in the worst
1283 * case we may need to go off CPU. We don't want to spin within the
1284 * smr section and we can't block with it. Exiting the section means
1285 * the found entry could have been evicted. We are going to look it
1289 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1290 struct namecache *oncp, uint32_t hash)
1292 struct namecache *ncp;
1296 nl = NCP2NEGLIST(oncp);
1298 mtx_lock(&nl->nl_lock);
1300 * For hash iteration.
1305 * Avoid all surprises by only succeeding if we got the same entry and
1306 * bailing completely otherwise.
1307 * XXX There are no provisions to keep the vnode around, meaning we may
1308 * end up promoting a negative entry for a *new* vnode and returning
1309 * ENOENT on its account. This is the error we want to return anyway
1310 * and promotion is harmless.
1312 * In particular at this point there can be a new ncp which matches the
1313 * search but hashes to a different neglist.
1315 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1321 * No match to begin with.
1323 if (__predict_false(ncp == NULL)) {
1328 * The newly found entry may be something different...
1330 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1331 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1336 * ... and not even negative.
1338 nc_flag = atomic_load_char(&ncp->nc_flag);
1339 if ((nc_flag & NCF_NEGATIVE) == 0) {
1343 if (!cache_ncp_canuse(ncp)) {
1347 cache_neg_promote_locked(ncp);
1348 cache_neg_hit_finish(ncp);
1350 mtx_unlock(&nl->nl_lock);
1354 mtx_unlock(&nl->nl_lock);
1359 cache_neg_promote(struct namecache *ncp)
1363 nl = NCP2NEGLIST(ncp);
1364 mtx_lock(&nl->nl_lock);
1365 cache_neg_promote_locked(ncp);
1366 mtx_unlock(&nl->nl_lock);
1370 cache_neg_insert(struct namecache *ncp)
1374 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1375 cache_assert_bucket_locked(ncp);
1376 nl = NCP2NEGLIST(ncp);
1377 mtx_lock(&nl->nl_lock);
1378 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1379 mtx_unlock(&nl->nl_lock);
1380 atomic_add_long(&numneg, 1);
1384 cache_neg_remove(struct namecache *ncp)
1387 struct negstate *ns;
1389 cache_assert_bucket_locked(ncp);
1390 nl = NCP2NEGLIST(ncp);
1391 ns = NCP2NEGSTATE(ncp);
1392 mtx_lock(&nl->nl_lock);
1393 if ((ns->neg_flag & NEG_HOT) != 0) {
1394 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1397 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1399 mtx_unlock(&nl->nl_lock);
1400 atomic_subtract_long(&numneg, 1);
1403 static struct neglist *
1404 cache_neg_evict_select_list(void)
1409 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1410 nl = &neglists[c % numneglists];
1411 if (!mtx_trylock(&nl->nl_evict_lock)) {
1412 counter_u64_add(neg_evict_skipped_contended, 1);
1418 static struct namecache *
1419 cache_neg_evict_select_entry(struct neglist *nl)
1421 struct namecache *ncp, *lncp;
1422 struct negstate *ns, *lns;
1425 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1426 mtx_assert(&nl->nl_lock, MA_OWNED);
1427 ncp = TAILQ_FIRST(&nl->nl_list);
1431 lns = NCP2NEGSTATE(lncp);
1432 for (i = 1; i < 4; i++) {
1433 ncp = TAILQ_NEXT(ncp, nc_dst);
1436 ns = NCP2NEGSTATE(ncp);
1437 if (ns->neg_hit < lns->neg_hit) {
1446 cache_neg_evict(void)
1448 struct namecache *ncp, *ncp2;
1457 nl = cache_neg_evict_select_list();
1462 mtx_lock(&nl->nl_lock);
1463 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1465 cache_neg_demote_locked(ncp);
1467 ncp = cache_neg_evict_select_entry(nl);
1469 counter_u64_add(neg_evict_skipped_empty, 1);
1470 mtx_unlock(&nl->nl_lock);
1471 mtx_unlock(&nl->nl_evict_lock);
1474 nlen = ncp->nc_nlen;
1476 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1477 dvlp = VP2VNODELOCK(dvp);
1478 blp = HASH2BUCKETLOCK(hash);
1479 mtx_unlock(&nl->nl_lock);
1480 mtx_unlock(&nl->nl_evict_lock);
1484 * Note that since all locks were dropped above, the entry may be
1485 * gone or reallocated to be something else.
1487 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1488 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1489 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1493 counter_u64_add(neg_evict_skipped_missed, 1);
1497 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1498 MPASS(blp == NCP2BUCKETLOCK(ncp));
1499 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1501 cache_zap_locked(ncp);
1502 counter_u64_add(neg_evicted, 1);
1513 * Maybe evict a negative entry to create more room.
1515 * The ncnegfactor parameter limits what fraction of the total count
1516 * can comprise of negative entries. However, if the cache is just
1517 * warming up this leads to excessive evictions. As such, ncnegminpct
1518 * (recomputed to neg_min) dictates whether the above should be
1521 * Try evicting if the cache is close to full capacity regardless of
1522 * other considerations.
1525 cache_neg_evict_cond(u_long lnumcache)
1529 if (ncsize - 1000 < lnumcache)
1531 lnumneg = atomic_load_long(&numneg);
1532 if (lnumneg < neg_min)
1534 if (lnumneg * ncnegfactor < lnumcache)
1537 return (cache_neg_evict());
1541 * cache_zap_locked():
1543 * Removes a namecache entry from cache, whether it contains an actual
1544 * pointer to a vnode or if it is just a negative cache entry.
1547 cache_zap_locked(struct namecache *ncp)
1549 struct nchashhead *ncpp;
1550 struct vnode *dvp, *vp;
1555 if (!(ncp->nc_flag & NCF_NEGATIVE))
1556 cache_assert_vnode_locked(vp);
1557 cache_assert_vnode_locked(dvp);
1558 cache_assert_bucket_locked(ncp);
1560 cache_ncp_invalidate(ncp);
1562 ncpp = NCP2BUCKET(ncp);
1563 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1564 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1565 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1566 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1567 if (ncp == vp->v_cache_dd) {
1568 atomic_store_ptr(&vp->v_cache_dd, NULL);
1571 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1572 cache_neg_remove(ncp);
1574 if (ncp->nc_flag & NCF_ISDOTDOT) {
1575 if (ncp == dvp->v_cache_dd) {
1576 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1579 LIST_REMOVE(ncp, nc_src);
1580 if (LIST_EMPTY(&dvp->v_cache_src)) {
1581 ncp->nc_flag |= NCF_DVDROP;
1587 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1591 MPASS(ncp->nc_dvp == vp);
1592 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1593 cache_assert_vnode_locked(vp);
1595 blp = NCP2BUCKETLOCK(ncp);
1597 cache_zap_locked(ncp);
1602 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1605 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1608 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1609 cache_assert_vnode_locked(vp);
1611 if (ncp->nc_flag & NCF_NEGATIVE) {
1612 if (*vlpp != NULL) {
1616 cache_zap_negative_locked_vnode_kl(ncp, vp);
1620 pvlp = VP2VNODELOCK(vp);
1621 blp = NCP2BUCKETLOCK(ncp);
1622 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1623 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1625 if (*vlpp == vlp1 || *vlpp == vlp2) {
1629 if (*vlpp != NULL) {
1633 cache_sort_vnodes(&vlp1, &vlp2);
1638 if (!mtx_trylock(vlp1))
1644 cache_zap_locked(ncp);
1646 if (to_unlock != NULL)
1647 mtx_unlock(to_unlock);
1654 MPASS(*vlpp == NULL);
1660 * If trylocking failed we can get here. We know enough to take all needed locks
1661 * in the right order and re-lookup the entry.
1664 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1665 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1668 struct namecache *rncp;
1670 cache_assert_bucket_unlocked(ncp);
1672 cache_sort_vnodes(&dvlp, &vlp);
1673 cache_lock_vnodes(dvlp, vlp);
1675 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1676 if (rncp == ncp && rncp->nc_dvp == dvp &&
1677 rncp->nc_nlen == cnp->cn_namelen &&
1678 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1682 cache_zap_locked(rncp);
1684 cache_unlock_vnodes(dvlp, vlp);
1685 counter_u64_add(zap_bucket_relock_success, 1);
1690 cache_unlock_vnodes(dvlp, vlp);
1694 static int __noinline
1695 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1696 uint32_t hash, struct mtx *blp)
1698 struct mtx *dvlp, *vlp;
1701 cache_assert_bucket_locked(ncp);
1703 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1705 if (!(ncp->nc_flag & NCF_NEGATIVE))
1706 vlp = VP2VNODELOCK(ncp->nc_vp);
1707 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1708 cache_zap_locked(ncp);
1710 cache_unlock_vnodes(dvlp, vlp);
1716 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1719 static __noinline int
1720 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1722 struct namecache *ncp;
1724 struct mtx *dvlp, *dvlp2;
1728 if (cnp->cn_namelen == 2 &&
1729 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1730 dvlp = VP2VNODELOCK(dvp);
1734 ncp = dvp->v_cache_dd;
1739 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1742 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1743 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1745 MPASS(dvp->v_cache_dd == NULL);
1751 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1756 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1760 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1761 blp = HASH2BUCKETLOCK(hash);
1763 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1768 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1769 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1770 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1779 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1780 if (__predict_false(error != 0)) {
1784 counter_u64_add(numposzaps, 1);
1785 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1789 counter_u64_add(nummisszap, 1);
1790 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1794 static int __noinline
1795 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1796 struct timespec *tsp, int *ticksp)
1801 counter_u64_add(dothits, 1);
1802 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1809 * When we lookup "." we still can be asked to lock it
1812 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1813 if (ltype != VOP_ISLOCKED(*vpp)) {
1814 if (ltype == LK_EXCLUSIVE) {
1815 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1816 if (VN_IS_DOOMED((*vpp))) {
1817 /* forced unmount */
1823 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1828 static int __noinline
1829 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1830 struct timespec *tsp, int *ticksp)
1832 struct namecache_ts *ncp_ts;
1833 struct namecache *ncp;
1839 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1841 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1842 cache_remove_cnp(dvp, cnp);
1846 counter_u64_add(dotdothits, 1);
1848 dvlp = VP2VNODELOCK(dvp);
1850 ncp = dvp->v_cache_dd;
1852 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1856 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1857 if (ncp->nc_flag & NCF_NEGATIVE)
1864 goto negative_success;
1865 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1866 cache_out_ts(ncp, tsp, ticksp);
1867 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1868 NCF_DTS && tsp != NULL) {
1869 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1870 *tsp = ncp_ts->nc_dotdottime;
1874 ltype = VOP_ISLOCKED(dvp);
1876 vs = vget_prep(*vpp);
1878 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1879 vn_lock(dvp, ltype | LK_RETRY);
1880 if (VN_IS_DOOMED(dvp)) {
1892 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1893 if (cnp->cn_flags & ISLASTCN) {
1894 counter_u64_add(numnegzaps, 1);
1895 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1902 whiteout = (ncp->nc_flag & NCF_WHITE);
1903 cache_out_ts(ncp, tsp, ticksp);
1904 if (cache_neg_hit_prep(ncp))
1905 cache_neg_promote(ncp);
1907 cache_neg_hit_finish(ncp);
1910 cnp->cn_flags |= ISWHITEOUT;
1915 * Lookup a name in the name cache
1919 * - dvp: Parent directory in which to search.
1920 * - vpp: Return argument. Will contain desired vnode on cache hit.
1921 * - cnp: Parameters of the name search. The most interesting bits of
1922 * the cn_flags field have the following meanings:
1923 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1925 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1926 * - tsp: Return storage for cache timestamp. On a successful (positive
1927 * or negative) lookup, tsp will be filled with any timespec that
1928 * was stored when this cache entry was created. However, it will
1929 * be clear for "." entries.
1930 * - ticks: Return storage for alternate cache timestamp. On a successful
1931 * (positive or negative) lookup, it will contain the ticks value
1932 * that was current when the cache entry was created, unless cnp
1935 * Either both tsp and ticks have to be provided or neither of them.
1939 * - -1: A positive cache hit. vpp will contain the desired vnode.
1940 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1941 * to a forced unmount. vpp will not be modified. If the entry
1942 * is a whiteout, then the ISWHITEOUT flag will be set in
1944 * - 0: A cache miss. vpp will not be modified.
1948 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1949 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1950 * lock is not recursively acquired.
1952 static int __noinline
1953 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1954 struct timespec *tsp, int *ticksp)
1956 struct namecache *ncp;
1963 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1964 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1967 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1968 blp = HASH2BUCKETLOCK(hash);
1971 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1972 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1973 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1977 if (__predict_false(ncp == NULL)) {
1979 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
1980 counter_u64_add(nummiss, 1);
1984 if (ncp->nc_flag & NCF_NEGATIVE)
1985 goto negative_success;
1987 counter_u64_add(numposhits, 1);
1989 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1990 cache_out_ts(ncp, tsp, ticksp);
1992 vs = vget_prep(*vpp);
1994 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2002 * We don't get here with regular lookup apart from corner cases.
2004 if (__predict_true(cnp->cn_nameiop == CREATE)) {
2005 if (cnp->cn_flags & ISLASTCN) {
2006 counter_u64_add(numnegzaps, 1);
2007 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2008 if (__predict_false(error != 0)) {
2017 whiteout = (ncp->nc_flag & NCF_WHITE);
2018 cache_out_ts(ncp, tsp, ticksp);
2019 if (cache_neg_hit_prep(ncp))
2020 cache_neg_promote(ncp);
2022 cache_neg_hit_finish(ncp);
2025 cnp->cn_flags |= ISWHITEOUT;
2030 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2031 struct timespec *tsp, int *ticksp)
2033 struct namecache *ncp;
2037 bool whiteout, neg_promote;
2040 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2043 if (__predict_false(!doingcache)) {
2044 cnp->cn_flags &= ~MAKEENTRY;
2049 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2050 if (cnp->cn_namelen == 1)
2051 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2052 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2053 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2056 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2058 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2059 cache_remove_cnp(dvp, cnp);
2063 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2066 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2067 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2068 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2072 if (__predict_false(ncp == NULL)) {
2074 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2075 counter_u64_add(nummiss, 1);
2079 nc_flag = atomic_load_char(&ncp->nc_flag);
2080 if (nc_flag & NCF_NEGATIVE)
2081 goto negative_success;
2083 counter_u64_add(numposhits, 1);
2085 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2086 cache_out_ts(ncp, tsp, ticksp);
2088 if (!cache_ncp_canuse(ncp)) {
2093 vs = vget_prep_smr(*vpp);
2095 if (__predict_false(vs == VGET_NONE)) {
2099 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2106 if (cnp->cn_nameiop == CREATE) {
2107 if (cnp->cn_flags & ISLASTCN) {
2113 cache_out_ts(ncp, tsp, ticksp);
2114 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2115 neg_promote = cache_neg_hit_prep(ncp);
2116 if (!cache_ncp_canuse(ncp)) {
2117 cache_neg_hit_abort(ncp);
2123 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2126 cache_neg_hit_finish(ncp);
2130 cnp->cn_flags |= ISWHITEOUT;
2133 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2136 struct celockstate {
2140 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2141 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2144 cache_celockstate_init(struct celockstate *cel)
2147 bzero(cel, sizeof(*cel));
2151 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2154 struct mtx *vlp1, *vlp2;
2156 MPASS(cel->vlp[0] == NULL);
2157 MPASS(cel->vlp[1] == NULL);
2158 MPASS(cel->vlp[2] == NULL);
2160 MPASS(vp != NULL || dvp != NULL);
2162 vlp1 = VP2VNODELOCK(vp);
2163 vlp2 = VP2VNODELOCK(dvp);
2164 cache_sort_vnodes(&vlp1, &vlp2);
2175 cache_unlock_vnodes_cel(struct celockstate *cel)
2178 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2180 if (cel->vlp[0] != NULL)
2181 mtx_unlock(cel->vlp[0]);
2182 if (cel->vlp[1] != NULL)
2183 mtx_unlock(cel->vlp[1]);
2184 if (cel->vlp[2] != NULL)
2185 mtx_unlock(cel->vlp[2]);
2189 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2194 cache_assert_vlp_locked(cel->vlp[0]);
2195 cache_assert_vlp_locked(cel->vlp[1]);
2196 MPASS(cel->vlp[2] == NULL);
2199 vlp = VP2VNODELOCK(vp);
2202 if (vlp >= cel->vlp[1]) {
2205 if (mtx_trylock(vlp))
2207 cache_lock_vnodes_cel_3_failures++;
2208 cache_unlock_vnodes_cel(cel);
2209 if (vlp < cel->vlp[0]) {
2211 mtx_lock(cel->vlp[0]);
2212 mtx_lock(cel->vlp[1]);
2214 if (cel->vlp[0] != NULL)
2215 mtx_lock(cel->vlp[0]);
2217 mtx_lock(cel->vlp[1]);
2227 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2231 MPASS(cel->blp[0] == NULL);
2232 MPASS(cel->blp[1] == NULL);
2234 cache_sort_vnodes(&blp1, &blp2);
2245 cache_unlock_buckets_cel(struct celockstate *cel)
2248 if (cel->blp[0] != NULL)
2249 mtx_unlock(cel->blp[0]);
2250 mtx_unlock(cel->blp[1]);
2254 * Lock part of the cache affected by the insertion.
2256 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2257 * However, insertion can result in removal of an old entry. In this
2258 * case we have an additional vnode and bucketlock pair to lock.
2260 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2261 * preserving the locking order (smaller address first).
2264 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2267 struct namecache *ncp;
2268 struct mtx *blps[2];
2271 blps[0] = HASH2BUCKETLOCK(hash);
2274 cache_lock_vnodes_cel(cel, dvp, vp);
2275 if (vp == NULL || vp->v_type != VDIR)
2277 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2280 nc_flag = atomic_load_char(&ncp->nc_flag);
2281 if ((nc_flag & NCF_ISDOTDOT) == 0)
2283 MPASS(ncp->nc_dvp == vp);
2284 blps[1] = NCP2BUCKETLOCK(ncp);
2285 if ((nc_flag & NCF_NEGATIVE) != 0)
2287 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2290 * All vnodes got re-locked. Re-validate the state and if
2291 * nothing changed we are done. Otherwise restart.
2293 if (ncp == vp->v_cache_dd &&
2294 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2295 blps[1] == NCP2BUCKETLOCK(ncp) &&
2296 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2298 cache_unlock_vnodes_cel(cel);
2303 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2307 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2310 struct namecache *ncp;
2311 struct mtx *blps[2];
2314 blps[0] = HASH2BUCKETLOCK(hash);
2317 cache_lock_vnodes_cel(cel, dvp, vp);
2318 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2321 nc_flag = atomic_load_char(&ncp->nc_flag);
2322 if ((nc_flag & NCF_ISDOTDOT) == 0)
2324 MPASS(ncp->nc_dvp == dvp);
2325 blps[1] = NCP2BUCKETLOCK(ncp);
2326 if ((nc_flag & NCF_NEGATIVE) != 0)
2328 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2330 if (ncp == dvp->v_cache_dd &&
2331 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2332 blps[1] == NCP2BUCKETLOCK(ncp) &&
2333 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2335 cache_unlock_vnodes_cel(cel);
2340 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2344 cache_enter_unlock(struct celockstate *cel)
2347 cache_unlock_buckets_cel(cel);
2348 cache_unlock_vnodes_cel(cel);
2351 static void __noinline
2352 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2353 struct componentname *cnp)
2355 struct celockstate cel;
2356 struct namecache *ncp;
2360 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2362 len = cnp->cn_namelen;
2363 cache_celockstate_init(&cel);
2364 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2365 cache_enter_lock_dd(&cel, dvp, vp, hash);
2366 ncp = dvp->v_cache_dd;
2367 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2368 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2369 cache_zap_locked(ncp);
2373 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2374 cache_enter_unlock(&cel);
2380 * Add an entry to the cache.
2383 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2384 struct timespec *tsp, struct timespec *dtsp)
2386 struct celockstate cel;
2387 struct namecache *ncp, *n2, *ndd;
2388 struct namecache_ts *ncp_ts;
2389 struct nchashhead *ncpp;
2394 KASSERT(cnp->cn_namelen <= NAME_MAX,
2395 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2399 * Not everything doing this is weeded out yet.
2401 VNPASS(dvp != vp, dvp);
2403 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2404 VNPASS(dvp->v_type != VNON, dvp);
2406 VNPASS(!VN_IS_DOOMED(vp), vp);
2407 VNPASS(vp->v_type != VNON, vp);
2411 if (__predict_false(!doingcache))
2416 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2417 if (cnp->cn_namelen == 1)
2419 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2420 cache_enter_dotdot_prep(dvp, vp, cnp);
2421 flag = NCF_ISDOTDOT;
2425 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2429 cache_celockstate_init(&cel);
2434 * Calculate the hash key and setup as much of the new
2435 * namecache entry as possible before acquiring the lock.
2437 ncp->nc_flag = flag | NCF_WIP;
2440 cache_neg_init(ncp);
2443 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2444 ncp_ts->nc_time = *tsp;
2445 ncp_ts->nc_ticks = ticks;
2446 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2448 ncp_ts->nc_dotdottime = *dtsp;
2449 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2452 len = ncp->nc_nlen = cnp->cn_namelen;
2453 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2454 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2455 ncp->nc_name[len] = '\0';
2456 cache_enter_lock(&cel, dvp, vp, hash);
2459 * See if this vnode or negative entry is already in the cache
2460 * with this name. This can happen with concurrent lookups of
2461 * the same path name.
2463 ncpp = NCHHASH(hash);
2464 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2465 if (n2->nc_dvp == dvp &&
2466 n2->nc_nlen == cnp->cn_namelen &&
2467 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2468 MPASS(cache_ncp_canuse(n2));
2469 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2471 ("%s: found entry pointing to a different vnode (%p != %p)",
2472 __func__, NULL, vp));
2474 KASSERT(n2->nc_vp == vp,
2475 ("%s: found entry pointing to a different vnode (%p != %p)",
2476 __func__, n2->nc_vp, vp));
2478 * Entries are supposed to be immutable unless in the
2479 * process of getting destroyed. Accommodating for
2480 * changing timestamps is possible but not worth it.
2481 * This should be harmless in terms of correctness, in
2482 * the worst case resulting in an earlier expiration.
2483 * Alternatively, the found entry can be replaced
2486 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2489 KASSERT((n2->nc_flag & NCF_TS) != 0,
2491 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2492 n2_ts->nc_time = ncp_ts->nc_time;
2493 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2495 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2496 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2500 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2502 goto out_unlock_free;
2506 if (flag == NCF_ISDOTDOT) {
2508 * See if we are trying to add .. entry, but some other lookup
2509 * has populated v_cache_dd pointer already.
2511 if (dvp->v_cache_dd != NULL)
2512 goto out_unlock_free;
2513 KASSERT(vp == NULL || vp->v_type == VDIR,
2514 ("wrong vnode type %p", vp));
2515 atomic_thread_fence_rel();
2516 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2520 if (flag != NCF_ISDOTDOT) {
2522 * For this case, the cache entry maps both the
2523 * directory name in it and the name ".." for the
2524 * directory's parent.
2526 if ((ndd = vp->v_cache_dd) != NULL) {
2527 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2528 cache_zap_locked(ndd);
2532 atomic_thread_fence_rel();
2533 atomic_store_ptr(&vp->v_cache_dd, ncp);
2534 } else if (vp->v_type != VDIR) {
2535 if (vp->v_cache_dd != NULL) {
2536 atomic_store_ptr(&vp->v_cache_dd, NULL);
2541 if (flag != NCF_ISDOTDOT) {
2542 if (LIST_EMPTY(&dvp->v_cache_src)) {
2543 cache_hold_vnode(dvp);
2545 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2549 * If the entry is "negative", we place it into the
2550 * "negative" cache queue, otherwise, we place it into the
2551 * destination vnode's cache entries queue.
2554 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2555 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2558 if (cnp->cn_flags & ISWHITEOUT)
2559 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2560 cache_neg_insert(ncp);
2561 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2566 * Insert the new namecache entry into the appropriate chain
2567 * within the cache entries table.
2569 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2571 atomic_thread_fence_rel();
2573 * Mark the entry as fully constructed.
2574 * It is immutable past this point until its removal.
2576 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2578 cache_enter_unlock(&cel);
2583 cache_enter_unlock(&cel);
2589 cache_roundup_2(u_int val)
2593 for (res = 1; res <= val; res <<= 1)
2599 static struct nchashhead *
2600 nchinittbl(u_long elements, u_long *hashmask)
2602 struct nchashhead *hashtbl;
2605 hashsize = cache_roundup_2(elements) / 2;
2607 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2608 for (i = 0; i < hashsize; i++)
2609 CK_SLIST_INIT(&hashtbl[i]);
2610 *hashmask = hashsize - 1;
2615 ncfreetbl(struct nchashhead *hashtbl)
2618 free(hashtbl, M_VFSCACHE);
2622 * Name cache initialization, from vfs_init() when we are booting
2625 nchinit(void *dummy __unused)
2629 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2630 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2631 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2632 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2633 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2634 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2635 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2636 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2638 VFS_SMR_ZONE_SET(cache_zone_small);
2639 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2640 VFS_SMR_ZONE_SET(cache_zone_large);
2641 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2643 ncsize = desiredvnodes * ncsizefactor;
2644 cache_recalc_neg_min(ncnegminpct);
2645 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2646 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2647 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2649 if (ncbuckethash > nchash)
2650 ncbuckethash = nchash;
2651 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2653 for (i = 0; i < numbucketlocks; i++)
2654 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2655 ncvnodehash = ncbuckethash;
2656 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2658 for (i = 0; i < numvnodelocks; i++)
2659 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2661 for (i = 0; i < numneglists; i++) {
2662 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2663 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2664 TAILQ_INIT(&neglists[i].nl_list);
2665 TAILQ_INIT(&neglists[i].nl_hotlist);
2668 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2671 cache_vnode_init(struct vnode *vp)
2674 LIST_INIT(&vp->v_cache_src);
2675 TAILQ_INIT(&vp->v_cache_dst);
2676 vp->v_cache_dd = NULL;
2681 * Induce transient cache misses for lockless operation in cache_lookup() by
2682 * using a temporary hash table.
2684 * This will force a fs lookup.
2686 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2687 * to observe all CPUs not performing the lookup.
2690 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2693 MPASS(temphash < nchash);
2695 * Change the size. The new size is smaller and can safely be used
2696 * against the existing table. All lookups which now hash wrong will
2697 * result in a cache miss, which all callers are supposed to know how
2700 atomic_store_long(&nchash, temphash);
2701 atomic_thread_fence_rel();
2702 vfs_smr_synchronize();
2704 * At this point everyone sees the updated hash value, but they still
2705 * see the old table.
2707 atomic_store_ptr(&nchashtbl, temptbl);
2708 atomic_thread_fence_rel();
2709 vfs_smr_synchronize();
2711 * At this point everyone sees the updated table pointer and size pair.
2716 * Set the new hash table.
2718 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2719 * lockless operation in cache_lookup().
2722 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2725 MPASS(nchash < new_hash);
2727 * Change the pointer first. This wont result in out of bounds access
2728 * since the temporary table is guaranteed to be smaller.
2730 atomic_store_ptr(&nchashtbl, new_tbl);
2731 atomic_thread_fence_rel();
2732 vfs_smr_synchronize();
2734 * At this point everyone sees the updated pointer value, but they
2735 * still see the old size.
2737 atomic_store_long(&nchash, new_hash);
2738 atomic_thread_fence_rel();
2739 vfs_smr_synchronize();
2741 * At this point everyone sees the updated table pointer and size pair.
2746 cache_changesize(u_long newmaxvnodes)
2748 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2749 u_long new_nchash, old_nchash, temphash;
2750 struct namecache *ncp;
2755 newncsize = newmaxvnodes * ncsizefactor;
2756 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2757 if (newmaxvnodes < numbucketlocks)
2758 newmaxvnodes = numbucketlocks;
2760 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2761 /* If same hash table size, nothing to do */
2762 if (nchash == new_nchash) {
2763 ncfreetbl(new_nchashtbl);
2767 temptbl = nchinittbl(1, &temphash);
2770 * Move everything from the old hash table to the new table.
2771 * None of the namecache entries in the table can be removed
2772 * because to do so, they have to be removed from the hash table.
2774 cache_fplookup_lockout();
2775 cache_lock_all_vnodes();
2776 cache_lock_all_buckets();
2777 old_nchashtbl = nchashtbl;
2778 old_nchash = nchash;
2779 cache_changesize_set_temp(temptbl, temphash);
2780 for (i = 0; i <= old_nchash; i++) {
2781 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2782 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2784 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2785 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2789 cache_recalc_neg_min(ncnegminpct);
2790 cache_changesize_set_new(new_nchashtbl, new_nchash);
2791 cache_unlock_all_buckets();
2792 cache_unlock_all_vnodes();
2793 cache_fplookup_restore();
2794 ncfreetbl(old_nchashtbl);
2799 * Remove all entries from and to a particular vnode.
2802 cache_purge_impl(struct vnode *vp)
2804 struct cache_freebatch batch;
2805 struct namecache *ncp;
2806 struct mtx *vlp, *vlp2;
2809 vlp = VP2VNODELOCK(vp);
2813 while (!LIST_EMPTY(&vp->v_cache_src)) {
2814 ncp = LIST_FIRST(&vp->v_cache_src);
2815 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2817 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2819 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2820 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2821 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2823 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2825 ncp = vp->v_cache_dd;
2827 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2828 ("lost dotdot link"));
2829 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2831 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2833 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2837 cache_free_batch(&batch);
2841 * Opportunistic check to see if there is anything to do.
2844 cache_has_entries(struct vnode *vp)
2847 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2848 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2854 cache_purge(struct vnode *vp)
2857 SDT_PROBE1(vfs, namecache, purge, done, vp);
2858 if (!cache_has_entries(vp))
2860 cache_purge_impl(vp);
2864 * Only to be used by vgone.
2867 cache_purge_vgone(struct vnode *vp)
2871 VNPASS(VN_IS_DOOMED(vp), vp);
2872 if (cache_has_entries(vp)) {
2873 cache_purge_impl(vp);
2878 * Serialize against a potential thread doing cache_purge.
2880 vlp = VP2VNODELOCK(vp);
2881 mtx_wait_unlocked(vlp);
2882 if (cache_has_entries(vp)) {
2883 cache_purge_impl(vp);
2890 * Remove all negative entries for a particular directory vnode.
2893 cache_purge_negative(struct vnode *vp)
2895 struct cache_freebatch batch;
2896 struct namecache *ncp, *nnp;
2899 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2900 if (LIST_EMPTY(&vp->v_cache_src))
2903 vlp = VP2VNODELOCK(vp);
2905 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2906 if (!(ncp->nc_flag & NCF_NEGATIVE))
2908 cache_zap_negative_locked_vnode_kl(ncp, vp);
2909 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2912 cache_free_batch(&batch);
2916 * Entry points for modifying VOP operations.
2919 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2920 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2923 ASSERT_VOP_IN_SEQC(fdvp);
2924 ASSERT_VOP_IN_SEQC(fvp);
2925 ASSERT_VOP_IN_SEQC(tdvp);
2927 ASSERT_VOP_IN_SEQC(tvp);
2932 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2933 ("%s: lingering negative entry", __func__));
2935 cache_remove_cnp(tdvp, tcnp);
2941 * Historically renaming was always purging all revelang entries,
2942 * but that's quite wasteful. In particular turns out that in many cases
2943 * the target file is immediately accessed after rename, inducing a cache
2946 * Recode this to reduce relocking and reuse the existing entry (if any)
2947 * instead of just removing it above and allocating a new one here.
2949 if (cache_rename_add) {
2950 cache_enter(tdvp, fvp, tcnp);
2955 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2958 ASSERT_VOP_IN_SEQC(dvp);
2959 ASSERT_VOP_IN_SEQC(vp);
2965 * Validate that if an entry exists it matches.
2968 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2970 struct namecache *ncp;
2974 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2975 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2977 blp = HASH2BUCKETLOCK(hash);
2979 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2980 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2981 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2982 if (ncp->nc_vp != vp)
2983 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
2984 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
2992 * Flush all entries referencing a particular filesystem.
2995 cache_purgevfs(struct mount *mp)
2997 struct vnode *vp, *mvp;
2999 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
3001 * Somewhat wasteful iteration over all vnodes. Would be better to
3002 * support filtering and avoid the interlock to begin with.
3004 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3005 if (!cache_has_entries(vp)) {
3017 * Perform canonical checks and cache lookup and pass on to filesystem
3018 * through the vop_cachedlookup only if needed.
3022 vfs_cache_lookup(struct vop_lookup_args *ap)
3026 struct vnode **vpp = ap->a_vpp;
3027 struct componentname *cnp = ap->a_cnp;
3028 int flags = cnp->cn_flags;
3033 if (dvp->v_type != VDIR)
3036 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3037 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3040 error = vn_dir_check_exec(dvp, cnp);
3044 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3046 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3052 /* Implementation of the getcwd syscall. */
3054 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3060 buflen = uap->buflen;
3061 if (__predict_false(buflen < 2))
3063 if (buflen > MAXPATHLEN)
3064 buflen = MAXPATHLEN;
3066 buf = uma_zalloc(namei_zone, M_WAITOK);
3067 error = vn_getcwd(buf, &retbuf, &buflen);
3069 error = copyout(retbuf, uap->buf, buflen);
3070 uma_zfree(namei_zone, buf);
3075 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3081 pwd = pwd_get_smr();
3082 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3084 VFS_SMR_ASSERT_NOT_ENTERED();
3086 pwd = pwd_hold(curthread);
3087 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3093 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3100 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3101 size_t size, int flags, enum uio_seg pathseg)
3103 struct nameidata nd;
3104 char *retbuf, *freebuf;
3109 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
3110 pathseg, path, fd, &cap_fstat_rights, td);
3111 if ((error = namei(&nd)) != 0)
3113 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
3115 error = copyout(retbuf, buf, size);
3116 free(freebuf, M_TEMP);
3123 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3126 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3127 uap->flags, UIO_USERSPACE));
3131 * Retrieve the full filesystem path that correspond to a vnode from the name
3132 * cache (if available)
3135 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3142 if (__predict_false(vp == NULL))
3145 buflen = MAXPATHLEN;
3146 buf = malloc(buflen, M_TEMP, M_WAITOK);
3148 pwd = pwd_get_smr();
3149 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3150 VFS_SMR_ASSERT_NOT_ENTERED();
3152 pwd = pwd_hold(curthread);
3153 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3164 * This function is similar to vn_fullpath, but it attempts to lookup the
3165 * pathname relative to the global root mount point. This is required for the
3166 * auditing sub-system, as audited pathnames must be absolute, relative to the
3167 * global root mount point.
3170 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3176 if (__predict_false(vp == NULL))
3178 buflen = MAXPATHLEN;
3179 buf = malloc(buflen, M_TEMP, M_WAITOK);
3181 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3182 VFS_SMR_ASSERT_NOT_ENTERED();
3184 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3193 static struct namecache *
3194 vn_dd_from_dst(struct vnode *vp)
3196 struct namecache *ncp;
3198 cache_assert_vnode_locked(vp);
3199 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3200 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3207 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3210 struct namecache *ncp;
3214 vlp = VP2VNODELOCK(*vp);
3216 ncp = (*vp)->v_cache_dd;
3217 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3218 KASSERT(ncp == vn_dd_from_dst(*vp),
3219 ("%s: mismatch for dd entry (%p != %p)", __func__,
3220 ncp, vn_dd_from_dst(*vp)));
3222 ncp = vn_dd_from_dst(*vp);
3225 if (*buflen < ncp->nc_nlen) {
3228 counter_u64_add(numfullpathfail4, 1);
3230 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3234 *buflen -= ncp->nc_nlen;
3235 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3236 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3245 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3248 vn_lock(*vp, LK_SHARED | LK_RETRY);
3249 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3252 counter_u64_add(numfullpathfail2, 1);
3253 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3258 if (VN_IS_DOOMED(dvp)) {
3259 /* forced unmount */
3262 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3266 * *vp has its use count incremented still.
3273 * Resolve a directory to a pathname.
3275 * The name of the directory can always be found in the namecache or fetched
3276 * from the filesystem. There is also guaranteed to be only one parent, meaning
3277 * we can just follow vnodes up until we find the root.
3279 * The vnode must be referenced.
3282 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3283 size_t *len, size_t addend)
3285 #ifdef KDTRACE_HOOKS
3286 struct vnode *startvp = vp;
3291 bool slash_prefixed;
3293 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3294 VNPASS(vp->v_usecount > 0, vp);
3298 slash_prefixed = true;
3303 slash_prefixed = false;
3308 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3309 counter_u64_add(numfullpathcalls, 1);
3310 while (vp != rdir && vp != rootvnode) {
3312 * The vp vnode must be already fully constructed,
3313 * since it is either found in namecache or obtained
3314 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3315 * without obtaining the vnode lock.
3317 if ((vp->v_vflag & VV_ROOT) != 0) {
3318 vn_lock(vp, LK_RETRY | LK_SHARED);
3321 * With the vnode locked, check for races with
3322 * unmount, forced or not. Note that we
3323 * already verified that vp is not equal to
3324 * the root vnode, which means that
3325 * mnt_vnodecovered can be NULL only for the
3328 if (VN_IS_DOOMED(vp) ||
3329 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3330 vp1->v_mountedhere != vp->v_mount) {
3333 SDT_PROBE3(vfs, namecache, fullpath, return,
3343 if (vp->v_type != VDIR) {
3345 counter_u64_add(numfullpathfail1, 1);
3347 SDT_PROBE3(vfs, namecache, fullpath, return,
3351 error = vn_vptocnp(&vp, buf, &buflen);
3357 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3361 buf[--buflen] = '/';
3362 slash_prefixed = true;
3366 if (!slash_prefixed) {
3369 counter_u64_add(numfullpathfail4, 1);
3370 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3374 buf[--buflen] = '/';
3376 counter_u64_add(numfullpathfound, 1);
3379 *retbuf = buf + buflen;
3380 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3387 * Resolve an arbitrary vnode to a pathname.
3390 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3391 * resolve to a different path than the one used to find it
3392 * - namecache is not mandatory, meaning names are not guaranteed to be added
3393 * (in which case resolving fails)
3395 static void __inline
3396 cache_rev_failed_impl(int *reason, int line)
3401 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3404 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3405 char **retbuf, size_t *buflen, size_t addend)
3407 #ifdef KDTRACE_HOOKS
3408 struct vnode *startvp = vp;
3412 struct namecache *ncp;
3416 #ifdef KDTRACE_HOOKS
3419 seqc_t vp_seqc, tvp_seqc;
3422 VFS_SMR_ASSERT_ENTERED();
3424 if (!cache_fast_revlookup) {
3429 orig_buflen = *buflen;
3432 MPASS(*buflen >= 2);
3434 buf[*buflen] = '\0';
3437 if (vp == rdir || vp == rootvnode) {
3445 #ifdef KDTRACE_HOOKS
3449 ncp = NULL; /* for sdt probe down below */
3450 vp_seqc = vn_seqc_read_any(vp);
3451 if (seqc_in_modify(vp_seqc)) {
3452 cache_rev_failed(&reason);
3457 #ifdef KDTRACE_HOOKS
3460 if ((vp->v_vflag & VV_ROOT) != 0) {
3461 mp = atomic_load_ptr(&vp->v_mount);
3463 cache_rev_failed(&reason);
3466 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3467 tvp_seqc = vn_seqc_read_any(tvp);
3468 if (seqc_in_modify(tvp_seqc)) {
3469 cache_rev_failed(&reason);
3472 if (!vn_seqc_consistent(vp, vp_seqc)) {
3473 cache_rev_failed(&reason);
3480 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3482 cache_rev_failed(&reason);
3485 nc_flag = atomic_load_char(&ncp->nc_flag);
3486 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3487 cache_rev_failed(&reason);
3490 if (ncp->nc_nlen >= *buflen) {
3491 cache_rev_failed(&reason);
3495 *buflen -= ncp->nc_nlen;
3496 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3500 tvp_seqc = vn_seqc_read_any(tvp);
3501 if (seqc_in_modify(tvp_seqc)) {
3502 cache_rev_failed(&reason);
3505 if (!vn_seqc_consistent(vp, vp_seqc)) {
3506 cache_rev_failed(&reason);
3510 * Acquire fence provided by vn_seqc_read_any above.
3512 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3513 cache_rev_failed(&reason);
3516 if (!cache_ncp_canuse(ncp)) {
3517 cache_rev_failed(&reason);
3522 if (vp == rdir || vp == rootvnode)
3527 *retbuf = buf + *buflen;
3528 *buflen = orig_buflen - *buflen + addend;
3529 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3533 *buflen = orig_buflen;
3534 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3540 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3543 size_t orig_buflen, addend;
3549 orig_buflen = *buflen;
3553 if (vp->v_type != VDIR) {
3555 buf[*buflen] = '\0';
3556 error = vn_vptocnp(&vp, buf, buflen);
3565 addend = orig_buflen - *buflen;
3568 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3572 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3574 * Since the namecache does not track hardlinks, the caller is expected to first
3575 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3577 * Then we have 2 cases:
3578 * - if the found vnode is a directory, the path can be constructed just by
3579 * following names up the chain
3580 * - otherwise we populate the buffer with the saved name and start resolving
3584 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3589 struct componentname *cnp;
3597 if (*buflen > MAXPATHLEN)
3598 *buflen = MAXPATHLEN;
3600 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3605 * Check for VBAD to work around the vp_crossmp bug in lookup().
3607 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3608 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3609 * If the type is VDIR (like in this very case) we can skip looking
3610 * at ni_dvp in the first place. However, since vnodes get passed here
3611 * unlocked the target may transition to doomed state (type == VBAD)
3612 * before we get to evaluate the condition. If this happens, we will
3613 * populate part of the buffer and descend to vn_fullpath_dir with
3614 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3616 * This should be atomic_load(&vp->v_type) but it is illegal to take
3617 * an address of a bit field, even if said field is sized to char.
3618 * Work around the problem by reading the value into a full-sized enum
3619 * and then re-reading it with atomic_load which will still prevent
3620 * the compiler from re-reading down the road.
3623 type = atomic_load_int(&type);
3630 addend = cnp->cn_namelen + 2;
3631 if (*buflen < addend) {
3636 tmpbuf = buf + *buflen;
3638 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3639 tmpbuf[addend - 1] = '\0';
3644 pwd = pwd_get_smr();
3645 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3647 VFS_SMR_ASSERT_NOT_ENTERED();
3649 pwd = pwd_hold(curthread);
3651 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3667 vn_dir_dd_ino(struct vnode *vp)
3669 struct namecache *ncp;
3674 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3675 vlp = VP2VNODELOCK(vp);
3677 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3678 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3681 vs = vget_prep(ddvp);
3683 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3692 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3694 struct namecache *ncp;
3698 vlp = VP2VNODELOCK(vp);
3700 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3701 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3707 l = min(ncp->nc_nlen, buflen - 1);
3708 memcpy(buf, ncp->nc_name, l);
3715 * This function updates path string to vnode's full global path
3716 * and checks the size of the new path string against the pathlen argument.
3718 * Requires a locked, referenced vnode.
3719 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3721 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3722 * because it falls back to the ".." lookup if the namecache lookup fails.
3725 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3728 struct nameidata nd;
3733 ASSERT_VOP_ELOCKED(vp, __func__);
3735 /* Construct global filesystem path from vp. */
3737 error = vn_fullpath_global(vp, &rpath, &fbuf);
3744 if (strlen(rpath) >= pathlen) {
3746 error = ENAMETOOLONG;
3751 * Re-lookup the vnode by path to detect a possible rename.
3752 * As a side effect, the vnode is relocked.
3753 * If vnode was renamed, return ENOENT.
3755 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3756 UIO_SYSSPACE, path, td);
3762 NDFREE(&nd, NDF_ONLY_PNBUF);
3766 strcpy(path, rpath);
3779 db_print_vpath(struct vnode *vp)
3782 while (vp != NULL) {
3783 db_printf("%p: ", vp);
3784 if (vp == rootvnode) {
3788 if (vp->v_vflag & VV_ROOT) {
3789 db_printf("<mount point>");
3790 vp = vp->v_mount->mnt_vnodecovered;
3792 struct namecache *ncp;
3796 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3799 for (i = 0; i < ncp->nc_nlen; i++)
3800 db_printf("%c", *ncn++);
3813 DB_SHOW_COMMAND(vpath, db_show_vpath)
3818 db_printf("usage: show vpath <struct vnode *>\n");
3822 vp = (struct vnode *)addr;
3828 static int cache_fast_lookup = 1;
3829 static char __read_frequently cache_fast_lookup_enabled = true;
3831 #define CACHE_FPL_FAILED -2020
3834 cache_fast_lookup_enabled_recalc(void)
3840 mac_on = mac_vnode_check_lookup_enabled();
3841 mac_on |= mac_vnode_check_readlink_enabled();
3846 lookup_flag = atomic_load_int(&cache_fast_lookup);
3847 if (lookup_flag && !mac_on) {
3848 atomic_store_char(&cache_fast_lookup_enabled, true);
3850 atomic_store_char(&cache_fast_lookup_enabled, false);
3855 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
3859 old = atomic_load_int(&cache_fast_lookup);
3860 error = sysctl_handle_int(oidp, arg1, arg2, req);
3861 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
3862 cache_fast_lookup_enabled_recalc();
3865 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
3866 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
3869 * Disable lockless lookup and observe all CPUs not executing it.
3871 * Used when resizing the hash table.
3873 * TODO: no provisions are made to handle tweaking of the knob at the same time
3876 cache_fplookup_lockout(void)
3880 on = atomic_load_char(&cache_fast_lookup_enabled);
3882 atomic_store_char(&cache_fast_lookup_enabled, false);
3883 atomic_thread_fence_rel();
3884 vfs_smr_synchronize();
3889 cache_fplookup_restore(void)
3892 cache_fast_lookup_enabled_recalc();
3896 * Components of nameidata (or objects it can point to) which may
3897 * need restoring in case fast path lookup fails.
3899 struct nameidata_outer {
3904 struct nameidata_saved {
3912 struct cache_fpl_debug {
3918 struct nameidata *ndp;
3919 struct componentname *cnp;
3926 struct nameidata_saved snd;
3927 struct nameidata_outer snd_outer;
3929 enum cache_fpl_status status:8;
3935 struct cache_fpl_debug debug;
3939 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
3940 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
3941 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
3942 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
3943 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
3944 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
3945 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
3946 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
3947 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
3950 cache_fpl_cleanup_cnp(struct componentname *cnp)
3953 uma_zfree(namei_zone, cnp->cn_pnbuf);
3955 cnp->cn_pnbuf = NULL;
3956 cnp->cn_nameptr = NULL;
3960 static struct vnode *
3961 cache_fpl_handle_root(struct cache_fpl *fpl)
3963 struct nameidata *ndp;
3964 struct componentname *cnp;
3969 MPASS(*(cnp->cn_nameptr) == '/');
3971 cache_fpl_pathlen_dec(fpl);
3973 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
3976 cache_fpl_pathlen_dec(fpl);
3977 } while (*(cnp->cn_nameptr) == '/');
3980 return (ndp->ni_rootdir);
3984 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
3987 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
3988 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
3992 cache_fpl_checkpoint(struct cache_fpl *fpl)
3996 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3997 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4002 cache_fpl_restore_partial(struct cache_fpl *fpl)
4005 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4007 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4012 cache_fpl_restore_abort(struct cache_fpl *fpl)
4015 cache_fpl_restore_partial(fpl);
4017 * It is 0 on entry by API contract.
4019 fpl->ndp->ni_resflags = 0;
4020 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4021 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4025 #define cache_fpl_smr_assert_entered(fpl) ({ \
4026 struct cache_fpl *_fpl = (fpl); \
4027 MPASS(_fpl->in_smr == true); \
4028 VFS_SMR_ASSERT_ENTERED(); \
4030 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4031 struct cache_fpl *_fpl = (fpl); \
4032 MPASS(_fpl->in_smr == false); \
4033 VFS_SMR_ASSERT_NOT_ENTERED(); \
4036 cache_fpl_assert_status(struct cache_fpl *fpl)
4039 switch (fpl->status) {
4040 case CACHE_FPL_STATUS_UNSET:
4041 __assert_unreachable();
4043 case CACHE_FPL_STATUS_DESTROYED:
4044 case CACHE_FPL_STATUS_ABORTED:
4045 case CACHE_FPL_STATUS_PARTIAL:
4046 case CACHE_FPL_STATUS_HANDLED:
4051 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4052 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4053 #define cache_fpl_assert_status(fpl) do { } while (0)
4056 #define cache_fpl_smr_enter_initial(fpl) ({ \
4057 struct cache_fpl *_fpl = (fpl); \
4059 _fpl->in_smr = true; \
4062 #define cache_fpl_smr_enter(fpl) ({ \
4063 struct cache_fpl *_fpl = (fpl); \
4064 MPASS(_fpl->in_smr == false); \
4066 _fpl->in_smr = true; \
4069 #define cache_fpl_smr_exit(fpl) ({ \
4070 struct cache_fpl *_fpl = (fpl); \
4071 MPASS(_fpl->in_smr == true); \
4073 _fpl->in_smr = false; \
4077 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4080 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4081 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4082 ("%s: converting to abort from %d at %d, set at %d\n",
4083 __func__, fpl->status, line, fpl->line));
4085 cache_fpl_smr_assert_not_entered(fpl);
4086 fpl->status = CACHE_FPL_STATUS_ABORTED;
4088 return (CACHE_FPL_FAILED);
4091 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4093 static int __noinline
4094 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4096 struct nameidata *ndp;
4097 struct componentname *cnp;
4102 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4103 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4104 ("%s: converting to abort from %d at %d, set at %d\n",
4105 __func__, fpl->status, line, fpl->line));
4107 fpl->status = CACHE_FPL_STATUS_ABORTED;
4110 cache_fpl_smr_exit(fpl);
4111 cache_fpl_restore_abort(fpl);
4113 * Resolving symlinks overwrites data passed by the caller.
4116 if (ndp->ni_loopcnt > 0) {
4117 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4118 cache_fpl_cleanup_cnp(cnp);
4120 return (CACHE_FPL_FAILED);
4123 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4125 static int __noinline
4126 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4129 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4130 ("%s: setting to partial at %d, but already set to %d at %d\n",
4131 __func__, line, fpl->status, fpl->line));
4132 cache_fpl_smr_assert_entered(fpl);
4133 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4135 return (cache_fplookup_partial_setup(fpl));
4138 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4141 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4144 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4145 ("%s: setting to handled at %d, but already set to %d at %d\n",
4146 __func__, line, fpl->status, fpl->line));
4147 cache_fpl_smr_assert_not_entered(fpl);
4148 fpl->status = CACHE_FPL_STATUS_HANDLED;
4153 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4156 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4159 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4160 ("%s: setting to handled at %d, but already set to %d at %d\n",
4161 __func__, line, fpl->status, fpl->line));
4163 MPASS(error != CACHE_FPL_FAILED);
4164 cache_fpl_smr_assert_not_entered(fpl);
4165 fpl->status = CACHE_FPL_STATUS_HANDLED;
4169 fpl->savename = false;
4173 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4176 cache_fpl_terminated(struct cache_fpl *fpl)
4179 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4182 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4183 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4184 FAILIFEXISTS | FOLLOW | LOCKSHARED | SAVENAME | SAVESTART | WILLBEDIR | \
4185 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
4187 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4188 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4190 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4191 "supported and internal flags overlap");
4194 cache_fpl_islastcn(struct nameidata *ndp)
4197 return (*ndp->ni_next == 0);
4201 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4204 return (*(fpl->nulchar - 1) == '/');
4208 cache_fpl_isdotdot(struct componentname *cnp)
4211 if (cnp->cn_namelen == 2 &&
4212 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4218 cache_can_fplookup(struct cache_fpl *fpl)
4220 struct nameidata *ndp;
4221 struct componentname *cnp;
4226 td = cnp->cn_thread;
4228 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4229 cache_fpl_aborted_early(fpl);
4232 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4233 cache_fpl_aborted_early(fpl);
4236 if (IN_CAPABILITY_MODE(td)) {
4237 cache_fpl_aborted_early(fpl);
4240 if (AUDITING_TD(td)) {
4241 cache_fpl_aborted_early(fpl);
4244 if (ndp->ni_startdir != NULL) {
4245 cache_fpl_aborted_early(fpl);
4252 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4254 struct nameidata *ndp;
4259 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4260 if (__predict_false(error != 0)) {
4261 return (cache_fpl_aborted(fpl));
4263 fpl->fsearch = fsearch;
4267 static int __noinline
4268 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4271 struct componentname *cnp;
4277 cache_fpl_smr_exit(fpl);
4278 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4279 return (cache_fpl_handled_error(fpl, ENOENT));
4281 return (cache_fpl_aborted(fpl));
4285 * The target vnode is not supported, prepare for the slow path to take over.
4287 static int __noinline
4288 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4290 struct nameidata *ndp;
4291 struct componentname *cnp;
4301 dvp_seqc = fpl->dvp_seqc;
4303 if (!pwd_hold_smr(pwd)) {
4304 return (cache_fpl_aborted(fpl));
4308 * Note that seqc is checked before the vnode is locked, so by
4309 * the time regular lookup gets to it it may have moved.
4311 * Ultimately this does not affect correctness, any lookup errors
4312 * are userspace racing with itself. It is guaranteed that any
4313 * path which ultimately gets found could also have been found
4314 * by regular lookup going all the way in absence of concurrent
4317 dvs = vget_prep_smr(dvp);
4318 cache_fpl_smr_exit(fpl);
4319 if (__predict_false(dvs == VGET_NONE)) {
4321 return (cache_fpl_aborted(fpl));
4324 vget_finish_ref(dvp, dvs);
4325 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4328 return (cache_fpl_aborted(fpl));
4331 cache_fpl_restore_partial(fpl);
4333 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4334 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4335 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4339 ndp->ni_startdir = dvp;
4340 cnp->cn_flags |= MAKEENTRY;
4341 if (cache_fpl_islastcn(ndp))
4342 cnp->cn_flags |= ISLASTCN;
4343 if (cache_fpl_isdotdot(cnp))
4344 cnp->cn_flags |= ISDOTDOT;
4347 * Skip potential extra slashes parsing did not take care of.
4348 * cache_fplookup_skip_slashes explains the mechanism.
4350 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4353 cache_fpl_pathlen_dec(fpl);
4354 } while (*(cnp->cn_nameptr) == '/');
4357 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4359 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4360 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4361 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4362 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4369 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4371 struct componentname *cnp;
4378 tvp_seqc = fpl->tvp_seqc;
4380 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4381 lkflags = LK_SHARED;
4382 if ((cnp->cn_flags & LOCKSHARED) == 0)
4383 lkflags = LK_EXCLUSIVE;
4384 error = vget_finish(tvp, lkflags, tvs);
4385 if (__predict_false(error != 0)) {
4386 return (cache_fpl_aborted(fpl));
4389 vget_finish_ref(tvp, tvs);
4392 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4393 if ((cnp->cn_flags & LOCKLEAF) != 0)
4397 return (cache_fpl_aborted(fpl));
4400 return (cache_fpl_handled(fpl));
4404 * They want to possibly modify the state of the namecache.
4406 static int __noinline
4407 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4409 struct nameidata *ndp;
4410 struct componentname *cnp;
4412 struct vnode *dvp, *tvp;
4421 dvp_seqc = fpl->dvp_seqc;
4423 MPASS(*(cnp->cn_nameptr) != '/');
4424 MPASS(cache_fpl_islastcn(ndp));
4425 if ((cnp->cn_flags & LOCKPARENT) == 0)
4426 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4427 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4428 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4429 cnp->cn_nameiop == RENAME);
4430 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4431 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4433 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4434 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4438 * Regular lookup nulifies the slash, which we don't do here.
4439 * Don't take chances with filesystem routines seeing it for
4442 if (cache_fpl_istrailingslash(fpl)) {
4443 return (cache_fpl_partial(fpl));
4446 mp = atomic_load_ptr(&dvp->v_mount);
4447 if (__predict_false(mp == NULL)) {
4448 return (cache_fpl_aborted(fpl));
4451 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4452 cache_fpl_smr_exit(fpl);
4454 * Original code keeps not checking for CREATE which
4455 * might be a bug. For now let the old lookup decide.
4457 if (cnp->cn_nameiop == CREATE) {
4458 return (cache_fpl_aborted(fpl));
4460 return (cache_fpl_handled_error(fpl, EROFS));
4463 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4464 cache_fpl_smr_exit(fpl);
4465 return (cache_fpl_handled_error(fpl, EEXIST));
4469 * Secure access to dvp; check cache_fplookup_partial_setup for
4472 * XXX At least UFS requires its lookup routine to be called for
4473 * the last path component, which leads to some level of complication
4475 * - the target routine always locks the target vnode, but our caller
4476 * may not need it locked
4477 * - some of the VOP machinery asserts that the parent is locked, which
4478 * once more may be not required
4480 * TODO: add a flag for filesystems which don't need this.
4482 dvs = vget_prep_smr(dvp);
4483 cache_fpl_smr_exit(fpl);
4484 if (__predict_false(dvs == VGET_NONE)) {
4485 return (cache_fpl_aborted(fpl));
4488 vget_finish_ref(dvp, dvs);
4489 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4491 return (cache_fpl_aborted(fpl));
4494 error = vn_lock(dvp, LK_EXCLUSIVE);
4495 if (__predict_false(error != 0)) {
4497 return (cache_fpl_aborted(fpl));
4501 cnp->cn_flags |= ISLASTCN;
4503 cnp->cn_flags |= MAKEENTRY;
4504 if (cache_fpl_isdotdot(cnp))
4505 cnp->cn_flags |= ISDOTDOT;
4506 cnp->cn_lkflags = LK_EXCLUSIVE;
4507 error = VOP_LOOKUP(dvp, &tvp, cnp);
4515 return (cache_fpl_handled_error(fpl, error));
4518 return (cache_fpl_aborted(fpl));
4522 fpl->savename = (cnp->cn_flags & SAVENAME) != 0;
4525 if ((cnp->cn_flags & SAVESTART) != 0) {
4526 ndp->ni_startdir = dvp;
4527 vrefact(ndp->ni_startdir);
4528 cnp->cn_flags |= SAVENAME;
4529 fpl->savename = true;
4531 MPASS(error == EJUSTRETURN);
4532 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4535 return (cache_fpl_handled(fpl));
4539 * There are very hairy corner cases concerning various flag combinations
4540 * and locking state. In particular here we only hold one lock instead of
4543 * Skip the complexity as it is of no significance for normal workloads.
4545 if (__predict_false(tvp == dvp)) {
4548 return (cache_fpl_aborted(fpl));
4552 * If they want the symlink itself we are fine, but if they want to
4553 * follow it regular lookup has to be engaged.
4555 if (tvp->v_type == VLNK) {
4556 if ((cnp->cn_flags & FOLLOW) != 0) {
4559 return (cache_fpl_aborted(fpl));
4564 * Since we expect this to be the terminal vnode it should almost never
4567 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4570 return (cache_fpl_aborted(fpl));
4573 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4576 return (cache_fpl_handled_error(fpl, EEXIST));
4579 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4583 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4587 if ((cnp->cn_flags & SAVESTART) != 0) {
4588 ndp->ni_startdir = dvp;
4589 vrefact(ndp->ni_startdir);
4590 cnp->cn_flags |= SAVENAME;
4591 fpl->savename = true;
4594 return (cache_fpl_handled(fpl));
4597 static int __noinline
4598 cache_fplookup_modifying(struct cache_fpl *fpl)
4600 struct nameidata *ndp;
4604 if (!cache_fpl_islastcn(ndp)) {
4605 return (cache_fpl_partial(fpl));
4607 return (cache_fplookup_final_modifying(fpl));
4610 static int __noinline
4611 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4613 struct componentname *cnp;
4614 enum vgetstate dvs, tvs;
4615 struct vnode *dvp, *tvp;
4621 dvp_seqc = fpl->dvp_seqc;
4624 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4627 * This is less efficient than it can be for simplicity.
4629 dvs = vget_prep_smr(dvp);
4630 if (__predict_false(dvs == VGET_NONE)) {
4631 return (cache_fpl_aborted(fpl));
4633 tvs = vget_prep_smr(tvp);
4634 if (__predict_false(tvs == VGET_NONE)) {
4635 cache_fpl_smr_exit(fpl);
4636 vget_abort(dvp, dvs);
4637 return (cache_fpl_aborted(fpl));
4640 cache_fpl_smr_exit(fpl);
4642 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4643 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4644 if (__predict_false(error != 0)) {
4645 vget_abort(tvp, tvs);
4646 return (cache_fpl_aborted(fpl));
4649 vget_finish_ref(dvp, dvs);
4652 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4653 vget_abort(tvp, tvs);
4654 if ((cnp->cn_flags & LOCKPARENT) != 0)
4658 return (cache_fpl_aborted(fpl));
4661 error = cache_fplookup_final_child(fpl, tvs);
4662 if (__predict_false(error != 0)) {
4663 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4664 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4665 if ((cnp->cn_flags & LOCKPARENT) != 0)
4672 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4677 cache_fplookup_final(struct cache_fpl *fpl)
4679 struct componentname *cnp;
4681 struct vnode *dvp, *tvp;
4686 dvp_seqc = fpl->dvp_seqc;
4689 MPASS(*(cnp->cn_nameptr) != '/');
4691 if (cnp->cn_nameiop != LOOKUP) {
4692 return (cache_fplookup_final_modifying(fpl));
4695 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4696 return (cache_fplookup_final_withparent(fpl));
4698 tvs = vget_prep_smr(tvp);
4699 if (__predict_false(tvs == VGET_NONE)) {
4700 return (cache_fpl_partial(fpl));
4703 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4704 cache_fpl_smr_exit(fpl);
4705 vget_abort(tvp, tvs);
4706 return (cache_fpl_aborted(fpl));
4709 cache_fpl_smr_exit(fpl);
4710 return (cache_fplookup_final_child(fpl, tvs));
4714 * Comment from locked lookup:
4715 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4716 * directory, e.g. like "/." or ".".
4718 static int __noinline
4719 cache_fplookup_degenerate(struct cache_fpl *fpl)
4721 struct componentname *cnp;
4729 fpl->tvp = fpl->dvp;
4730 fpl->tvp_seqc = fpl->dvp_seqc;
4736 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4738 ("%s: encountered non-slash; string [%s]\n", __func__,
4743 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4744 cache_fpl_smr_exit(fpl);
4745 return (cache_fpl_handled_error(fpl, EISDIR));
4748 MPASS((cnp->cn_flags & SAVESTART) == 0);
4750 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4751 return (cache_fplookup_final_withparent(fpl));
4754 dvs = vget_prep_smr(dvp);
4755 cache_fpl_smr_exit(fpl);
4756 if (__predict_false(dvs == VGET_NONE)) {
4757 return (cache_fpl_aborted(fpl));
4760 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4761 lkflags = LK_SHARED;
4762 if ((cnp->cn_flags & LOCKSHARED) == 0)
4763 lkflags = LK_EXCLUSIVE;
4764 error = vget_finish(dvp, lkflags, dvs);
4765 if (__predict_false(error != 0)) {
4766 return (cache_fpl_aborted(fpl));
4769 vget_finish_ref(dvp, dvs);
4771 return (cache_fpl_handled(fpl));
4774 static int __noinline
4775 cache_fplookup_noentry(struct cache_fpl *fpl)
4777 struct nameidata *ndp;
4778 struct componentname *cnp;
4780 struct vnode *dvp, *tvp;
4788 dvp_seqc = fpl->dvp_seqc;
4790 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4791 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4792 MPASS(!cache_fpl_isdotdot(cnp));
4795 * Hack: delayed name len checking.
4797 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4798 cache_fpl_smr_exit(fpl);
4799 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
4802 if (cnp->cn_nameptr[0] == '/') {
4803 return (cache_fplookup_skip_slashes(fpl));
4806 if (cnp->cn_nameptr[0] == '\0') {
4807 if (fpl->tvp == NULL) {
4808 return (cache_fplookup_degenerate(fpl));
4810 return (cache_fplookup_trailingslash(fpl));
4813 if (cnp->cn_nameiop != LOOKUP) {
4815 return (cache_fplookup_modifying(fpl));
4818 MPASS((cnp->cn_flags & SAVESTART) == 0);
4821 * Only try to fill in the component if it is the last one,
4822 * otherwise not only there may be several to handle but the
4823 * walk may be complicated.
4825 if (!cache_fpl_islastcn(ndp)) {
4826 return (cache_fpl_partial(fpl));
4830 * Regular lookup nulifies the slash, which we don't do here.
4831 * Don't take chances with filesystem routines seeing it for
4834 if (cache_fpl_istrailingslash(fpl)) {
4835 return (cache_fpl_partial(fpl));
4839 * Secure access to dvp; check cache_fplookup_partial_setup for
4842 dvs = vget_prep_smr(dvp);
4843 cache_fpl_smr_exit(fpl);
4844 if (__predict_false(dvs == VGET_NONE)) {
4845 return (cache_fpl_aborted(fpl));
4848 vget_finish_ref(dvp, dvs);
4849 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4851 return (cache_fpl_aborted(fpl));
4854 error = vn_lock(dvp, LK_SHARED);
4855 if (__predict_false(error != 0)) {
4857 return (cache_fpl_aborted(fpl));
4862 * TODO: provide variants which don't require locking either vnode.
4864 cnp->cn_flags |= ISLASTCN;
4865 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4867 cnp->cn_flags |= MAKEENTRY;
4868 cnp->cn_lkflags = LK_SHARED;
4869 if ((cnp->cn_flags & LOCKSHARED) == 0) {
4870 cnp->cn_lkflags = LK_EXCLUSIVE;
4872 error = VOP_LOOKUP(dvp, &tvp, cnp);
4880 return (cache_fpl_handled_error(fpl, error));
4883 return (cache_fpl_aborted(fpl));
4887 if (!fpl->savename) {
4888 MPASS((cnp->cn_flags & SAVENAME) == 0);
4892 MPASS(error == EJUSTRETURN);
4893 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4895 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4898 return (cache_fpl_handled(fpl));
4901 if (tvp->v_type == VLNK) {
4902 if ((cnp->cn_flags & FOLLOW) != 0) {
4905 return (cache_fpl_aborted(fpl));
4909 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4912 return (cache_fpl_aborted(fpl));
4915 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4919 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4921 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4924 return (cache_fpl_handled(fpl));
4927 static int __noinline
4928 cache_fplookup_dot(struct cache_fpl *fpl)
4932 MPASS(!seqc_in_modify(fpl->dvp_seqc));
4934 * Just re-assign the value. seqc will be checked later for the first
4935 * non-dot path component in line and/or before deciding to return the
4938 fpl->tvp = fpl->dvp;
4939 fpl->tvp_seqc = fpl->dvp_seqc;
4941 counter_u64_add(dothits, 1);
4942 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
4945 if (cache_fplookup_is_mp(fpl)) {
4946 error = cache_fplookup_cross_mount(fpl);
4951 static int __noinline
4952 cache_fplookup_dotdot(struct cache_fpl *fpl)
4954 struct nameidata *ndp;
4955 struct componentname *cnp;
4956 struct namecache *ncp;
4965 MPASS(cache_fpl_isdotdot(cnp));
4968 * XXX this is racy the same way regular lookup is
4970 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
4972 if (dvp == pr->pr_root)
4975 if (dvp == ndp->ni_rootdir ||
4976 dvp == ndp->ni_topdir ||
4980 fpl->tvp_seqc = vn_seqc_read_any(dvp);
4981 if (seqc_in_modify(fpl->tvp_seqc)) {
4982 return (cache_fpl_aborted(fpl));
4987 if ((dvp->v_vflag & VV_ROOT) != 0) {
4990 * The opposite of climb mount is needed here.
4992 return (cache_fpl_partial(fpl));
4995 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
4997 return (cache_fpl_aborted(fpl));
5000 nc_flag = atomic_load_char(&ncp->nc_flag);
5001 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5002 if ((nc_flag & NCF_NEGATIVE) != 0)
5003 return (cache_fpl_aborted(fpl));
5004 fpl->tvp = ncp->nc_vp;
5006 fpl->tvp = ncp->nc_dvp;
5009 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5010 if (seqc_in_modify(fpl->tvp_seqc)) {
5011 return (cache_fpl_partial(fpl));
5015 * Acquire fence provided by vn_seqc_read_any above.
5017 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5018 return (cache_fpl_aborted(fpl));
5021 if (!cache_ncp_canuse(ncp)) {
5022 return (cache_fpl_aborted(fpl));
5025 counter_u64_add(dotdothits, 1);
5029 static int __noinline
5030 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5035 nc_flag = atomic_load_char(&ncp->nc_flag);
5036 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5038 * If they want to create an entry we need to replace this one.
5040 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5042 return (cache_fplookup_modifying(fpl));
5044 neg_promote = cache_neg_hit_prep(ncp);
5045 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5046 cache_neg_hit_abort(ncp);
5047 return (cache_fpl_partial(fpl));
5050 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5052 cache_neg_hit_finish(ncp);
5053 cache_fpl_smr_exit(fpl);
5054 return (cache_fpl_handled_error(fpl, ENOENT));
5058 * Resolve a symlink. Called by filesystem-specific routines.
5061 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5064 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5066 struct nameidata *ndp;
5067 struct componentname *cnp;
5073 if (__predict_false(len == 0)) {
5077 if (__predict_false(len > MAXPATHLEN - 2)) {
5078 if (cache_fpl_istrailingslash(fpl)) {
5083 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5085 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5086 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5087 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5088 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5092 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5093 return (ENAMETOOLONG);
5096 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5101 if (ndp->ni_pathlen > 1) {
5102 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5104 if (cache_fpl_istrailingslash(fpl)) {
5106 cnp->cn_pnbuf[len] = '/';
5107 cnp->cn_pnbuf[len + 1] = '\0';
5109 cnp->cn_pnbuf[len] = '\0';
5112 bcopy(string, cnp->cn_pnbuf, len);
5114 ndp->ni_pathlen += adjust;
5115 cache_fpl_pathlen_add(fpl, adjust);
5116 cnp->cn_nameptr = cnp->cn_pnbuf;
5117 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5122 static int __noinline
5123 cache_fplookup_symlink(struct cache_fpl *fpl)
5126 struct nameidata *ndp;
5127 struct componentname *cnp;
5128 struct vnode *dvp, *tvp;
5136 if (cache_fpl_islastcn(ndp)) {
5137 if ((cnp->cn_flags & FOLLOW) == 0) {
5138 return (cache_fplookup_final(fpl));
5142 mp = atomic_load_ptr(&dvp->v_mount);
5143 if (__predict_false(mp == NULL)) {
5144 return (cache_fpl_aborted(fpl));
5148 * Note this check races against setting the flag just like regular
5151 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5152 cache_fpl_smr_exit(fpl);
5153 return (cache_fpl_handled_error(fpl, EACCES));
5156 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5157 if (__predict_false(error != 0)) {
5160 return (cache_fpl_partial(fpl));
5164 cache_fpl_smr_exit(fpl);
5165 return (cache_fpl_handled_error(fpl, error));
5167 return (cache_fpl_aborted(fpl));
5171 if (*(cnp->cn_nameptr) == '/') {
5172 fpl->dvp = cache_fpl_handle_root(fpl);
5173 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5174 if (seqc_in_modify(fpl->dvp_seqc)) {
5175 return (cache_fpl_aborted(fpl));
5182 cache_fplookup_next(struct cache_fpl *fpl)
5184 struct componentname *cnp;
5185 struct namecache *ncp;
5186 struct vnode *dvp, *tvp;
5195 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5196 if (cnp->cn_namelen == 1) {
5197 return (cache_fplookup_dot(fpl));
5199 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5200 return (cache_fplookup_dotdot(fpl));
5204 MPASS(!cache_fpl_isdotdot(cnp));
5206 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5207 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5208 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5212 if (__predict_false(ncp == NULL)) {
5213 return (cache_fplookup_noentry(fpl));
5216 tvp = atomic_load_ptr(&ncp->nc_vp);
5217 nc_flag = atomic_load_char(&ncp->nc_flag);
5218 if ((nc_flag & NCF_NEGATIVE) != 0) {
5219 return (cache_fplookup_neg(fpl, ncp, hash));
5222 if (!cache_ncp_canuse(ncp)) {
5223 return (cache_fpl_partial(fpl));
5227 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5228 if (seqc_in_modify(fpl->tvp_seqc)) {
5229 return (cache_fpl_partial(fpl));
5232 counter_u64_add(numposhits, 1);
5233 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5236 if (cache_fplookup_is_mp(fpl)) {
5237 error = cache_fplookup_cross_mount(fpl);
5243 cache_fplookup_mp_supported(struct mount *mp)
5247 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5253 * Walk up the mount stack (if any).
5255 * Correctness is provided in the following ways:
5256 * - all vnodes are protected from freeing with SMR
5257 * - struct mount objects are type stable making them always safe to access
5258 * - stability of the particular mount is provided by busying it
5259 * - relationship between the vnode which is mounted on and the mount is
5260 * verified with the vnode sequence counter after busying
5261 * - association between root vnode of the mount and the mount is protected
5264 * From that point on we can read the sequence counter of the root vnode
5265 * and get the next mount on the stack (if any) using the same protection.
5267 * By the end of successful walk we are guaranteed the reached state was
5268 * indeed present at least at some point which matches the regular lookup.
5270 static int __noinline
5271 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5273 struct mount *mp, *prev_mp;
5274 struct mount_pcpu *mpcpu, *prev_mpcpu;
5279 vp_seqc = fpl->tvp_seqc;
5281 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5282 mp = atomic_load_ptr(&vp->v_mountedhere);
5283 if (__predict_false(mp == NULL)) {
5289 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5290 if (prev_mp != NULL)
5291 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5292 return (cache_fpl_partial(fpl));
5294 if (prev_mp != NULL)
5295 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5296 if (!vn_seqc_consistent(vp, vp_seqc)) {
5297 vfs_op_thread_exit_crit(mp, mpcpu);
5298 return (cache_fpl_partial(fpl));
5300 if (!cache_fplookup_mp_supported(mp)) {
5301 vfs_op_thread_exit_crit(mp, mpcpu);
5302 return (cache_fpl_partial(fpl));
5304 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5306 vfs_op_thread_exit_crit(mp, mpcpu);
5307 return (cache_fpl_partial(fpl));
5309 vp_seqc = vn_seqc_read_any(vp);
5310 if (seqc_in_modify(vp_seqc)) {
5311 vfs_op_thread_exit_crit(mp, mpcpu);
5312 return (cache_fpl_partial(fpl));
5316 mp = atomic_load_ptr(&vp->v_mountedhere);
5321 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5323 fpl->tvp_seqc = vp_seqc;
5327 static int __noinline
5328 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5331 struct mount_pcpu *mpcpu;
5336 vp_seqc = fpl->tvp_seqc;
5338 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5339 mp = atomic_load_ptr(&vp->v_mountedhere);
5340 if (__predict_false(mp == NULL)) {
5344 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5345 return (cache_fpl_partial(fpl));
5347 if (!vn_seqc_consistent(vp, vp_seqc)) {
5348 vfs_op_thread_exit_crit(mp, mpcpu);
5349 return (cache_fpl_partial(fpl));
5351 if (!cache_fplookup_mp_supported(mp)) {
5352 vfs_op_thread_exit_crit(mp, mpcpu);
5353 return (cache_fpl_partial(fpl));
5355 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5356 if (__predict_false(vp == NULL)) {
5357 vfs_op_thread_exit_crit(mp, mpcpu);
5358 return (cache_fpl_partial(fpl));
5360 vp_seqc = vn_seqc_read_any(vp);
5361 vfs_op_thread_exit_crit(mp, mpcpu);
5362 if (seqc_in_modify(vp_seqc)) {
5363 return (cache_fpl_partial(fpl));
5365 mp = atomic_load_ptr(&vp->v_mountedhere);
5366 if (__predict_false(mp != NULL)) {
5368 * There are possibly more mount points on top.
5369 * Normally this does not happen so for simplicity just start
5372 return (cache_fplookup_climb_mount(fpl));
5376 fpl->tvp_seqc = vp_seqc;
5381 * Check if a vnode is mounted on.
5384 cache_fplookup_is_mp(struct cache_fpl *fpl)
5389 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5395 * The code was originally copy-pasted from regular lookup and despite
5396 * clean ups leaves performance on the table. Any modifications here
5397 * must take into account that in case off fallback the resulting
5398 * nameidata state has to be compatible with the original.
5402 * Debug ni_pathlen tracking.
5406 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5409 fpl->debug.ni_pathlen += n;
5410 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5411 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5415 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5418 fpl->debug.ni_pathlen -= n;
5419 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5420 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5424 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5427 cache_fpl_pathlen_add(fpl, 1);
5431 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5434 cache_fpl_pathlen_sub(fpl, 1);
5438 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5443 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5448 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5453 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5459 cache_fplookup_parse(struct cache_fpl *fpl)
5461 struct nameidata *ndp;
5462 struct componentname *cnp;
5472 * Find the end of this path component, it is either / or nul.
5474 * Store / as a temporary sentinel so that we only have one character
5475 * to test for. Pathnames tend to be short so this should not be
5476 * resulting in cache misses.
5478 * TODO: fix this to be word-sized.
5480 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5481 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5482 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5483 fpl->nulchar, cnp->cn_pnbuf));
5484 KASSERT(*fpl->nulchar == '\0',
5485 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5487 hash = cache_get_hash_iter_start(dvp);
5488 *fpl->nulchar = '/';
5489 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5490 KASSERT(*cp != '\0',
5491 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5493 hash = cache_get_hash_iter(*cp, hash);
5496 *fpl->nulchar = '\0';
5497 fpl->hash = cache_get_hash_iter_finish(hash);
5499 cnp->cn_namelen = cp - cnp->cn_nameptr;
5500 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5504 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5505 * we are going to fail this lookup with ENAMETOOLONG (see below).
5507 if (cnp->cn_namelen <= NAME_MAX) {
5508 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5509 panic("%s: mismatched hash for [%s] len %ld", __func__,
5510 cnp->cn_nameptr, cnp->cn_namelen);
5516 * Hack: we have to check if the found path component's length exceeds
5517 * NAME_MAX. However, the condition is very rarely true and check can
5518 * be elided in the common case -- if an entry was found in the cache,
5519 * then it could not have been too long to begin with.
5525 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5527 struct nameidata *ndp;
5528 struct componentname *cnp;
5533 cnp->cn_nameptr = ndp->ni_next;
5534 KASSERT(*(cnp->cn_nameptr) == '/',
5535 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5536 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5538 cache_fpl_pathlen_dec(fpl);
5542 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5544 * Lockless lookup tries to elide checking for spurious slashes and should they
5545 * be present is guaranteed to fail to find an entry. In this case the caller
5546 * must check if the name starts with a slash and call this routine. It is
5547 * going to fast forward across the spurious slashes and set the state up for
5550 static int __noinline
5551 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5553 struct nameidata *ndp;
5554 struct componentname *cnp;
5559 MPASS(*(cnp->cn_nameptr) == '/');
5562 cache_fpl_pathlen_dec(fpl);
5563 } while (*(cnp->cn_nameptr) == '/');
5566 * Go back to one slash so that cache_fplookup_parse_advance has
5567 * something to skip.
5570 cache_fpl_pathlen_inc(fpl);
5573 * cache_fplookup_parse_advance starts from ndp->ni_next
5575 ndp->ni_next = cnp->cn_nameptr;
5578 * See cache_fplookup_dot.
5580 fpl->tvp = fpl->dvp;
5581 fpl->tvp_seqc = fpl->dvp_seqc;
5587 * Handle trailing slashes (e.g., "foo/").
5589 * If a trailing slash is found the terminal vnode must be a directory.
5590 * Regular lookup shortens the path by nulifying the first trailing slash and
5591 * sets the TRAILINGSLASH flag to denote this took place. There are several
5592 * checks on it performed later.
5594 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5595 * manner relying on an invariant that a non-directory vnode will get a miss.
5596 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5598 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5599 * and denotes this is the last path component, which avoids looping back.
5601 * Only plain lookups are supported for now to restrict corner cases to handle.
5603 static int __noinline
5604 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5609 struct nameidata *ndp;
5610 struct componentname *cnp;
5611 struct namecache *ncp;
5613 char *cn_nameptr_orig, *cn_nameptr_slash;
5620 tvp_seqc = fpl->tvp_seqc;
5622 MPASS(fpl->dvp == fpl->tvp);
5623 KASSERT(cache_fpl_istrailingslash(fpl),
5624 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5626 KASSERT(cnp->cn_nameptr[0] == '\0',
5627 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5629 KASSERT(cnp->cn_namelen == 0,
5630 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5632 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5634 if (cnp->cn_nameiop != LOOKUP) {
5635 return (cache_fpl_aborted(fpl));
5638 if (__predict_false(tvp->v_type != VDIR)) {
5639 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5640 return (cache_fpl_aborted(fpl));
5642 cache_fpl_smr_exit(fpl);
5643 return (cache_fpl_handled_error(fpl, ENOTDIR));
5647 * Denote the last component.
5649 ndp->ni_next = &cnp->cn_nameptr[0];
5650 MPASS(cache_fpl_islastcn(ndp));
5653 * Unwind trailing slashes.
5655 cn_nameptr_orig = cnp->cn_nameptr;
5656 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5658 if (cnp->cn_nameptr[0] != '/') {
5664 * Unwind to the beginning of the path component.
5666 * Note the path may or may not have started with a slash.
5668 cn_nameptr_slash = cnp->cn_nameptr;
5669 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5671 if (cnp->cn_nameptr[0] == '/') {
5675 if (cnp->cn_nameptr[0] == '/') {
5679 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5680 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5681 cache_fpl_checkpoint(fpl);
5684 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5685 if (ni_pathlen != fpl->debug.ni_pathlen) {
5686 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5687 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5688 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5693 * If this was a "./" lookup the parent directory is already correct.
5695 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5700 * Otherwise we need to look it up.
5703 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5704 if (__predict_false(ncp == NULL)) {
5705 return (cache_fpl_aborted(fpl));
5707 nc_flag = atomic_load_char(&ncp->nc_flag);
5708 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5709 return (cache_fpl_aborted(fpl));
5711 fpl->dvp = ncp->nc_dvp;
5712 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5713 if (seqc_in_modify(fpl->dvp_seqc)) {
5714 return (cache_fpl_aborted(fpl));
5720 * See the API contract for VOP_FPLOOKUP_VEXEC.
5722 static int __noinline
5723 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5725 struct componentname *cnp;
5731 dvp_seqc = fpl->dvp_seqc;
5734 * TODO: Due to ignoring trailing slashes lookup will perform a
5735 * permission check on the last dir when it should not be doing it. It
5736 * may fail, but said failure should be ignored. It is possible to fix
5737 * it up fully without resorting to regular lookup, but for now just
5740 if (cache_fpl_istrailingslash(fpl)) {
5741 return (cache_fpl_aborted(fpl));
5745 * Hack: delayed degenerate path checking.
5747 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5748 return (cache_fplookup_degenerate(fpl));
5752 * Hack: delayed name len checking.
5754 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5755 cache_fpl_smr_exit(fpl);
5756 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5760 * Hack: they may be looking up foo/bar, where foo is not a directory.
5761 * In such a case we need to return ENOTDIR, but we may happen to get
5762 * here with a different error.
5764 if (dvp->v_type != VDIR) {
5769 * Hack: handle O_SEARCH.
5771 * Open Group Base Specifications Issue 7, 2018 edition states:
5773 * If the access mode of the open file description associated with the
5774 * file descriptor is not O_SEARCH, the function shall check whether
5775 * directory searches are permitted using the current permissions of
5776 * the directory underlying the file descriptor. If the access mode is
5777 * O_SEARCH, the function shall not perform the check.
5780 * Regular lookup tests for the NOEXECCHECK flag for every path
5781 * component to decide whether to do the permission check. However,
5782 * since most lookups never have the flag (and when they do it is only
5783 * present for the first path component), lockless lookup only acts on
5784 * it if there is a permission problem. Here the flag is represented
5785 * with a boolean so that we don't have to clear it on the way out.
5787 * For simplicity this always aborts.
5788 * TODO: check if this is the first lookup and ignore the permission
5789 * problem. Note the flag has to survive fallback (if it happens to be
5793 return (cache_fpl_aborted(fpl));
5798 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5799 error = cache_fpl_aborted(fpl);
5801 cache_fpl_partial(fpl);
5805 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5806 error = cache_fpl_aborted(fpl);
5808 cache_fpl_smr_exit(fpl);
5809 cache_fpl_handled_error(fpl, error);
5817 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
5819 struct nameidata *ndp;
5820 struct componentname *cnp;
5827 cache_fpl_checkpoint(fpl);
5830 * The vnode at hand is almost always stable, skip checking for it.
5831 * Worst case this postpones the check towards the end of the iteration
5835 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
5837 mp = atomic_load_ptr(&dvp->v_mount);
5838 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
5839 return (cache_fpl_aborted(fpl));
5842 MPASS(fpl->tvp == NULL);
5845 cache_fplookup_parse(fpl);
5847 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
5848 if (__predict_false(error != 0)) {
5849 error = cache_fplookup_failed_vexec(fpl, error);
5853 error = cache_fplookup_next(fpl);
5854 if (__predict_false(cache_fpl_terminated(fpl))) {
5858 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
5860 if (fpl->tvp->v_type == VLNK) {
5861 error = cache_fplookup_symlink(fpl);
5862 if (cache_fpl_terminated(fpl)) {
5866 if (cache_fpl_islastcn(ndp)) {
5867 error = cache_fplookup_final(fpl);
5871 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
5872 error = cache_fpl_aborted(fpl);
5876 fpl->dvp = fpl->tvp;
5877 fpl->dvp_seqc = fpl->tvp_seqc;
5878 cache_fplookup_parse_advance(fpl);
5881 cache_fpl_checkpoint(fpl);
5888 * Fast path lookup protected with SMR and sequence counters.
5890 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
5892 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
5895 * Traditional vnode lookup conceptually looks like this:
5901 * vn_unlock(current);
5908 * Each jump to the next vnode is safe memory-wise and atomic with respect to
5909 * any modifications thanks to holding respective locks.
5911 * The same guarantee can be provided with a combination of safe memory
5912 * reclamation and sequence counters instead. If all operations which affect
5913 * the relationship between the current vnode and the one we are looking for
5914 * also modify the counter, we can verify whether all the conditions held as
5915 * we made the jump. This includes things like permissions, mount points etc.
5916 * Counter modification is provided by enclosing relevant places in
5917 * vn_seqc_write_begin()/end() calls.
5919 * Thus this translates to:
5922 * dvp_seqc = seqc_read_any(dvp);
5923 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
5927 * tvp_seqc = seqc_read_any(tvp);
5928 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
5930 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
5932 * dvp = tvp; // we know nothing of importance has changed
5933 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
5937 * vget(); // secure the vnode
5938 * if (!seqc_consistent(tvp, tvp_seqc) // final check
5940 * // at this point we know nothing has changed for any parent<->child pair
5941 * // as they were crossed during the lookup, meaning we matched the guarantee
5942 * // of the locked variant
5945 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
5946 * - they are called while within vfs_smr protection which they must never exit
5947 * - EAGAIN can be returned to denote checking could not be performed, it is
5948 * always valid to return it
5949 * - if the sequence counter has not changed the result must be valid
5950 * - if the sequence counter has changed both false positives and false negatives
5951 * are permitted (since the result will be rejected later)
5952 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
5954 * Caveats to watch out for:
5955 * - vnodes are passed unlocked and unreferenced with nothing stopping
5956 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
5957 * to use atomic_load_ptr to fetch it.
5958 * - the aforementioned object can also get freed, meaning absent other means it
5959 * should be protected with vfs_smr
5960 * - either safely checking permissions as they are modified or guaranteeing
5961 * their stability is left to the routine
5964 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
5967 struct cache_fpl fpl;
5970 struct componentname *cnp;
5973 fpl.status = CACHE_FPL_STATUS_UNSET;
5976 fpl.cnp = cnp = &ndp->ni_cnd;
5977 MPASS(ndp->ni_lcf == 0);
5978 MPASS(curthread == cnp->cn_thread);
5979 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
5980 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
5982 if ((cnp->cn_flags & SAVESTART) != 0) {
5983 MPASS(cnp->cn_nameiop != LOOKUP);
5985 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
5987 if (__predict_false(!cache_can_fplookup(&fpl))) {
5988 *status = fpl.status;
5989 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
5990 return (EOPNOTSUPP);
5993 cache_fpl_checkpoint_outer(&fpl);
5995 cache_fpl_smr_enter_initial(&fpl);
5997 fpl.debug.ni_pathlen = ndp->ni_pathlen;
5999 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6000 fpl.fsearch = false;
6001 fpl.savename = (cnp->cn_flags & SAVENAME) != 0;
6002 fpl.tvp = NULL; /* for degenerate path handling */
6004 pwd = pwd_get_smr();
6006 ndp->ni_rootdir = pwd->pwd_rdir;
6007 ndp->ni_topdir = pwd->pwd_jdir;
6009 if (cnp->cn_pnbuf[0] == '/') {
6010 dvp = cache_fpl_handle_root(&fpl);
6011 MPASS(ndp->ni_resflags == 0);
6012 ndp->ni_resflags = NIRES_ABS;
6014 if (ndp->ni_dirfd == AT_FDCWD) {
6015 dvp = pwd->pwd_cdir;
6017 error = cache_fplookup_dirfd(&fpl, &dvp);
6018 if (__predict_false(error != 0)) {
6024 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6025 error = cache_fplookup_impl(dvp, &fpl);
6027 cache_fpl_smr_assert_not_entered(&fpl);
6028 cache_fpl_assert_status(&fpl);
6029 *status = fpl.status;
6030 if (SDT_PROBES_ENABLED()) {
6031 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6032 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6033 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6037 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6038 MPASS(error != CACHE_FPL_FAILED);
6040 MPASS(fpl.dvp == NULL);
6041 MPASS(fpl.tvp == NULL);
6042 MPASS(fpl.savename == false);
6044 ndp->ni_dvp = fpl.dvp;
6045 ndp->ni_vp = fpl.tvp;
6047 cnp->cn_flags |= HASBUF;
6049 cache_fpl_cleanup_cnp(cnp);