2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993, 1995
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Poul-Henning Kamp of the FreeBSD Project.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
41 #include "opt_ktrace.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/capsicum.h>
46 #include <sys/counter.h>
47 #include <sys/filedesc.h>
48 #include <sys/fnv_hash.h>
49 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/fcntl.h>
55 #include <sys/mount.h>
56 #include <sys/namei.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysproto.h>
65 #include <sys/vnode.h>
68 #include <sys/ktrace.h>
71 #include <machine/_inttypes.h>
74 #include <sys/capsicum.h>
76 #include <security/audit/audit.h>
77 #include <security/mac/mac_framework.h>
86 * High level overview of name caching in the VFS layer.
88 * Originally caching was implemented as part of UFS, later extracted to allow
89 * use by other filesystems. A decision was made to make it optional and
90 * completely detached from the rest of the kernel, which comes with limitations
91 * outlined near the end of this comment block.
93 * This fundamental choice needs to be revisited. In the meantime, the current
94 * state is described below. Significance of all notable routines is explained
95 * in comments placed above their implementation. Scattered thoroughout the
96 * file are TODO comments indicating shortcomings which can be fixed without
97 * reworking everything (most of the fixes will likely be reusable). Various
98 * details are omitted from this explanation to not clutter the overview, they
99 * have to be checked by reading the code and associated commentary.
101 * Keep in mind that it's individual path components which are cached, not full
102 * paths. That is, for a fully cached path "foo/bar/baz" there are 3 entries,
105 * I. Data organization
107 * Entries are described by "struct namecache" objects and stored in a hash
108 * table. See cache_get_hash for more information.
110 * "struct vnode" contains pointers to source entries (names which can be found
111 * when traversing through said vnode), destination entries (names of that
112 * vnode (see "Limitations" for a breakdown on the subject) and a pointer to
115 * The (directory vnode; name) tuple reliably determines the target entry if
118 * Since there are no small locks at this time (all are 32 bytes in size on
119 * LP64), the code works around the problem by introducing lock arrays to
120 * protect hash buckets and vnode lists.
122 * II. Filesystem integration
124 * Filesystems participating in name caching do the following:
125 * - set vop_lookup routine to vfs_cache_lookup
126 * - set vop_cachedlookup to whatever can perform the lookup if the above fails
127 * - if they support lockless lookup (see below), vop_fplookup_vexec and
128 * vop_fplookup_symlink are set along with the MNTK_FPLOOKUP flag on the
130 * - call cache_purge or cache_vop_* routines to eliminate stale entries as
132 * - call cache_enter to add entries depending on the MAKEENTRY flag
134 * With the above in mind, there are 2 entry points when doing lookups:
135 * - ... -> namei -> cache_fplookup -- this is the default
136 * - ... -> VOP_LOOKUP -> vfs_cache_lookup -- normally only called by namei
137 * should the above fail
139 * Example code flow how an entry is added:
140 * ... -> namei -> cache_fplookup -> cache_fplookup_noentry -> VOP_LOOKUP ->
141 * vfs_cache_lookup -> VOP_CACHEDLOOKUP -> ufs_lookup_ino -> cache_enter
143 * III. Performance considerations
145 * For lockless case forward lookup avoids any writes to shared areas apart
146 * from the terminal path component. In other words non-modifying lookups of
147 * different files don't suffer any scalability problems in the namecache.
148 * Looking up the same file is limited by VFS and goes beyond the scope of this
151 * At least on amd64 the single-threaded bottleneck for long paths is hashing
152 * (see cache_get_hash). There are cases where the code issues acquire fence
153 * multiple times, they can be combined on architectures which suffer from it.
155 * For locked case each encountered vnode has to be referenced and locked in
156 * order to be handed out to the caller (normally that's namei). This
157 * introduces significant hit single-threaded and serialization multi-threaded.
159 * Reverse lookup (e.g., "getcwd") fully scales provided it is fully cached --
160 * avoids any writes to shared areas to any components.
162 * Unrelated insertions are partially serialized on updating the global entry
163 * counter and possibly serialized on colliding bucket or vnode locks.
167 * Note not everything has an explicit dtrace probe nor it should have, thus
168 * some of the one-liners below depend on implementation details.
172 * # Check what lookups failed to be handled in a lockless manner. Column 1 is
173 * # line number, column 2 is status code (see cache_fpl_status)
174 * dtrace -n 'vfs:fplookup:lookup:done { @[arg1, arg2] = count(); }'
176 * # Lengths of names added by binary name
177 * dtrace -n 'fbt::cache_enter_time:entry { @[execname] = quantize(args[2]->cn_namelen); }'
179 * # Same as above but only those which exceed 64 characters
180 * dtrace -n 'fbt::cache_enter_time:entry /args[2]->cn_namelen > 64/ { @[execname] = quantize(args[2]->cn_namelen); }'
182 * # Who is performing lookups with spurious slashes (e.g., "foo//bar") and what
184 * dtrace -n 'fbt::cache_fplookup_skip_slashes:entry { @[execname, stringof(args[0]->cnp->cn_pnbuf)] = count(); }'
186 * V. Limitations and implementation defects
188 * - since it is possible there is no entry for an open file, tools like
189 * "procstat" may fail to resolve fd -> vnode -> path to anything
190 * - even if a filesystem adds an entry, it may get purged (e.g., due to memory
191 * shortage) in which case the above problem applies
192 * - hardlinks are not tracked, thus if a vnode is reachable in more than one
193 * way, resolving a name may return a different path than the one used to
194 * open it (even if said path is still valid)
195 * - by default entries are not added for newly created files
196 * - adding an entry may need to evict negative entry first, which happens in 2
197 * distinct places (evicting on lookup, adding in a later VOP) making it
198 * impossible to simply reuse it
199 * - there is a simple scheme to evict negative entries as the cache is approaching
200 * its capacity, but it is very unclear if doing so is a good idea to begin with
201 * - vnodes are subject to being recycled even if target inode is left in memory,
202 * which loses the name cache entries when it perhaps should not. in case of tmpfs
203 * names get duplicated -- kept by filesystem itself and namecache separately
204 * - struct namecache has a fixed size and comes in 2 variants, often wasting space.
205 * now hard to replace with malloc due to dependence on SMR.
206 * - lack of better integration with the kernel also turns nullfs into a layered
207 * filesystem instead of something which can take advantage of caching
210 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
213 SDT_PROVIDER_DECLARE(vfs);
214 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
216 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
218 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
220 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
222 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
223 "struct namecache *", "int", "int");
224 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
225 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
226 "char *", "struct vnode *");
227 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
228 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
229 "struct vnode *", "char *");
230 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
232 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
233 "struct vnode *", "char *");
234 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
236 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
237 "struct componentname *");
238 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
239 "struct componentname *");
240 SDT_PROBE_DEFINE3(vfs, namecache, purge, done, "struct vnode *", "size_t", "size_t");
241 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
242 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
243 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
244 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
246 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
248 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
250 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
252 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
253 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
254 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
256 static char __read_frequently cache_fast_lookup_enabled = true;
259 * This structure describes the elements in the cache of recent
260 * names looked up by namei.
266 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
267 "the state must fit in a union with a pointer without growing it");
270 LIST_ENTRY(namecache) nc_src; /* source vnode list */
271 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
272 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
273 struct vnode *nc_dvp; /* vnode of parent of name */
275 struct vnode *nu_vp; /* vnode the name refers to */
276 struct negstate nu_neg;/* negative entry state */
278 u_char nc_flag; /* flag bits */
279 u_char nc_nlen; /* length of name */
280 char nc_name[0]; /* segment name + nul */
284 * struct namecache_ts repeats struct namecache layout up to the
286 * struct namecache_ts is used in place of struct namecache when time(s) need
287 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
288 * both a non-dotdot directory name plus dotdot for the directory's
291 * See below for alignment requirement.
293 struct namecache_ts {
294 struct timespec nc_time; /* timespec provided by fs */
295 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
296 int nc_ticks; /* ticks value when entry was added */
298 struct namecache nc_nc;
301 TAILQ_HEAD(cache_freebatch, namecache);
304 * At least mips n32 performs 64-bit accesses to timespec as found
305 * in namecache_ts and requires them to be aligned. Since others
306 * may be in the same spot suffer a little bit and enforce the
307 * alignment for everyone. Note this is a nop for 64-bit platforms.
309 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
312 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
313 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
314 * smaller and the value was bumped to retain the total size, but it
315 * was never re-evaluated for suitability. A simple test counting
316 * lengths during package building shows that the value of 45 covers
317 * about 86% of all added entries, reaching 99% at 65.
319 * Regardless of the above, use of dedicated zones instead of malloc may be
320 * inducing additional waste. This may be hard to address as said zones are
321 * tied to VFS SMR. Even if retaining them, the current split should be
325 #define CACHE_PATH_CUTOFF 45
326 #define CACHE_LARGE_PAD 6
328 #define CACHE_PATH_CUTOFF 41
329 #define CACHE_LARGE_PAD 2
332 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
333 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
334 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
335 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
337 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
338 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
339 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
340 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
342 #define nc_vp n_un.nu_vp
343 #define nc_neg n_un.nu_neg
346 * Flags in namecache.nc_flag
348 #define NCF_WHITE 0x01
349 #define NCF_ISDOTDOT 0x02
352 #define NCF_DVDROP 0x10
353 #define NCF_NEGATIVE 0x20
354 #define NCF_INVALID 0x40
358 * Flags in negstate.neg_flag
362 static bool cache_neg_evict_cond(u_long lnumcache);
365 * Mark an entry as invalid.
367 * This is called before it starts getting deconstructed.
370 cache_ncp_invalidate(struct namecache *ncp)
373 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
374 ("%s: entry %p already invalid", __func__, ncp));
375 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
376 atomic_thread_fence_rel();
380 * Check whether the entry can be safely used.
382 * All places which elide locks are supposed to call this after they are
383 * done with reading from an entry.
385 #define cache_ncp_canuse(ncp) ({ \
386 struct namecache *_ncp = (ncp); \
389 atomic_thread_fence_acq(); \
390 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
391 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0); \
395 * Like the above but also checks NCF_WHITE.
397 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
398 struct namecache *_ncp = (ncp); \
401 atomic_thread_fence_acq(); \
402 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
403 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
408 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
409 "Name cache parameters");
411 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
412 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
413 "Total namecache capacity");
415 u_int ncsizefactor = 2;
416 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
417 "Size factor for namecache");
419 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
420 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
421 "Ratio of negative namecache entries");
424 * Negative entry % of namecache capacity above which automatic eviction is allowed.
426 * Check cache_neg_evict_cond for details.
428 static u_int ncnegminpct = 3;
430 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
431 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
432 "Negative entry count above which automatic eviction is allowed");
435 * Structures associated with name caching.
437 #define NCHHASH(hash) \
438 (&nchashtbl[(hash) & nchash])
439 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
440 static u_long __read_mostly nchash; /* size of hash table */
441 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
442 "Size of namecache hash table");
443 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
444 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
446 struct nchstats nchstats; /* cache effectiveness statistics */
448 static bool __read_mostly cache_rename_add = true;
449 SYSCTL_BOOL(_vfs, OID_AUTO, cache_rename_add, CTLFLAG_RW,
450 &cache_rename_add, 0, "");
452 static u_int __exclusive_cache_line neg_cycle;
455 #define numneglists (ncneghash + 1)
458 struct mtx nl_evict_lock;
459 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
460 TAILQ_HEAD(, namecache) nl_list;
461 TAILQ_HEAD(, namecache) nl_hotlist;
463 } __aligned(CACHE_LINE_SIZE);
465 static struct neglist neglists[numneglists];
467 static inline struct neglist *
468 NCP2NEGLIST(struct namecache *ncp)
471 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
474 static inline struct negstate *
475 NCP2NEGSTATE(struct namecache *ncp)
478 MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
479 return (&ncp->nc_neg);
482 #define numbucketlocks (ncbuckethash + 1)
483 static u_int __read_mostly ncbuckethash;
484 static struct mtx_padalign __read_mostly *bucketlocks;
485 #define HASH2BUCKETLOCK(hash) \
486 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
488 #define numvnodelocks (ncvnodehash + 1)
489 static u_int __read_mostly ncvnodehash;
490 static struct mtx __read_mostly *vnodelocks;
491 static inline struct mtx *
492 VP2VNODELOCK(struct vnode *vp)
495 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
499 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
501 struct namecache_ts *ncp_ts;
503 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
504 (tsp == NULL && ticksp == NULL),
510 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
511 *tsp = ncp_ts->nc_time;
512 *ticksp = ncp_ts->nc_ticks;
516 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
517 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
518 "VFS namecache enabled");
521 /* Export size information to userland */
522 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
523 sizeof(struct namecache), "sizeof(struct namecache)");
526 * The new name cache statistics
528 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
529 "Name cache statistics");
531 #define STATNODE_ULONG(name, varname, descr) \
532 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
533 #define STATNODE_COUNTER(name, varname, descr) \
534 static COUNTER_U64_DEFINE_EARLY(varname); \
535 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
537 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
538 STATNODE_ULONG(count, numcache, "Number of cache entries");
539 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
540 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
541 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
542 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
543 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
544 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
545 STATNODE_COUNTER(posszaps, numposzaps,
546 "Number of cache hits (positive) we do not want to cache");
547 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
548 STATNODE_COUNTER(negzaps, numnegzaps,
549 "Number of cache hits (negative) we do not want to cache");
550 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
551 /* These count for vn_getcwd(), too. */
552 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
553 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
554 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
555 "Number of fullpath search errors (VOP_VPTOCNP failures)");
556 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
557 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
558 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
561 * Debug or developer statistics.
563 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
564 "Name cache debugging");
565 #define DEBUGNODE_ULONG(name, varname, descr) \
566 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
567 #define DEBUGNODE_COUNTER(name, varname, descr) \
568 static COUNTER_U64_DEFINE_EARLY(varname); \
569 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
571 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
572 "Number of successful removals after relocking");
573 static long zap_bucket_fail;
574 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
575 static long zap_bucket_fail2;
576 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
577 static long cache_lock_vnodes_cel_3_failures;
578 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
579 "Number of times 3-way vnode locking failed");
581 static void cache_zap_locked(struct namecache *ncp);
582 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
583 char **freebuf, size_t *buflen);
584 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
585 char **retbuf, size_t *buflen, size_t addend);
586 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
587 char **retbuf, size_t *buflen);
588 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
589 char **retbuf, size_t *len, size_t addend);
591 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
594 cache_assert_vlp_locked(struct mtx *vlp)
598 mtx_assert(vlp, MA_OWNED);
602 cache_assert_vnode_locked(struct vnode *vp)
606 vlp = VP2VNODELOCK(vp);
607 cache_assert_vlp_locked(vlp);
611 * Directory vnodes with entries are held for two reasons:
612 * 1. make them less of a target for reclamation in vnlru
613 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
615 * It will be feasible to stop doing it altogether if all filesystems start
616 * supporting lockless lookup.
619 cache_hold_vnode(struct vnode *vp)
622 cache_assert_vnode_locked(vp);
623 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
625 counter_u64_add(numcachehv, 1);
629 cache_drop_vnode(struct vnode *vp)
633 * Called after all locks are dropped, meaning we can't assert
634 * on the state of v_cache_src.
637 counter_u64_add(numcachehv, -1);
643 static uma_zone_t __read_mostly cache_zone_small;
644 static uma_zone_t __read_mostly cache_zone_small_ts;
645 static uma_zone_t __read_mostly cache_zone_large;
646 static uma_zone_t __read_mostly cache_zone_large_ts;
649 cache_symlink_alloc(size_t size, int flags)
652 if (size < CACHE_ZONE_SMALL_SIZE) {
653 return (uma_zalloc_smr(cache_zone_small, flags));
655 if (size < CACHE_ZONE_LARGE_SIZE) {
656 return (uma_zalloc_smr(cache_zone_large, flags));
658 counter_u64_add(symlinktoobig, 1);
659 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
664 cache_symlink_free(char *string, size_t size)
667 MPASS(string != NULL);
668 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
669 ("%s: size %zu too big", __func__, size));
671 if (size < CACHE_ZONE_SMALL_SIZE) {
672 uma_zfree_smr(cache_zone_small, string);
675 if (size < CACHE_ZONE_LARGE_SIZE) {
676 uma_zfree_smr(cache_zone_large, string);
679 __assert_unreachable();
682 static struct namecache *
683 cache_alloc_uma(int len, bool ts)
685 struct namecache_ts *ncp_ts;
686 struct namecache *ncp;
688 if (__predict_false(ts)) {
689 if (len <= CACHE_PATH_CUTOFF)
690 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
692 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
693 ncp = &ncp_ts->nc_nc;
695 if (len <= CACHE_PATH_CUTOFF)
696 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
698 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
704 cache_free_uma(struct namecache *ncp)
706 struct namecache_ts *ncp_ts;
708 if (__predict_false(ncp->nc_flag & NCF_TS)) {
709 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
710 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
711 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
713 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
715 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
716 uma_zfree_smr(cache_zone_small, ncp);
718 uma_zfree_smr(cache_zone_large, ncp);
722 static struct namecache *
723 cache_alloc(int len, bool ts)
728 * Avoid blowout in namecache entries.
731 * 1. filesystems may end up trying to add an already existing entry
732 * (for example this can happen after a cache miss during concurrent
733 * lookup), in which case we will call cache_neg_evict despite not
735 * 2. the routine may fail to free anything and no provisions are made
736 * to make it try harder (see the inside for failure modes)
737 * 3. it only ever looks at negative entries.
739 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
740 if (cache_neg_evict_cond(lnumcache)) {
741 lnumcache = atomic_load_long(&numcache);
743 if (__predict_false(lnumcache >= ncsize)) {
744 atomic_subtract_long(&numcache, 1);
745 counter_u64_add(numdrops, 1);
748 return (cache_alloc_uma(len, ts));
752 cache_free(struct namecache *ncp)
756 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
757 cache_drop_vnode(ncp->nc_dvp);
760 atomic_subtract_long(&numcache, 1);
764 cache_free_batch(struct cache_freebatch *batch)
766 struct namecache *ncp, *nnp;
770 if (TAILQ_EMPTY(batch))
772 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
773 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
774 cache_drop_vnode(ncp->nc_dvp);
779 atomic_subtract_long(&numcache, i);
781 SDT_PROBE1(vfs, namecache, purge, batch, i);
787 * The code was made to use FNV in 2001 and this choice needs to be revisited.
789 * Short summary of the difficulty:
790 * The longest name which can be inserted is NAME_MAX characters in length (or
791 * 255 at the time of writing this comment), while majority of names used in
792 * practice are significantly shorter (mostly below 10). More importantly
793 * majority of lookups performed find names are even shorter than that.
795 * This poses a problem where hashes which do better than FNV past word size
796 * (or so) tend to come with additional overhead when finalizing the result,
797 * making them noticeably slower for the most commonly used range.
799 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
801 * When looking it up the most time consuming part by a large margin (at least
802 * on amd64) is hashing. Replacing FNV with something which pessimizes short
803 * input would make the slowest part stand out even more.
807 * TODO: With the value stored we can do better than computing the hash based
811 cache_prehash(struct vnode *vp)
814 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
818 cache_get_hash(char *name, u_char len, struct vnode *dvp)
821 return (fnv_32_buf(name, len, dvp->v_nchash));
825 cache_get_hash_iter_start(struct vnode *dvp)
828 return (dvp->v_nchash);
832 cache_get_hash_iter(char c, uint32_t hash)
835 return (fnv_32_buf(&c, 1, hash));
839 cache_get_hash_iter_finish(uint32_t hash)
845 static inline struct nchashhead *
846 NCP2BUCKET(struct namecache *ncp)
850 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
851 return (NCHHASH(hash));
854 static inline struct mtx *
855 NCP2BUCKETLOCK(struct namecache *ncp)
859 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
860 return (HASH2BUCKETLOCK(hash));
865 cache_assert_bucket_locked(struct namecache *ncp)
869 blp = NCP2BUCKETLOCK(ncp);
870 mtx_assert(blp, MA_OWNED);
874 cache_assert_bucket_unlocked(struct namecache *ncp)
878 blp = NCP2BUCKETLOCK(ncp);
879 mtx_assert(blp, MA_NOTOWNED);
882 #define cache_assert_bucket_locked(x) do { } while (0)
883 #define cache_assert_bucket_unlocked(x) do { } while (0)
886 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
888 _cache_sort_vnodes(void **p1, void **p2)
892 MPASS(*p1 != NULL || *p2 != NULL);
902 cache_lock_all_buckets(void)
906 for (i = 0; i < numbucketlocks; i++)
907 mtx_lock(&bucketlocks[i]);
911 cache_unlock_all_buckets(void)
915 for (i = 0; i < numbucketlocks; i++)
916 mtx_unlock(&bucketlocks[i]);
920 cache_lock_all_vnodes(void)
924 for (i = 0; i < numvnodelocks; i++)
925 mtx_lock(&vnodelocks[i]);
929 cache_unlock_all_vnodes(void)
933 for (i = 0; i < numvnodelocks; i++)
934 mtx_unlock(&vnodelocks[i]);
938 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
941 cache_sort_vnodes(&vlp1, &vlp2);
944 if (!mtx_trylock(vlp1))
947 if (!mtx_trylock(vlp2)) {
957 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
960 MPASS(vlp1 != NULL || vlp2 != NULL);
970 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
973 MPASS(vlp1 != NULL || vlp2 != NULL);
982 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
984 struct nchstats snap;
986 if (req->oldptr == NULL)
987 return (SYSCTL_OUT(req, 0, sizeof(snap)));
990 snap.ncs_goodhits = counter_u64_fetch(numposhits);
991 snap.ncs_neghits = counter_u64_fetch(numneghits);
992 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
993 counter_u64_fetch(numnegzaps);
994 snap.ncs_miss = counter_u64_fetch(nummisszap) +
995 counter_u64_fetch(nummiss);
997 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
999 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
1000 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
1001 "VFS cache effectiveness statistics");
1004 cache_recalc_neg_min(u_int val)
1007 neg_min = (ncsize * val) / 100;
1011 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1017 error = sysctl_handle_int(oidp, &val, 0, req);
1018 if (error != 0 || req->newptr == NULL)
1021 if (val == ncnegminpct)
1023 if (val < 0 || val > 99)
1026 cache_recalc_neg_min(val);
1030 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1031 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1032 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1036 * Grab an atomic snapshot of the name cache hash chain lengths
1038 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1039 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1040 "hash table stats");
1043 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1045 struct nchashhead *ncpp;
1046 struct namecache *ncp;
1047 int i, error, n_nchash, *cntbuf;
1050 n_nchash = nchash + 1; /* nchash is max index, not count */
1051 if (req->oldptr == NULL)
1052 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1053 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1054 cache_lock_all_buckets();
1055 if (n_nchash != nchash + 1) {
1056 cache_unlock_all_buckets();
1057 free(cntbuf, M_TEMP);
1060 /* Scan hash tables counting entries */
1061 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1062 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1064 cache_unlock_all_buckets();
1065 for (error = 0, i = 0; i < n_nchash; i++)
1066 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1068 free(cntbuf, M_TEMP);
1071 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1072 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1073 "nchash chain lengths");
1076 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1079 struct nchashhead *ncpp;
1080 struct namecache *ncp;
1082 int count, maxlength, used, pct;
1085 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1087 cache_lock_all_buckets();
1088 n_nchash = nchash + 1; /* nchash is max index, not count */
1092 /* Scan hash tables for applicable entries */
1093 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1095 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1100 if (maxlength < count)
1103 n_nchash = nchash + 1;
1104 cache_unlock_all_buckets();
1105 pct = (used * 100) / (n_nchash / 100);
1106 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1109 error = SYSCTL_OUT(req, &used, sizeof(used));
1112 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1115 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1120 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1121 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1122 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1126 * Negative entries management
1128 * Various workloads create plenty of negative entries and barely use them
1129 * afterwards. Moreover malicious users can keep performing bogus lookups
1130 * adding even more entries. For example "make tinderbox" as of writing this
1131 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1134 * As such, a rather aggressive eviction method is needed. The currently
1135 * employed method is a placeholder.
1137 * Entries are split over numneglists separate lists, each of which is further
1138 * split into hot and cold entries. Entries get promoted after getting a hit.
1139 * Eviction happens on addition of new entry.
1141 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1142 "Name cache negative entry statistics");
1144 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1145 "Number of negative cache entries");
1147 static COUNTER_U64_DEFINE_EARLY(neg_created);
1148 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1149 "Number of created negative entries");
1151 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1152 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1153 "Number of evicted negative entries");
1155 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1156 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1157 &neg_evict_skipped_empty,
1158 "Number of times evicting failed due to lack of entries");
1160 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1161 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1162 &neg_evict_skipped_missed,
1163 "Number of times evicting failed due to target entry disappearing");
1165 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1166 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1167 &neg_evict_skipped_contended,
1168 "Number of times evicting failed due to contention");
1170 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1171 "Number of cache hits (negative)");
1174 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1179 for (i = 0; i < numneglists; i++)
1180 out += neglists[i].nl_hotnum;
1182 return (SYSCTL_OUT(req, &out, sizeof(out)));
1184 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1185 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1186 "Number of hot negative entries");
1189 cache_neg_init(struct namecache *ncp)
1191 struct negstate *ns;
1193 ncp->nc_flag |= NCF_NEGATIVE;
1194 ns = NCP2NEGSTATE(ncp);
1197 counter_u64_add(neg_created, 1);
1200 #define CACHE_NEG_PROMOTION_THRESH 2
1203 cache_neg_hit_prep(struct namecache *ncp)
1205 struct negstate *ns;
1208 ns = NCP2NEGSTATE(ncp);
1209 n = atomic_load_char(&ns->neg_hit);
1211 if (n >= CACHE_NEG_PROMOTION_THRESH)
1213 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1216 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1220 * Nothing to do here but it is provided for completeness as some
1221 * cache_neg_hit_prep callers may end up returning without even
1222 * trying to promote.
1224 #define cache_neg_hit_abort(ncp) do { } while (0)
1227 cache_neg_hit_finish(struct namecache *ncp)
1230 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1231 counter_u64_add(numneghits, 1);
1235 * Move a negative entry to the hot list.
1238 cache_neg_promote_locked(struct namecache *ncp)
1241 struct negstate *ns;
1243 ns = NCP2NEGSTATE(ncp);
1244 nl = NCP2NEGLIST(ncp);
1245 mtx_assert(&nl->nl_lock, MA_OWNED);
1246 if ((ns->neg_flag & NEG_HOT) == 0) {
1247 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1248 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1250 ns->neg_flag |= NEG_HOT;
1255 * Move a hot negative entry to the cold list.
1258 cache_neg_demote_locked(struct namecache *ncp)
1261 struct negstate *ns;
1263 ns = NCP2NEGSTATE(ncp);
1264 nl = NCP2NEGLIST(ncp);
1265 mtx_assert(&nl->nl_lock, MA_OWNED);
1266 MPASS(ns->neg_flag & NEG_HOT);
1267 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1268 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1270 ns->neg_flag &= ~NEG_HOT;
1271 atomic_store_char(&ns->neg_hit, 0);
1275 * Move a negative entry to the hot list if it matches the lookup.
1277 * We have to take locks, but they may be contended and in the worst
1278 * case we may need to go off CPU. We don't want to spin within the
1279 * smr section and we can't block with it. Exiting the section means
1280 * the found entry could have been evicted. We are going to look it
1284 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1285 struct namecache *oncp, uint32_t hash)
1287 struct namecache *ncp;
1291 nl = NCP2NEGLIST(oncp);
1293 mtx_lock(&nl->nl_lock);
1295 * For hash iteration.
1300 * Avoid all surprises by only succeeding if we got the same entry and
1301 * bailing completely otherwise.
1302 * XXX There are no provisions to keep the vnode around, meaning we may
1303 * end up promoting a negative entry for a *new* vnode and returning
1304 * ENOENT on its account. This is the error we want to return anyway
1305 * and promotion is harmless.
1307 * In particular at this point there can be a new ncp which matches the
1308 * search but hashes to a different neglist.
1310 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1316 * No match to begin with.
1318 if (__predict_false(ncp == NULL)) {
1323 * The newly found entry may be something different...
1325 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1326 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1331 * ... and not even negative.
1333 nc_flag = atomic_load_char(&ncp->nc_flag);
1334 if ((nc_flag & NCF_NEGATIVE) == 0) {
1338 if (!cache_ncp_canuse(ncp)) {
1342 cache_neg_promote_locked(ncp);
1343 cache_neg_hit_finish(ncp);
1345 mtx_unlock(&nl->nl_lock);
1349 mtx_unlock(&nl->nl_lock);
1354 cache_neg_promote(struct namecache *ncp)
1358 nl = NCP2NEGLIST(ncp);
1359 mtx_lock(&nl->nl_lock);
1360 cache_neg_promote_locked(ncp);
1361 mtx_unlock(&nl->nl_lock);
1365 cache_neg_insert(struct namecache *ncp)
1369 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1370 cache_assert_bucket_locked(ncp);
1371 nl = NCP2NEGLIST(ncp);
1372 mtx_lock(&nl->nl_lock);
1373 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1374 mtx_unlock(&nl->nl_lock);
1375 atomic_add_long(&numneg, 1);
1379 cache_neg_remove(struct namecache *ncp)
1382 struct negstate *ns;
1384 cache_assert_bucket_locked(ncp);
1385 nl = NCP2NEGLIST(ncp);
1386 ns = NCP2NEGSTATE(ncp);
1387 mtx_lock(&nl->nl_lock);
1388 if ((ns->neg_flag & NEG_HOT) != 0) {
1389 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1392 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1394 mtx_unlock(&nl->nl_lock);
1395 atomic_subtract_long(&numneg, 1);
1398 static struct neglist *
1399 cache_neg_evict_select_list(void)
1404 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1405 nl = &neglists[c % numneglists];
1406 if (!mtx_trylock(&nl->nl_evict_lock)) {
1407 counter_u64_add(neg_evict_skipped_contended, 1);
1413 static struct namecache *
1414 cache_neg_evict_select_entry(struct neglist *nl)
1416 struct namecache *ncp, *lncp;
1417 struct negstate *ns, *lns;
1420 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1421 mtx_assert(&nl->nl_lock, MA_OWNED);
1422 ncp = TAILQ_FIRST(&nl->nl_list);
1426 lns = NCP2NEGSTATE(lncp);
1427 for (i = 1; i < 4; i++) {
1428 ncp = TAILQ_NEXT(ncp, nc_dst);
1431 ns = NCP2NEGSTATE(ncp);
1432 if (ns->neg_hit < lns->neg_hit) {
1441 cache_neg_evict(void)
1443 struct namecache *ncp, *ncp2;
1452 nl = cache_neg_evict_select_list();
1457 mtx_lock(&nl->nl_lock);
1458 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1460 cache_neg_demote_locked(ncp);
1462 ncp = cache_neg_evict_select_entry(nl);
1464 counter_u64_add(neg_evict_skipped_empty, 1);
1465 mtx_unlock(&nl->nl_lock);
1466 mtx_unlock(&nl->nl_evict_lock);
1469 nlen = ncp->nc_nlen;
1471 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1472 dvlp = VP2VNODELOCK(dvp);
1473 blp = HASH2BUCKETLOCK(hash);
1474 mtx_unlock(&nl->nl_lock);
1475 mtx_unlock(&nl->nl_evict_lock);
1479 * Note that since all locks were dropped above, the entry may be
1480 * gone or reallocated to be something else.
1482 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1483 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1484 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1488 counter_u64_add(neg_evict_skipped_missed, 1);
1492 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1493 MPASS(blp == NCP2BUCKETLOCK(ncp));
1494 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1496 cache_zap_locked(ncp);
1497 counter_u64_add(neg_evicted, 1);
1508 * Maybe evict a negative entry to create more room.
1510 * The ncnegfactor parameter limits what fraction of the total count
1511 * can comprise of negative entries. However, if the cache is just
1512 * warming up this leads to excessive evictions. As such, ncnegminpct
1513 * (recomputed to neg_min) dictates whether the above should be
1516 * Try evicting if the cache is close to full capacity regardless of
1517 * other considerations.
1520 cache_neg_evict_cond(u_long lnumcache)
1524 if (ncsize - 1000 < lnumcache)
1526 lnumneg = atomic_load_long(&numneg);
1527 if (lnumneg < neg_min)
1529 if (lnumneg * ncnegfactor < lnumcache)
1532 return (cache_neg_evict());
1536 * cache_zap_locked():
1538 * Removes a namecache entry from cache, whether it contains an actual
1539 * pointer to a vnode or if it is just a negative cache entry.
1542 cache_zap_locked(struct namecache *ncp)
1544 struct nchashhead *ncpp;
1545 struct vnode *dvp, *vp;
1550 if (!(ncp->nc_flag & NCF_NEGATIVE))
1551 cache_assert_vnode_locked(vp);
1552 cache_assert_vnode_locked(dvp);
1553 cache_assert_bucket_locked(ncp);
1555 cache_ncp_invalidate(ncp);
1557 ncpp = NCP2BUCKET(ncp);
1558 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1559 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1560 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1561 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1562 if (ncp == vp->v_cache_dd) {
1563 atomic_store_ptr(&vp->v_cache_dd, NULL);
1566 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1567 cache_neg_remove(ncp);
1569 if (ncp->nc_flag & NCF_ISDOTDOT) {
1570 if (ncp == dvp->v_cache_dd) {
1571 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1574 LIST_REMOVE(ncp, nc_src);
1575 if (LIST_EMPTY(&dvp->v_cache_src)) {
1576 ncp->nc_flag |= NCF_DVDROP;
1582 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1586 MPASS(ncp->nc_dvp == vp);
1587 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1588 cache_assert_vnode_locked(vp);
1590 blp = NCP2BUCKETLOCK(ncp);
1592 cache_zap_locked(ncp);
1597 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1600 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1603 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1604 cache_assert_vnode_locked(vp);
1606 if (ncp->nc_flag & NCF_NEGATIVE) {
1607 if (*vlpp != NULL) {
1611 cache_zap_negative_locked_vnode_kl(ncp, vp);
1615 pvlp = VP2VNODELOCK(vp);
1616 blp = NCP2BUCKETLOCK(ncp);
1617 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1618 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1620 if (*vlpp == vlp1 || *vlpp == vlp2) {
1624 if (*vlpp != NULL) {
1628 cache_sort_vnodes(&vlp1, &vlp2);
1633 if (!mtx_trylock(vlp1))
1639 cache_zap_locked(ncp);
1641 if (to_unlock != NULL)
1642 mtx_unlock(to_unlock);
1649 MPASS(*vlpp == NULL);
1655 * If trylocking failed we can get here. We know enough to take all needed locks
1656 * in the right order and re-lookup the entry.
1659 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1660 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1663 struct namecache *rncp;
1665 cache_assert_bucket_unlocked(ncp);
1667 cache_sort_vnodes(&dvlp, &vlp);
1668 cache_lock_vnodes(dvlp, vlp);
1670 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1671 if (rncp == ncp && rncp->nc_dvp == dvp &&
1672 rncp->nc_nlen == cnp->cn_namelen &&
1673 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1677 cache_zap_locked(rncp);
1679 cache_unlock_vnodes(dvlp, vlp);
1680 counter_u64_add(zap_bucket_relock_success, 1);
1685 cache_unlock_vnodes(dvlp, vlp);
1689 static int __noinline
1690 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1691 uint32_t hash, struct mtx *blp)
1693 struct mtx *dvlp, *vlp;
1696 cache_assert_bucket_locked(ncp);
1698 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1700 if (!(ncp->nc_flag & NCF_NEGATIVE))
1701 vlp = VP2VNODELOCK(ncp->nc_vp);
1702 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1703 cache_zap_locked(ncp);
1705 cache_unlock_vnodes(dvlp, vlp);
1711 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1714 static __noinline int
1715 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1717 struct namecache *ncp;
1719 struct mtx *dvlp, *dvlp2;
1723 if (cnp->cn_namelen == 2 &&
1724 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1725 dvlp = VP2VNODELOCK(dvp);
1729 ncp = dvp->v_cache_dd;
1734 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1737 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1738 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1740 MPASS(dvp->v_cache_dd == NULL);
1746 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1751 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1755 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1756 blp = HASH2BUCKETLOCK(hash);
1758 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1763 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1764 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1765 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1774 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1775 if (__predict_false(error != 0)) {
1779 counter_u64_add(numposzaps, 1);
1780 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1784 counter_u64_add(nummisszap, 1);
1785 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1789 static int __noinline
1790 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1791 struct timespec *tsp, int *ticksp)
1796 counter_u64_add(dothits, 1);
1797 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1804 * When we lookup "." we still can be asked to lock it
1807 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1808 if (ltype != VOP_ISLOCKED(*vpp)) {
1809 if (ltype == LK_EXCLUSIVE) {
1810 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1811 if (VN_IS_DOOMED((*vpp))) {
1812 /* forced unmount */
1818 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1823 static int __noinline
1824 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1825 struct timespec *tsp, int *ticksp)
1827 struct namecache_ts *ncp_ts;
1828 struct namecache *ncp;
1834 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1836 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1837 cache_remove_cnp(dvp, cnp);
1841 counter_u64_add(dotdothits, 1);
1843 dvlp = VP2VNODELOCK(dvp);
1845 ncp = dvp->v_cache_dd;
1847 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1851 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1852 if (ncp->nc_flag & NCF_NEGATIVE)
1859 goto negative_success;
1860 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1861 cache_out_ts(ncp, tsp, ticksp);
1862 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1863 NCF_DTS && tsp != NULL) {
1864 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1865 *tsp = ncp_ts->nc_dotdottime;
1869 ltype = VOP_ISLOCKED(dvp);
1871 vs = vget_prep(*vpp);
1873 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1874 vn_lock(dvp, ltype | LK_RETRY);
1875 if (VN_IS_DOOMED(dvp)) {
1887 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1888 if (cnp->cn_flags & ISLASTCN) {
1889 counter_u64_add(numnegzaps, 1);
1890 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1897 whiteout = (ncp->nc_flag & NCF_WHITE);
1898 cache_out_ts(ncp, tsp, ticksp);
1899 if (cache_neg_hit_prep(ncp))
1900 cache_neg_promote(ncp);
1902 cache_neg_hit_finish(ncp);
1905 cnp->cn_flags |= ISWHITEOUT;
1910 * Lookup a name in the name cache
1914 * - dvp: Parent directory in which to search.
1915 * - vpp: Return argument. Will contain desired vnode on cache hit.
1916 * - cnp: Parameters of the name search. The most interesting bits of
1917 * the cn_flags field have the following meanings:
1918 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1920 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1921 * - tsp: Return storage for cache timestamp. On a successful (positive
1922 * or negative) lookup, tsp will be filled with any timespec that
1923 * was stored when this cache entry was created. However, it will
1924 * be clear for "." entries.
1925 * - ticks: Return storage for alternate cache timestamp. On a successful
1926 * (positive or negative) lookup, it will contain the ticks value
1927 * that was current when the cache entry was created, unless cnp
1930 * Either both tsp and ticks have to be provided or neither of them.
1934 * - -1: A positive cache hit. vpp will contain the desired vnode.
1935 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1936 * to a forced unmount. vpp will not be modified. If the entry
1937 * is a whiteout, then the ISWHITEOUT flag will be set in
1939 * - 0: A cache miss. vpp will not be modified.
1943 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1944 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1945 * lock is not recursively acquired.
1947 static int __noinline
1948 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1949 struct timespec *tsp, int *ticksp)
1951 struct namecache *ncp;
1958 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1959 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1962 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1963 blp = HASH2BUCKETLOCK(hash);
1966 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1967 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1968 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1972 if (__predict_false(ncp == NULL)) {
1974 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
1975 counter_u64_add(nummiss, 1);
1979 if (ncp->nc_flag & NCF_NEGATIVE)
1980 goto negative_success;
1982 counter_u64_add(numposhits, 1);
1984 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1985 cache_out_ts(ncp, tsp, ticksp);
1987 vs = vget_prep(*vpp);
1989 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1997 * We don't get here with regular lookup apart from corner cases.
1999 if (__predict_true(cnp->cn_nameiop == CREATE)) {
2000 if (cnp->cn_flags & ISLASTCN) {
2001 counter_u64_add(numnegzaps, 1);
2002 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2003 if (__predict_false(error != 0)) {
2012 whiteout = (ncp->nc_flag & NCF_WHITE);
2013 cache_out_ts(ncp, tsp, ticksp);
2014 if (cache_neg_hit_prep(ncp))
2015 cache_neg_promote(ncp);
2017 cache_neg_hit_finish(ncp);
2020 cnp->cn_flags |= ISWHITEOUT;
2025 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2026 struct timespec *tsp, int *ticksp)
2028 struct namecache *ncp;
2032 bool whiteout, neg_promote;
2035 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2038 if (__predict_false(!doingcache)) {
2039 cnp->cn_flags &= ~MAKEENTRY;
2044 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2045 if (cnp->cn_namelen == 1)
2046 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2047 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2048 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2051 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2053 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2054 cache_remove_cnp(dvp, cnp);
2058 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2061 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2062 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2063 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2067 if (__predict_false(ncp == NULL)) {
2069 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2070 counter_u64_add(nummiss, 1);
2074 nc_flag = atomic_load_char(&ncp->nc_flag);
2075 if (nc_flag & NCF_NEGATIVE)
2076 goto negative_success;
2078 counter_u64_add(numposhits, 1);
2080 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2081 cache_out_ts(ncp, tsp, ticksp);
2083 if (!cache_ncp_canuse(ncp)) {
2088 vs = vget_prep_smr(*vpp);
2090 if (__predict_false(vs == VGET_NONE)) {
2094 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2101 if (cnp->cn_nameiop == CREATE) {
2102 if (cnp->cn_flags & ISLASTCN) {
2108 cache_out_ts(ncp, tsp, ticksp);
2109 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2110 neg_promote = cache_neg_hit_prep(ncp);
2111 if (!cache_ncp_canuse(ncp)) {
2112 cache_neg_hit_abort(ncp);
2118 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2121 cache_neg_hit_finish(ncp);
2125 cnp->cn_flags |= ISWHITEOUT;
2128 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2131 struct celockstate {
2135 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2136 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2139 cache_celockstate_init(struct celockstate *cel)
2142 bzero(cel, sizeof(*cel));
2146 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2149 struct mtx *vlp1, *vlp2;
2151 MPASS(cel->vlp[0] == NULL);
2152 MPASS(cel->vlp[1] == NULL);
2153 MPASS(cel->vlp[2] == NULL);
2155 MPASS(vp != NULL || dvp != NULL);
2157 vlp1 = VP2VNODELOCK(vp);
2158 vlp2 = VP2VNODELOCK(dvp);
2159 cache_sort_vnodes(&vlp1, &vlp2);
2170 cache_unlock_vnodes_cel(struct celockstate *cel)
2173 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2175 if (cel->vlp[0] != NULL)
2176 mtx_unlock(cel->vlp[0]);
2177 if (cel->vlp[1] != NULL)
2178 mtx_unlock(cel->vlp[1]);
2179 if (cel->vlp[2] != NULL)
2180 mtx_unlock(cel->vlp[2]);
2184 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2189 cache_assert_vlp_locked(cel->vlp[0]);
2190 cache_assert_vlp_locked(cel->vlp[1]);
2191 MPASS(cel->vlp[2] == NULL);
2194 vlp = VP2VNODELOCK(vp);
2197 if (vlp >= cel->vlp[1]) {
2200 if (mtx_trylock(vlp))
2202 cache_lock_vnodes_cel_3_failures++;
2203 cache_unlock_vnodes_cel(cel);
2204 if (vlp < cel->vlp[0]) {
2206 mtx_lock(cel->vlp[0]);
2207 mtx_lock(cel->vlp[1]);
2209 if (cel->vlp[0] != NULL)
2210 mtx_lock(cel->vlp[0]);
2212 mtx_lock(cel->vlp[1]);
2222 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2226 MPASS(cel->blp[0] == NULL);
2227 MPASS(cel->blp[1] == NULL);
2229 cache_sort_vnodes(&blp1, &blp2);
2240 cache_unlock_buckets_cel(struct celockstate *cel)
2243 if (cel->blp[0] != NULL)
2244 mtx_unlock(cel->blp[0]);
2245 mtx_unlock(cel->blp[1]);
2249 * Lock part of the cache affected by the insertion.
2251 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2252 * However, insertion can result in removal of an old entry. In this
2253 * case we have an additional vnode and bucketlock pair to lock.
2255 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2256 * preserving the locking order (smaller address first).
2259 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2262 struct namecache *ncp;
2263 struct mtx *blps[2];
2266 blps[0] = HASH2BUCKETLOCK(hash);
2269 cache_lock_vnodes_cel(cel, dvp, vp);
2270 if (vp == NULL || vp->v_type != VDIR)
2272 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2275 nc_flag = atomic_load_char(&ncp->nc_flag);
2276 if ((nc_flag & NCF_ISDOTDOT) == 0)
2278 MPASS(ncp->nc_dvp == vp);
2279 blps[1] = NCP2BUCKETLOCK(ncp);
2280 if ((nc_flag & NCF_NEGATIVE) != 0)
2282 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2285 * All vnodes got re-locked. Re-validate the state and if
2286 * nothing changed we are done. Otherwise restart.
2288 if (ncp == vp->v_cache_dd &&
2289 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2290 blps[1] == NCP2BUCKETLOCK(ncp) &&
2291 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2293 cache_unlock_vnodes_cel(cel);
2298 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2302 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2305 struct namecache *ncp;
2306 struct mtx *blps[2];
2309 blps[0] = HASH2BUCKETLOCK(hash);
2312 cache_lock_vnodes_cel(cel, dvp, vp);
2313 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2316 nc_flag = atomic_load_char(&ncp->nc_flag);
2317 if ((nc_flag & NCF_ISDOTDOT) == 0)
2319 MPASS(ncp->nc_dvp == dvp);
2320 blps[1] = NCP2BUCKETLOCK(ncp);
2321 if ((nc_flag & NCF_NEGATIVE) != 0)
2323 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2325 if (ncp == dvp->v_cache_dd &&
2326 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2327 blps[1] == NCP2BUCKETLOCK(ncp) &&
2328 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2330 cache_unlock_vnodes_cel(cel);
2335 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2339 cache_enter_unlock(struct celockstate *cel)
2342 cache_unlock_buckets_cel(cel);
2343 cache_unlock_vnodes_cel(cel);
2346 static void __noinline
2347 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2348 struct componentname *cnp)
2350 struct celockstate cel;
2351 struct namecache *ncp;
2355 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2357 len = cnp->cn_namelen;
2358 cache_celockstate_init(&cel);
2359 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2360 cache_enter_lock_dd(&cel, dvp, vp, hash);
2361 ncp = dvp->v_cache_dd;
2362 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2363 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2364 cache_zap_locked(ncp);
2368 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2369 cache_enter_unlock(&cel);
2375 * Add an entry to the cache.
2378 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2379 struct timespec *tsp, struct timespec *dtsp)
2381 struct celockstate cel;
2382 struct namecache *ncp, *n2, *ndd;
2383 struct namecache_ts *ncp_ts;
2384 struct nchashhead *ncpp;
2389 KASSERT(cnp->cn_namelen <= NAME_MAX,
2390 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2394 * Not everything doing this is weeded out yet.
2396 VNPASS(dvp != vp, dvp);
2398 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2399 VNPASS(dvp->v_type != VNON, dvp);
2401 VNPASS(!VN_IS_DOOMED(vp), vp);
2402 VNPASS(vp->v_type != VNON, vp);
2406 if (__predict_false(!doingcache))
2411 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2412 if (cnp->cn_namelen == 1)
2414 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2415 cache_enter_dotdot_prep(dvp, vp, cnp);
2416 flag = NCF_ISDOTDOT;
2420 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2424 cache_celockstate_init(&cel);
2429 * Calculate the hash key and setup as much of the new
2430 * namecache entry as possible before acquiring the lock.
2432 ncp->nc_flag = flag | NCF_WIP;
2435 cache_neg_init(ncp);
2438 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2439 ncp_ts->nc_time = *tsp;
2440 ncp_ts->nc_ticks = ticks;
2441 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2443 ncp_ts->nc_dotdottime = *dtsp;
2444 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2447 len = ncp->nc_nlen = cnp->cn_namelen;
2448 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2449 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2450 ncp->nc_name[len] = '\0';
2451 cache_enter_lock(&cel, dvp, vp, hash);
2454 * See if this vnode or negative entry is already in the cache
2455 * with this name. This can happen with concurrent lookups of
2456 * the same path name.
2458 ncpp = NCHHASH(hash);
2459 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2460 if (n2->nc_dvp == dvp &&
2461 n2->nc_nlen == cnp->cn_namelen &&
2462 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2463 MPASS(cache_ncp_canuse(n2));
2464 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2466 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2467 __func__, NULL, vp, cnp->cn_nameptr));
2469 KASSERT(n2->nc_vp == vp,
2470 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2471 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2473 * Entries are supposed to be immutable unless in the
2474 * process of getting destroyed. Accommodating for
2475 * changing timestamps is possible but not worth it.
2476 * This should be harmless in terms of correctness, in
2477 * the worst case resulting in an earlier expiration.
2478 * Alternatively, the found entry can be replaced
2481 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2484 KASSERT((n2->nc_flag & NCF_TS) != 0,
2486 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2487 n2_ts->nc_time = ncp_ts->nc_time;
2488 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2490 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2491 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2495 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2497 goto out_unlock_free;
2501 if (flag == NCF_ISDOTDOT) {
2503 * See if we are trying to add .. entry, but some other lookup
2504 * has populated v_cache_dd pointer already.
2506 if (dvp->v_cache_dd != NULL)
2507 goto out_unlock_free;
2508 KASSERT(vp == NULL || vp->v_type == VDIR,
2509 ("wrong vnode type %p", vp));
2510 atomic_thread_fence_rel();
2511 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2515 if (flag != NCF_ISDOTDOT) {
2517 * For this case, the cache entry maps both the
2518 * directory name in it and the name ".." for the
2519 * directory's parent.
2521 if ((ndd = vp->v_cache_dd) != NULL) {
2522 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2523 cache_zap_locked(ndd);
2527 atomic_thread_fence_rel();
2528 atomic_store_ptr(&vp->v_cache_dd, ncp);
2529 } else if (vp->v_type != VDIR) {
2530 if (vp->v_cache_dd != NULL) {
2531 atomic_store_ptr(&vp->v_cache_dd, NULL);
2536 if (flag != NCF_ISDOTDOT) {
2537 if (LIST_EMPTY(&dvp->v_cache_src)) {
2538 cache_hold_vnode(dvp);
2540 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2544 * If the entry is "negative", we place it into the
2545 * "negative" cache queue, otherwise, we place it into the
2546 * destination vnode's cache entries queue.
2549 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2550 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2553 if (cnp->cn_flags & ISWHITEOUT)
2554 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2555 cache_neg_insert(ncp);
2556 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2561 * Insert the new namecache entry into the appropriate chain
2562 * within the cache entries table.
2564 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2566 atomic_thread_fence_rel();
2568 * Mark the entry as fully constructed.
2569 * It is immutable past this point until its removal.
2571 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2573 cache_enter_unlock(&cel);
2578 cache_enter_unlock(&cel);
2584 * A variant of the above accepting flags.
2586 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2588 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2589 * happens to match and it is doing it in an inefficient manner. It was added
2590 * to accomodate NFS which runs into a case where the target for a given name
2591 * may change from under it. Note this does nothing to solve the following
2592 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2593 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2596 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2597 struct timespec *tsp, struct timespec *dtsp, int flags)
2600 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2602 if (flags & VFS_CACHE_DROPOLD)
2603 cache_remove_cnp(dvp, cnp);
2604 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2608 cache_roundup_2(u_int val)
2612 for (res = 1; res <= val; res <<= 1)
2618 static struct nchashhead *
2619 nchinittbl(u_long elements, u_long *hashmask)
2621 struct nchashhead *hashtbl;
2624 hashsize = cache_roundup_2(elements) / 2;
2626 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2627 for (i = 0; i < hashsize; i++)
2628 CK_SLIST_INIT(&hashtbl[i]);
2629 *hashmask = hashsize - 1;
2634 ncfreetbl(struct nchashhead *hashtbl)
2637 free(hashtbl, M_VFSCACHE);
2641 * Name cache initialization, from vfs_init() when we are booting
2644 nchinit(void *dummy __unused)
2648 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2649 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2650 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2651 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2652 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2653 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2654 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2655 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2657 VFS_SMR_ZONE_SET(cache_zone_small);
2658 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2659 VFS_SMR_ZONE_SET(cache_zone_large);
2660 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2662 ncsize = desiredvnodes * ncsizefactor;
2663 cache_recalc_neg_min(ncnegminpct);
2664 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2665 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2666 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2668 if (ncbuckethash > nchash)
2669 ncbuckethash = nchash;
2670 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2672 for (i = 0; i < numbucketlocks; i++)
2673 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2674 ncvnodehash = ncbuckethash;
2675 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2677 for (i = 0; i < numvnodelocks; i++)
2678 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2680 for (i = 0; i < numneglists; i++) {
2681 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2682 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2683 TAILQ_INIT(&neglists[i].nl_list);
2684 TAILQ_INIT(&neglists[i].nl_hotlist);
2687 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2690 cache_vnode_init(struct vnode *vp)
2693 LIST_INIT(&vp->v_cache_src);
2694 TAILQ_INIT(&vp->v_cache_dst);
2695 vp->v_cache_dd = NULL;
2700 * Induce transient cache misses for lockless operation in cache_lookup() by
2701 * using a temporary hash table.
2703 * This will force a fs lookup.
2705 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2706 * to observe all CPUs not performing the lookup.
2709 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2712 MPASS(temphash < nchash);
2714 * Change the size. The new size is smaller and can safely be used
2715 * against the existing table. All lookups which now hash wrong will
2716 * result in a cache miss, which all callers are supposed to know how
2719 atomic_store_long(&nchash, temphash);
2720 atomic_thread_fence_rel();
2721 vfs_smr_synchronize();
2723 * At this point everyone sees the updated hash value, but they still
2724 * see the old table.
2726 atomic_store_ptr(&nchashtbl, temptbl);
2727 atomic_thread_fence_rel();
2728 vfs_smr_synchronize();
2730 * At this point everyone sees the updated table pointer and size pair.
2735 * Set the new hash table.
2737 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2738 * lockless operation in cache_lookup().
2741 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2744 MPASS(nchash < new_hash);
2746 * Change the pointer first. This wont result in out of bounds access
2747 * since the temporary table is guaranteed to be smaller.
2749 atomic_store_ptr(&nchashtbl, new_tbl);
2750 atomic_thread_fence_rel();
2751 vfs_smr_synchronize();
2753 * At this point everyone sees the updated pointer value, but they
2754 * still see the old size.
2756 atomic_store_long(&nchash, new_hash);
2757 atomic_thread_fence_rel();
2758 vfs_smr_synchronize();
2760 * At this point everyone sees the updated table pointer and size pair.
2765 cache_changesize(u_long newmaxvnodes)
2767 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2768 u_long new_nchash, old_nchash, temphash;
2769 struct namecache *ncp;
2774 newncsize = newmaxvnodes * ncsizefactor;
2775 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2776 if (newmaxvnodes < numbucketlocks)
2777 newmaxvnodes = numbucketlocks;
2779 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2780 /* If same hash table size, nothing to do */
2781 if (nchash == new_nchash) {
2782 ncfreetbl(new_nchashtbl);
2786 temptbl = nchinittbl(1, &temphash);
2789 * Move everything from the old hash table to the new table.
2790 * None of the namecache entries in the table can be removed
2791 * because to do so, they have to be removed from the hash table.
2793 cache_lock_all_vnodes();
2794 cache_lock_all_buckets();
2795 old_nchashtbl = nchashtbl;
2796 old_nchash = nchash;
2797 cache_changesize_set_temp(temptbl, temphash);
2798 for (i = 0; i <= old_nchash; i++) {
2799 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2800 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2802 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2803 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2807 cache_recalc_neg_min(ncnegminpct);
2808 cache_changesize_set_new(new_nchashtbl, new_nchash);
2809 cache_unlock_all_buckets();
2810 cache_unlock_all_vnodes();
2811 ncfreetbl(old_nchashtbl);
2816 * Remove all entries from and to a particular vnode.
2819 cache_purge_impl(struct vnode *vp)
2821 struct cache_freebatch batch;
2822 struct namecache *ncp;
2823 struct mtx *vlp, *vlp2;
2826 vlp = VP2VNODELOCK(vp);
2830 while (!LIST_EMPTY(&vp->v_cache_src)) {
2831 ncp = LIST_FIRST(&vp->v_cache_src);
2832 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2834 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2836 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2837 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2838 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2840 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2842 ncp = vp->v_cache_dd;
2844 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2845 ("lost dotdot link"));
2846 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2848 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2850 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2854 cache_free_batch(&batch);
2858 * Opportunistic check to see if there is anything to do.
2861 cache_has_entries(struct vnode *vp)
2864 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2865 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2871 cache_purge(struct vnode *vp)
2874 SDT_PROBE1(vfs, namecache, purge, done, vp);
2875 if (!cache_has_entries(vp))
2877 cache_purge_impl(vp);
2881 * Only to be used by vgone.
2884 cache_purge_vgone(struct vnode *vp)
2888 VNPASS(VN_IS_DOOMED(vp), vp);
2889 if (cache_has_entries(vp)) {
2890 cache_purge_impl(vp);
2895 * Serialize against a potential thread doing cache_purge.
2897 vlp = VP2VNODELOCK(vp);
2898 mtx_wait_unlocked(vlp);
2899 if (cache_has_entries(vp)) {
2900 cache_purge_impl(vp);
2907 * Remove all negative entries for a particular directory vnode.
2910 cache_purge_negative(struct vnode *vp)
2912 struct cache_freebatch batch;
2913 struct namecache *ncp, *nnp;
2916 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2917 if (LIST_EMPTY(&vp->v_cache_src))
2920 vlp = VP2VNODELOCK(vp);
2922 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2923 if (!(ncp->nc_flag & NCF_NEGATIVE))
2925 cache_zap_negative_locked_vnode_kl(ncp, vp);
2926 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2929 cache_free_batch(&batch);
2933 * Entry points for modifying VOP operations.
2936 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2937 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2940 ASSERT_VOP_IN_SEQC(fdvp);
2941 ASSERT_VOP_IN_SEQC(fvp);
2942 ASSERT_VOP_IN_SEQC(tdvp);
2944 ASSERT_VOP_IN_SEQC(tvp);
2949 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2950 ("%s: lingering negative entry", __func__));
2952 cache_remove_cnp(tdvp, tcnp);
2958 * Historically renaming was always purging all revelang entries,
2959 * but that's quite wasteful. In particular turns out that in many cases
2960 * the target file is immediately accessed after rename, inducing a cache
2963 * Recode this to reduce relocking and reuse the existing entry (if any)
2964 * instead of just removing it above and allocating a new one here.
2966 if (cache_rename_add) {
2967 cache_enter(tdvp, fvp, tcnp);
2972 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2975 ASSERT_VOP_IN_SEQC(dvp);
2976 ASSERT_VOP_IN_SEQC(vp);
2982 * Validate that if an entry exists it matches.
2985 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2987 struct namecache *ncp;
2991 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2992 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2994 blp = HASH2BUCKETLOCK(hash);
2996 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2997 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2998 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2999 if (ncp->nc_vp != vp)
3000 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
3001 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3009 * Flush all entries referencing a particular filesystem.
3012 cache_purgevfs(struct mount *mp)
3014 struct vnode *vp, *mvp;
3015 size_t visited, purged;
3017 visited = purged = 0;
3019 * Somewhat wasteful iteration over all vnodes. Would be better to
3020 * support filtering and avoid the interlock to begin with.
3022 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3024 if (!cache_has_entries(vp)) {
3035 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3039 * Perform canonical checks and cache lookup and pass on to filesystem
3040 * through the vop_cachedlookup only if needed.
3044 vfs_cache_lookup(struct vop_lookup_args *ap)
3048 struct vnode **vpp = ap->a_vpp;
3049 struct componentname *cnp = ap->a_cnp;
3050 int flags = cnp->cn_flags;
3055 if (dvp->v_type != VDIR)
3058 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3059 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3062 error = vn_dir_check_exec(dvp, cnp);
3066 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3068 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3074 /* Implementation of the getcwd syscall. */
3076 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3082 buflen = uap->buflen;
3083 if (__predict_false(buflen < 2))
3085 if (buflen > MAXPATHLEN)
3086 buflen = MAXPATHLEN;
3088 buf = uma_zalloc(namei_zone, M_WAITOK);
3089 error = vn_getcwd(buf, &retbuf, &buflen);
3091 error = copyout(retbuf, uap->buf, buflen);
3092 uma_zfree(namei_zone, buf);
3097 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3103 pwd = pwd_get_smr();
3104 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3106 VFS_SMR_ASSERT_NOT_ENTERED();
3108 pwd = pwd_hold(curthread);
3109 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3115 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3122 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3123 size_t size, int flags, enum uio_seg pathseg)
3125 struct nameidata nd;
3126 char *retbuf, *freebuf;
3131 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
3132 pathseg, path, fd, &cap_fstat_rights, td);
3133 if ((error = namei(&nd)) != 0)
3135 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
3137 error = copyout(retbuf, buf, size);
3138 free(freebuf, M_TEMP);
3145 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3148 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3149 uap->flags, UIO_USERSPACE));
3153 * Retrieve the full filesystem path that correspond to a vnode from the name
3154 * cache (if available)
3157 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3164 if (__predict_false(vp == NULL))
3167 buflen = MAXPATHLEN;
3168 buf = malloc(buflen, M_TEMP, M_WAITOK);
3170 pwd = pwd_get_smr();
3171 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3172 VFS_SMR_ASSERT_NOT_ENTERED();
3174 pwd = pwd_hold(curthread);
3175 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3186 * This function is similar to vn_fullpath, but it attempts to lookup the
3187 * pathname relative to the global root mount point. This is required for the
3188 * auditing sub-system, as audited pathnames must be absolute, relative to the
3189 * global root mount point.
3192 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3198 if (__predict_false(vp == NULL))
3200 buflen = MAXPATHLEN;
3201 buf = malloc(buflen, M_TEMP, M_WAITOK);
3203 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3204 VFS_SMR_ASSERT_NOT_ENTERED();
3206 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3215 static struct namecache *
3216 vn_dd_from_dst(struct vnode *vp)
3218 struct namecache *ncp;
3220 cache_assert_vnode_locked(vp);
3221 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3222 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3229 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3232 struct namecache *ncp;
3236 vlp = VP2VNODELOCK(*vp);
3238 ncp = (*vp)->v_cache_dd;
3239 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3240 KASSERT(ncp == vn_dd_from_dst(*vp),
3241 ("%s: mismatch for dd entry (%p != %p)", __func__,
3242 ncp, vn_dd_from_dst(*vp)));
3244 ncp = vn_dd_from_dst(*vp);
3247 if (*buflen < ncp->nc_nlen) {
3250 counter_u64_add(numfullpathfail4, 1);
3252 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3256 *buflen -= ncp->nc_nlen;
3257 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3258 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3267 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3270 vn_lock(*vp, LK_SHARED | LK_RETRY);
3271 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3274 counter_u64_add(numfullpathfail2, 1);
3275 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3280 if (VN_IS_DOOMED(dvp)) {
3281 /* forced unmount */
3284 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3288 * *vp has its use count incremented still.
3295 * Resolve a directory to a pathname.
3297 * The name of the directory can always be found in the namecache or fetched
3298 * from the filesystem. There is also guaranteed to be only one parent, meaning
3299 * we can just follow vnodes up until we find the root.
3301 * The vnode must be referenced.
3304 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3305 size_t *len, size_t addend)
3307 #ifdef KDTRACE_HOOKS
3308 struct vnode *startvp = vp;
3313 bool slash_prefixed;
3315 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3316 VNPASS(vp->v_usecount > 0, vp);
3320 slash_prefixed = true;
3325 slash_prefixed = false;
3330 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3331 counter_u64_add(numfullpathcalls, 1);
3332 while (vp != rdir && vp != rootvnode) {
3334 * The vp vnode must be already fully constructed,
3335 * since it is either found in namecache or obtained
3336 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3337 * without obtaining the vnode lock.
3339 if ((vp->v_vflag & VV_ROOT) != 0) {
3340 vn_lock(vp, LK_RETRY | LK_SHARED);
3343 * With the vnode locked, check for races with
3344 * unmount, forced or not. Note that we
3345 * already verified that vp is not equal to
3346 * the root vnode, which means that
3347 * mnt_vnodecovered can be NULL only for the
3350 if (VN_IS_DOOMED(vp) ||
3351 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3352 vp1->v_mountedhere != vp->v_mount) {
3355 SDT_PROBE3(vfs, namecache, fullpath, return,
3365 if (vp->v_type != VDIR) {
3367 counter_u64_add(numfullpathfail1, 1);
3369 SDT_PROBE3(vfs, namecache, fullpath, return,
3373 error = vn_vptocnp(&vp, buf, &buflen);
3379 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3383 buf[--buflen] = '/';
3384 slash_prefixed = true;
3388 if (!slash_prefixed) {
3391 counter_u64_add(numfullpathfail4, 1);
3392 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3396 buf[--buflen] = '/';
3398 counter_u64_add(numfullpathfound, 1);
3401 *retbuf = buf + buflen;
3402 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3409 * Resolve an arbitrary vnode to a pathname.
3412 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3413 * resolve to a different path than the one used to find it
3414 * - namecache is not mandatory, meaning names are not guaranteed to be added
3415 * (in which case resolving fails)
3417 static void __inline
3418 cache_rev_failed_impl(int *reason, int line)
3423 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3426 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3427 char **retbuf, size_t *buflen, size_t addend)
3429 #ifdef KDTRACE_HOOKS
3430 struct vnode *startvp = vp;
3434 struct namecache *ncp;
3438 #ifdef KDTRACE_HOOKS
3441 seqc_t vp_seqc, tvp_seqc;
3444 VFS_SMR_ASSERT_ENTERED();
3446 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3451 orig_buflen = *buflen;
3454 MPASS(*buflen >= 2);
3456 buf[*buflen] = '\0';
3459 if (vp == rdir || vp == rootvnode) {
3467 #ifdef KDTRACE_HOOKS
3471 ncp = NULL; /* for sdt probe down below */
3472 vp_seqc = vn_seqc_read_any(vp);
3473 if (seqc_in_modify(vp_seqc)) {
3474 cache_rev_failed(&reason);
3479 #ifdef KDTRACE_HOOKS
3482 if ((vp->v_vflag & VV_ROOT) != 0) {
3483 mp = atomic_load_ptr(&vp->v_mount);
3485 cache_rev_failed(&reason);
3488 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3489 tvp_seqc = vn_seqc_read_any(tvp);
3490 if (seqc_in_modify(tvp_seqc)) {
3491 cache_rev_failed(&reason);
3494 if (!vn_seqc_consistent(vp, vp_seqc)) {
3495 cache_rev_failed(&reason);
3502 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3504 cache_rev_failed(&reason);
3507 nc_flag = atomic_load_char(&ncp->nc_flag);
3508 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3509 cache_rev_failed(&reason);
3512 if (ncp->nc_nlen >= *buflen) {
3513 cache_rev_failed(&reason);
3517 *buflen -= ncp->nc_nlen;
3518 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3522 tvp_seqc = vn_seqc_read_any(tvp);
3523 if (seqc_in_modify(tvp_seqc)) {
3524 cache_rev_failed(&reason);
3527 if (!vn_seqc_consistent(vp, vp_seqc)) {
3528 cache_rev_failed(&reason);
3532 * Acquire fence provided by vn_seqc_read_any above.
3534 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3535 cache_rev_failed(&reason);
3538 if (!cache_ncp_canuse(ncp)) {
3539 cache_rev_failed(&reason);
3544 if (vp == rdir || vp == rootvnode)
3549 *retbuf = buf + *buflen;
3550 *buflen = orig_buflen - *buflen + addend;
3551 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3555 *buflen = orig_buflen;
3556 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3562 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3565 size_t orig_buflen, addend;
3571 orig_buflen = *buflen;
3575 if (vp->v_type != VDIR) {
3577 buf[*buflen] = '\0';
3578 error = vn_vptocnp(&vp, buf, buflen);
3587 addend = orig_buflen - *buflen;
3590 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3594 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3596 * Since the namecache does not track hardlinks, the caller is expected to first
3597 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3599 * Then we have 2 cases:
3600 * - if the found vnode is a directory, the path can be constructed just by
3601 * following names up the chain
3602 * - otherwise we populate the buffer with the saved name and start resolving
3606 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3611 struct componentname *cnp;
3619 if (*buflen > MAXPATHLEN)
3620 *buflen = MAXPATHLEN;
3622 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3627 * Check for VBAD to work around the vp_crossmp bug in lookup().
3629 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3630 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3631 * If the type is VDIR (like in this very case) we can skip looking
3632 * at ni_dvp in the first place. However, since vnodes get passed here
3633 * unlocked the target may transition to doomed state (type == VBAD)
3634 * before we get to evaluate the condition. If this happens, we will
3635 * populate part of the buffer and descend to vn_fullpath_dir with
3636 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3638 * This should be atomic_load(&vp->v_type) but it is illegal to take
3639 * an address of a bit field, even if said field is sized to char.
3640 * Work around the problem by reading the value into a full-sized enum
3641 * and then re-reading it with atomic_load which will still prevent
3642 * the compiler from re-reading down the road.
3645 type = atomic_load_int(&type);
3652 addend = cnp->cn_namelen + 2;
3653 if (*buflen < addend) {
3658 tmpbuf = buf + *buflen;
3660 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3661 tmpbuf[addend - 1] = '\0';
3666 pwd = pwd_get_smr();
3667 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3669 VFS_SMR_ASSERT_NOT_ENTERED();
3671 pwd = pwd_hold(curthread);
3673 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3689 vn_dir_dd_ino(struct vnode *vp)
3691 struct namecache *ncp;
3696 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3697 vlp = VP2VNODELOCK(vp);
3699 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3700 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3703 vs = vget_prep(ddvp);
3705 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3714 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3716 struct namecache *ncp;
3720 vlp = VP2VNODELOCK(vp);
3722 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3723 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3729 l = min(ncp->nc_nlen, buflen - 1);
3730 memcpy(buf, ncp->nc_name, l);
3737 * This function updates path string to vnode's full global path
3738 * and checks the size of the new path string against the pathlen argument.
3740 * Requires a locked, referenced vnode.
3741 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3743 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3744 * because it falls back to the ".." lookup if the namecache lookup fails.
3747 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3750 struct nameidata nd;
3755 ASSERT_VOP_ELOCKED(vp, __func__);
3757 /* Construct global filesystem path from vp. */
3759 error = vn_fullpath_global(vp, &rpath, &fbuf);
3766 if (strlen(rpath) >= pathlen) {
3768 error = ENAMETOOLONG;
3773 * Re-lookup the vnode by path to detect a possible rename.
3774 * As a side effect, the vnode is relocked.
3775 * If vnode was renamed, return ENOENT.
3777 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3778 UIO_SYSSPACE, path, td);
3784 NDFREE(&nd, NDF_ONLY_PNBUF);
3788 strcpy(path, rpath);
3801 db_print_vpath(struct vnode *vp)
3804 while (vp != NULL) {
3805 db_printf("%p: ", vp);
3806 if (vp == rootvnode) {
3810 if (vp->v_vflag & VV_ROOT) {
3811 db_printf("<mount point>");
3812 vp = vp->v_mount->mnt_vnodecovered;
3814 struct namecache *ncp;
3818 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3821 for (i = 0; i < ncp->nc_nlen; i++)
3822 db_printf("%c", *ncn++);
3835 DB_SHOW_COMMAND(vpath, db_show_vpath)
3840 db_printf("usage: show vpath <struct vnode *>\n");
3844 vp = (struct vnode *)addr;
3850 static int cache_fast_lookup = 1;
3852 #define CACHE_FPL_FAILED -2020
3855 cache_fast_lookup_enabled_recalc(void)
3861 mac_on = mac_vnode_check_lookup_enabled();
3862 mac_on |= mac_vnode_check_readlink_enabled();
3867 lookup_flag = atomic_load_int(&cache_fast_lookup);
3868 if (lookup_flag && !mac_on) {
3869 atomic_store_char(&cache_fast_lookup_enabled, true);
3871 atomic_store_char(&cache_fast_lookup_enabled, false);
3876 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
3880 old = atomic_load_int(&cache_fast_lookup);
3881 error = sysctl_handle_int(oidp, arg1, arg2, req);
3882 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
3883 cache_fast_lookup_enabled_recalc();
3886 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
3887 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
3890 * Components of nameidata (or objects it can point to) which may
3891 * need restoring in case fast path lookup fails.
3893 struct nameidata_outer {
3898 struct nameidata_saved {
3906 struct cache_fpl_debug {
3912 struct nameidata *ndp;
3913 struct componentname *cnp;
3920 struct nameidata_saved snd;
3921 struct nameidata_outer snd_outer;
3923 enum cache_fpl_status status:8;
3929 struct cache_fpl_debug debug;
3933 static bool cache_fplookup_mp_supported(struct mount *mp);
3934 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
3935 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
3936 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
3937 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
3938 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
3939 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
3940 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
3941 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
3942 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
3945 cache_fpl_cleanup_cnp(struct componentname *cnp)
3948 uma_zfree(namei_zone, cnp->cn_pnbuf);
3950 cnp->cn_pnbuf = NULL;
3951 cnp->cn_nameptr = NULL;
3955 static struct vnode *
3956 cache_fpl_handle_root(struct cache_fpl *fpl)
3958 struct nameidata *ndp;
3959 struct componentname *cnp;
3964 MPASS(*(cnp->cn_nameptr) == '/');
3966 cache_fpl_pathlen_dec(fpl);
3968 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
3971 cache_fpl_pathlen_dec(fpl);
3972 } while (*(cnp->cn_nameptr) == '/');
3975 return (ndp->ni_rootdir);
3979 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
3982 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
3983 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
3987 cache_fpl_checkpoint(struct cache_fpl *fpl)
3991 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3992 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
3997 cache_fpl_restore_partial(struct cache_fpl *fpl)
4000 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4002 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4007 cache_fpl_restore_abort(struct cache_fpl *fpl)
4010 cache_fpl_restore_partial(fpl);
4012 * It is 0 on entry by API contract.
4014 fpl->ndp->ni_resflags = 0;
4015 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4016 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4020 #define cache_fpl_smr_assert_entered(fpl) ({ \
4021 struct cache_fpl *_fpl = (fpl); \
4022 MPASS(_fpl->in_smr == true); \
4023 VFS_SMR_ASSERT_ENTERED(); \
4025 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4026 struct cache_fpl *_fpl = (fpl); \
4027 MPASS(_fpl->in_smr == false); \
4028 VFS_SMR_ASSERT_NOT_ENTERED(); \
4031 cache_fpl_assert_status(struct cache_fpl *fpl)
4034 switch (fpl->status) {
4035 case CACHE_FPL_STATUS_UNSET:
4036 __assert_unreachable();
4038 case CACHE_FPL_STATUS_DESTROYED:
4039 case CACHE_FPL_STATUS_ABORTED:
4040 case CACHE_FPL_STATUS_PARTIAL:
4041 case CACHE_FPL_STATUS_HANDLED:
4046 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4047 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4048 #define cache_fpl_assert_status(fpl) do { } while (0)
4051 #define cache_fpl_smr_enter_initial(fpl) ({ \
4052 struct cache_fpl *_fpl = (fpl); \
4054 _fpl->in_smr = true; \
4057 #define cache_fpl_smr_enter(fpl) ({ \
4058 struct cache_fpl *_fpl = (fpl); \
4059 MPASS(_fpl->in_smr == false); \
4061 _fpl->in_smr = true; \
4064 #define cache_fpl_smr_exit(fpl) ({ \
4065 struct cache_fpl *_fpl = (fpl); \
4066 MPASS(_fpl->in_smr == true); \
4068 _fpl->in_smr = false; \
4072 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4075 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4076 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4077 ("%s: converting to abort from %d at %d, set at %d\n",
4078 __func__, fpl->status, line, fpl->line));
4080 cache_fpl_smr_assert_not_entered(fpl);
4081 fpl->status = CACHE_FPL_STATUS_ABORTED;
4083 return (CACHE_FPL_FAILED);
4086 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4088 static int __noinline
4089 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4091 struct nameidata *ndp;
4092 struct componentname *cnp;
4097 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4098 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4099 ("%s: converting to abort from %d at %d, set at %d\n",
4100 __func__, fpl->status, line, fpl->line));
4102 fpl->status = CACHE_FPL_STATUS_ABORTED;
4105 cache_fpl_smr_exit(fpl);
4106 cache_fpl_restore_abort(fpl);
4108 * Resolving symlinks overwrites data passed by the caller.
4111 if (ndp->ni_loopcnt > 0) {
4112 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4113 cache_fpl_cleanup_cnp(cnp);
4115 return (CACHE_FPL_FAILED);
4118 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4120 static int __noinline
4121 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4124 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4125 ("%s: setting to partial at %d, but already set to %d at %d\n",
4126 __func__, line, fpl->status, fpl->line));
4127 cache_fpl_smr_assert_entered(fpl);
4128 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4130 return (cache_fplookup_partial_setup(fpl));
4133 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4136 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4139 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4140 ("%s: setting to handled at %d, but already set to %d at %d\n",
4141 __func__, line, fpl->status, fpl->line));
4142 cache_fpl_smr_assert_not_entered(fpl);
4143 fpl->status = CACHE_FPL_STATUS_HANDLED;
4148 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4151 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4154 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4155 ("%s: setting to handled at %d, but already set to %d at %d\n",
4156 __func__, line, fpl->status, fpl->line));
4158 MPASS(error != CACHE_FPL_FAILED);
4159 cache_fpl_smr_assert_not_entered(fpl);
4160 fpl->status = CACHE_FPL_STATUS_HANDLED;
4164 fpl->savename = false;
4168 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4171 cache_fpl_terminated(struct cache_fpl *fpl)
4174 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4177 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4178 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4179 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | SAVENAME | SAVESTART | \
4180 WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | \
4181 OPENREAD | OPENWRITE)
4183 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4184 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4186 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4187 "supported and internal flags overlap");
4190 cache_fpl_islastcn(struct nameidata *ndp)
4193 return (*ndp->ni_next == 0);
4197 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4200 MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4201 return (*(fpl->nulchar - 1) == '/');
4205 cache_fpl_isdotdot(struct componentname *cnp)
4208 if (cnp->cn_namelen == 2 &&
4209 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4215 cache_can_fplookup(struct cache_fpl *fpl)
4217 struct nameidata *ndp;
4218 struct componentname *cnp;
4225 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4226 cache_fpl_aborted_early(fpl);
4229 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4230 cache_fpl_aborted_early(fpl);
4233 if (IN_CAPABILITY_MODE(td)) {
4234 cache_fpl_aborted_early(fpl);
4237 if (AUDITING_TD(td)) {
4238 cache_fpl_aborted_early(fpl);
4241 if (ndp->ni_startdir != NULL) {
4242 cache_fpl_aborted_early(fpl);
4249 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4251 struct nameidata *ndp;
4256 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4257 if (__predict_false(error != 0)) {
4258 return (cache_fpl_aborted(fpl));
4260 fpl->fsearch = fsearch;
4264 static int __noinline
4265 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4268 struct componentname *cnp;
4274 cache_fpl_smr_exit(fpl);
4275 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4276 return (cache_fpl_handled_error(fpl, ENOENT));
4278 return (cache_fpl_aborted(fpl));
4282 * The target vnode is not supported, prepare for the slow path to take over.
4284 static int __noinline
4285 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4287 struct nameidata *ndp;
4288 struct componentname *cnp;
4298 dvp_seqc = fpl->dvp_seqc;
4300 if (!pwd_hold_smr(pwd)) {
4301 return (cache_fpl_aborted(fpl));
4305 * Note that seqc is checked before the vnode is locked, so by
4306 * the time regular lookup gets to it it may have moved.
4308 * Ultimately this does not affect correctness, any lookup errors
4309 * are userspace racing with itself. It is guaranteed that any
4310 * path which ultimately gets found could also have been found
4311 * by regular lookup going all the way in absence of concurrent
4314 dvs = vget_prep_smr(dvp);
4315 cache_fpl_smr_exit(fpl);
4316 if (__predict_false(dvs == VGET_NONE)) {
4318 return (cache_fpl_aborted(fpl));
4321 vget_finish_ref(dvp, dvs);
4322 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4325 return (cache_fpl_aborted(fpl));
4328 cache_fpl_restore_partial(fpl);
4330 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4331 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4332 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4336 ndp->ni_startdir = dvp;
4337 cnp->cn_flags |= MAKEENTRY;
4338 if (cache_fpl_islastcn(ndp))
4339 cnp->cn_flags |= ISLASTCN;
4340 if (cache_fpl_isdotdot(cnp))
4341 cnp->cn_flags |= ISDOTDOT;
4344 * Skip potential extra slashes parsing did not take care of.
4345 * cache_fplookup_skip_slashes explains the mechanism.
4347 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4350 cache_fpl_pathlen_dec(fpl);
4351 } while (*(cnp->cn_nameptr) == '/');
4354 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4356 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4357 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4358 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4359 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4366 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4368 struct componentname *cnp;
4375 tvp_seqc = fpl->tvp_seqc;
4377 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4378 lkflags = LK_SHARED;
4379 if ((cnp->cn_flags & LOCKSHARED) == 0)
4380 lkflags = LK_EXCLUSIVE;
4381 error = vget_finish(tvp, lkflags, tvs);
4382 if (__predict_false(error != 0)) {
4383 return (cache_fpl_aborted(fpl));
4386 vget_finish_ref(tvp, tvs);
4389 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4390 if ((cnp->cn_flags & LOCKLEAF) != 0)
4394 return (cache_fpl_aborted(fpl));
4397 return (cache_fpl_handled(fpl));
4401 * They want to possibly modify the state of the namecache.
4403 static int __noinline
4404 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4406 struct nameidata *ndp;
4407 struct componentname *cnp;
4409 struct vnode *dvp, *tvp;
4418 dvp_seqc = fpl->dvp_seqc;
4420 MPASS(*(cnp->cn_nameptr) != '/');
4421 MPASS(cache_fpl_islastcn(ndp));
4422 if ((cnp->cn_flags & LOCKPARENT) == 0)
4423 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4424 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4425 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4426 cnp->cn_nameiop == RENAME);
4427 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4428 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4430 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4431 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4435 * Regular lookup nulifies the slash, which we don't do here.
4436 * Don't take chances with filesystem routines seeing it for
4439 if (cache_fpl_istrailingslash(fpl)) {
4440 return (cache_fpl_partial(fpl));
4443 mp = atomic_load_ptr(&dvp->v_mount);
4444 if (__predict_false(mp == NULL)) {
4445 return (cache_fpl_aborted(fpl));
4448 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4449 cache_fpl_smr_exit(fpl);
4451 * Original code keeps not checking for CREATE which
4452 * might be a bug. For now let the old lookup decide.
4454 if (cnp->cn_nameiop == CREATE) {
4455 return (cache_fpl_aborted(fpl));
4457 return (cache_fpl_handled_error(fpl, EROFS));
4460 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4461 cache_fpl_smr_exit(fpl);
4462 return (cache_fpl_handled_error(fpl, EEXIST));
4466 * Secure access to dvp; check cache_fplookup_partial_setup for
4469 * XXX At least UFS requires its lookup routine to be called for
4470 * the last path component, which leads to some level of complication
4472 * - the target routine always locks the target vnode, but our caller
4473 * may not need it locked
4474 * - some of the VOP machinery asserts that the parent is locked, which
4475 * once more may be not required
4477 * TODO: add a flag for filesystems which don't need this.
4479 dvs = vget_prep_smr(dvp);
4480 cache_fpl_smr_exit(fpl);
4481 if (__predict_false(dvs == VGET_NONE)) {
4482 return (cache_fpl_aborted(fpl));
4485 vget_finish_ref(dvp, dvs);
4486 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4488 return (cache_fpl_aborted(fpl));
4491 error = vn_lock(dvp, LK_EXCLUSIVE);
4492 if (__predict_false(error != 0)) {
4494 return (cache_fpl_aborted(fpl));
4498 cnp->cn_flags |= ISLASTCN;
4500 cnp->cn_flags |= MAKEENTRY;
4501 if (cache_fpl_isdotdot(cnp))
4502 cnp->cn_flags |= ISDOTDOT;
4503 cnp->cn_lkflags = LK_EXCLUSIVE;
4504 error = VOP_LOOKUP(dvp, &tvp, cnp);
4512 return (cache_fpl_handled_error(fpl, error));
4515 return (cache_fpl_aborted(fpl));
4519 fpl->savename = (cnp->cn_flags & SAVENAME) != 0;
4522 if ((cnp->cn_flags & SAVESTART) != 0) {
4523 ndp->ni_startdir = dvp;
4524 vrefact(ndp->ni_startdir);
4525 cnp->cn_flags |= SAVENAME;
4526 fpl->savename = true;
4528 MPASS(error == EJUSTRETURN);
4529 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4532 return (cache_fpl_handled(fpl));
4536 * There are very hairy corner cases concerning various flag combinations
4537 * and locking state. In particular here we only hold one lock instead of
4540 * Skip the complexity as it is of no significance for normal workloads.
4542 if (__predict_false(tvp == dvp)) {
4545 return (cache_fpl_aborted(fpl));
4549 * If they want the symlink itself we are fine, but if they want to
4550 * follow it regular lookup has to be engaged.
4552 if (tvp->v_type == VLNK) {
4553 if ((cnp->cn_flags & FOLLOW) != 0) {
4556 return (cache_fpl_aborted(fpl));
4561 * Since we expect this to be the terminal vnode it should almost never
4564 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4567 return (cache_fpl_aborted(fpl));
4570 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4573 return (cache_fpl_handled_error(fpl, EEXIST));
4576 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4580 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4584 if ((cnp->cn_flags & SAVESTART) != 0) {
4585 ndp->ni_startdir = dvp;
4586 vrefact(ndp->ni_startdir);
4587 cnp->cn_flags |= SAVENAME;
4588 fpl->savename = true;
4591 return (cache_fpl_handled(fpl));
4594 static int __noinline
4595 cache_fplookup_modifying(struct cache_fpl *fpl)
4597 struct nameidata *ndp;
4601 if (!cache_fpl_islastcn(ndp)) {
4602 return (cache_fpl_partial(fpl));
4604 return (cache_fplookup_final_modifying(fpl));
4607 static int __noinline
4608 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4610 struct componentname *cnp;
4611 enum vgetstate dvs, tvs;
4612 struct vnode *dvp, *tvp;
4618 dvp_seqc = fpl->dvp_seqc;
4621 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4624 * This is less efficient than it can be for simplicity.
4626 dvs = vget_prep_smr(dvp);
4627 if (__predict_false(dvs == VGET_NONE)) {
4628 return (cache_fpl_aborted(fpl));
4630 tvs = vget_prep_smr(tvp);
4631 if (__predict_false(tvs == VGET_NONE)) {
4632 cache_fpl_smr_exit(fpl);
4633 vget_abort(dvp, dvs);
4634 return (cache_fpl_aborted(fpl));
4637 cache_fpl_smr_exit(fpl);
4639 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4640 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4641 if (__predict_false(error != 0)) {
4642 vget_abort(tvp, tvs);
4643 return (cache_fpl_aborted(fpl));
4646 vget_finish_ref(dvp, dvs);
4649 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4650 vget_abort(tvp, tvs);
4651 if ((cnp->cn_flags & LOCKPARENT) != 0)
4655 return (cache_fpl_aborted(fpl));
4658 error = cache_fplookup_final_child(fpl, tvs);
4659 if (__predict_false(error != 0)) {
4660 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4661 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4662 if ((cnp->cn_flags & LOCKPARENT) != 0)
4669 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4674 cache_fplookup_final(struct cache_fpl *fpl)
4676 struct componentname *cnp;
4678 struct vnode *dvp, *tvp;
4683 dvp_seqc = fpl->dvp_seqc;
4686 MPASS(*(cnp->cn_nameptr) != '/');
4688 if (cnp->cn_nameiop != LOOKUP) {
4689 return (cache_fplookup_final_modifying(fpl));
4692 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4693 return (cache_fplookup_final_withparent(fpl));
4695 tvs = vget_prep_smr(tvp);
4696 if (__predict_false(tvs == VGET_NONE)) {
4697 return (cache_fpl_partial(fpl));
4700 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4701 cache_fpl_smr_exit(fpl);
4702 vget_abort(tvp, tvs);
4703 return (cache_fpl_aborted(fpl));
4706 cache_fpl_smr_exit(fpl);
4707 return (cache_fplookup_final_child(fpl, tvs));
4711 * Comment from locked lookup:
4712 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4713 * directory, e.g. like "/." or ".".
4715 static int __noinline
4716 cache_fplookup_degenerate(struct cache_fpl *fpl)
4718 struct componentname *cnp;
4726 fpl->tvp = fpl->dvp;
4727 fpl->tvp_seqc = fpl->dvp_seqc;
4733 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4735 ("%s: encountered non-slash; string [%s]\n", __func__,
4740 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4741 cache_fpl_smr_exit(fpl);
4742 return (cache_fpl_handled_error(fpl, EISDIR));
4745 MPASS((cnp->cn_flags & SAVESTART) == 0);
4747 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4748 return (cache_fplookup_final_withparent(fpl));
4751 dvs = vget_prep_smr(dvp);
4752 cache_fpl_smr_exit(fpl);
4753 if (__predict_false(dvs == VGET_NONE)) {
4754 return (cache_fpl_aborted(fpl));
4757 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4758 lkflags = LK_SHARED;
4759 if ((cnp->cn_flags & LOCKSHARED) == 0)
4760 lkflags = LK_EXCLUSIVE;
4761 error = vget_finish(dvp, lkflags, dvs);
4762 if (__predict_false(error != 0)) {
4763 return (cache_fpl_aborted(fpl));
4766 vget_finish_ref(dvp, dvs);
4768 return (cache_fpl_handled(fpl));
4771 static int __noinline
4772 cache_fplookup_emptypath(struct cache_fpl *fpl)
4774 struct nameidata *ndp;
4775 struct componentname *cnp;
4781 fpl->tvp = fpl->dvp;
4782 fpl->tvp_seqc = fpl->dvp_seqc;
4787 tvp_seqc = fpl->tvp_seqc;
4789 MPASS(*cnp->cn_pnbuf == '\0');
4791 if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
4792 cache_fpl_smr_exit(fpl);
4793 return (cache_fpl_handled_error(fpl, ENOENT));
4796 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
4798 tvs = vget_prep_smr(tvp);
4799 cache_fpl_smr_exit(fpl);
4800 if (__predict_false(tvs == VGET_NONE)) {
4801 return (cache_fpl_aborted(fpl));
4804 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4805 lkflags = LK_SHARED;
4806 if ((cnp->cn_flags & LOCKSHARED) == 0)
4807 lkflags = LK_EXCLUSIVE;
4808 error = vget_finish(tvp, lkflags, tvs);
4809 if (__predict_false(error != 0)) {
4810 return (cache_fpl_aborted(fpl));
4813 vget_finish_ref(tvp, tvs);
4816 ndp->ni_resflags |= NIRES_EMPTYPATH;
4817 return (cache_fpl_handled(fpl));
4820 static int __noinline
4821 cache_fplookup_noentry(struct cache_fpl *fpl)
4823 struct nameidata *ndp;
4824 struct componentname *cnp;
4826 struct vnode *dvp, *tvp;
4834 dvp_seqc = fpl->dvp_seqc;
4836 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4837 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4838 MPASS(!cache_fpl_isdotdot(cnp));
4841 * Hack: delayed name len checking.
4843 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4844 cache_fpl_smr_exit(fpl);
4845 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
4848 if (cnp->cn_nameptr[0] == '/') {
4849 return (cache_fplookup_skip_slashes(fpl));
4852 if (cnp->cn_pnbuf[0] == '\0') {
4853 return (cache_fplookup_emptypath(fpl));
4856 if (cnp->cn_nameptr[0] == '\0') {
4857 if (fpl->tvp == NULL) {
4858 return (cache_fplookup_degenerate(fpl));
4860 return (cache_fplookup_trailingslash(fpl));
4863 if (cnp->cn_nameiop != LOOKUP) {
4865 return (cache_fplookup_modifying(fpl));
4868 MPASS((cnp->cn_flags & SAVESTART) == 0);
4871 * Only try to fill in the component if it is the last one,
4872 * otherwise not only there may be several to handle but the
4873 * walk may be complicated.
4875 if (!cache_fpl_islastcn(ndp)) {
4876 return (cache_fpl_partial(fpl));
4880 * Regular lookup nulifies the slash, which we don't do here.
4881 * Don't take chances with filesystem routines seeing it for
4884 if (cache_fpl_istrailingslash(fpl)) {
4885 return (cache_fpl_partial(fpl));
4889 * Secure access to dvp; check cache_fplookup_partial_setup for
4892 dvs = vget_prep_smr(dvp);
4893 cache_fpl_smr_exit(fpl);
4894 if (__predict_false(dvs == VGET_NONE)) {
4895 return (cache_fpl_aborted(fpl));
4898 vget_finish_ref(dvp, dvs);
4899 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4901 return (cache_fpl_aborted(fpl));
4904 error = vn_lock(dvp, LK_SHARED);
4905 if (__predict_false(error != 0)) {
4907 return (cache_fpl_aborted(fpl));
4912 * TODO: provide variants which don't require locking either vnode.
4914 cnp->cn_flags |= ISLASTCN;
4915 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4917 cnp->cn_flags |= MAKEENTRY;
4918 cnp->cn_lkflags = LK_SHARED;
4919 if ((cnp->cn_flags & LOCKSHARED) == 0) {
4920 cnp->cn_lkflags = LK_EXCLUSIVE;
4922 error = VOP_LOOKUP(dvp, &tvp, cnp);
4930 return (cache_fpl_handled_error(fpl, error));
4933 return (cache_fpl_aborted(fpl));
4937 if (!fpl->savename) {
4938 MPASS((cnp->cn_flags & SAVENAME) == 0);
4942 MPASS(error == EJUSTRETURN);
4943 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4945 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4948 return (cache_fpl_handled(fpl));
4951 if (tvp->v_type == VLNK) {
4952 if ((cnp->cn_flags & FOLLOW) != 0) {
4955 return (cache_fpl_aborted(fpl));
4959 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4962 return (cache_fpl_aborted(fpl));
4965 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4969 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4971 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4974 return (cache_fpl_handled(fpl));
4977 static int __noinline
4978 cache_fplookup_dot(struct cache_fpl *fpl)
4982 MPASS(!seqc_in_modify(fpl->dvp_seqc));
4984 * Just re-assign the value. seqc will be checked later for the first
4985 * non-dot path component in line and/or before deciding to return the
4988 fpl->tvp = fpl->dvp;
4989 fpl->tvp_seqc = fpl->dvp_seqc;
4991 counter_u64_add(dothits, 1);
4992 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
4995 if (cache_fplookup_is_mp(fpl)) {
4996 error = cache_fplookup_cross_mount(fpl);
5001 static int __noinline
5002 cache_fplookup_dotdot(struct cache_fpl *fpl)
5004 struct nameidata *ndp;
5005 struct componentname *cnp;
5006 struct namecache *ncp;
5015 MPASS(cache_fpl_isdotdot(cnp));
5018 * XXX this is racy the same way regular lookup is
5020 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5022 if (dvp == pr->pr_root)
5025 if (dvp == ndp->ni_rootdir ||
5026 dvp == ndp->ni_topdir ||
5030 fpl->tvp_seqc = vn_seqc_read_any(dvp);
5031 if (seqc_in_modify(fpl->tvp_seqc)) {
5032 return (cache_fpl_aborted(fpl));
5037 if ((dvp->v_vflag & VV_ROOT) != 0) {
5040 * The opposite of climb mount is needed here.
5042 return (cache_fpl_partial(fpl));
5045 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5047 return (cache_fpl_aborted(fpl));
5050 nc_flag = atomic_load_char(&ncp->nc_flag);
5051 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5052 if ((nc_flag & NCF_NEGATIVE) != 0)
5053 return (cache_fpl_aborted(fpl));
5054 fpl->tvp = ncp->nc_vp;
5056 fpl->tvp = ncp->nc_dvp;
5059 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5060 if (seqc_in_modify(fpl->tvp_seqc)) {
5061 return (cache_fpl_partial(fpl));
5065 * Acquire fence provided by vn_seqc_read_any above.
5067 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5068 return (cache_fpl_aborted(fpl));
5071 if (!cache_ncp_canuse(ncp)) {
5072 return (cache_fpl_aborted(fpl));
5075 counter_u64_add(dotdothits, 1);
5079 static int __noinline
5080 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5085 nc_flag = atomic_load_char(&ncp->nc_flag);
5086 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5088 * If they want to create an entry we need to replace this one.
5090 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5092 return (cache_fplookup_modifying(fpl));
5094 neg_promote = cache_neg_hit_prep(ncp);
5095 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5096 cache_neg_hit_abort(ncp);
5097 return (cache_fpl_partial(fpl));
5100 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5102 cache_neg_hit_finish(ncp);
5103 cache_fpl_smr_exit(fpl);
5104 return (cache_fpl_handled_error(fpl, ENOENT));
5108 * Resolve a symlink. Called by filesystem-specific routines.
5111 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5114 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5116 struct nameidata *ndp;
5117 struct componentname *cnp;
5123 if (__predict_false(len == 0)) {
5127 if (__predict_false(len > MAXPATHLEN - 2)) {
5128 if (cache_fpl_istrailingslash(fpl)) {
5133 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5135 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5136 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5137 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5138 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5142 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5143 return (ENAMETOOLONG);
5146 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5151 if (ndp->ni_pathlen > 1) {
5152 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5154 if (cache_fpl_istrailingslash(fpl)) {
5156 cnp->cn_pnbuf[len] = '/';
5157 cnp->cn_pnbuf[len + 1] = '\0';
5159 cnp->cn_pnbuf[len] = '\0';
5162 bcopy(string, cnp->cn_pnbuf, len);
5164 ndp->ni_pathlen += adjust;
5165 cache_fpl_pathlen_add(fpl, adjust);
5166 cnp->cn_nameptr = cnp->cn_pnbuf;
5167 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5172 static int __noinline
5173 cache_fplookup_symlink(struct cache_fpl *fpl)
5176 struct nameidata *ndp;
5177 struct componentname *cnp;
5178 struct vnode *dvp, *tvp;
5186 if (cache_fpl_islastcn(ndp)) {
5187 if ((cnp->cn_flags & FOLLOW) == 0) {
5188 return (cache_fplookup_final(fpl));
5192 mp = atomic_load_ptr(&dvp->v_mount);
5193 if (__predict_false(mp == NULL)) {
5194 return (cache_fpl_aborted(fpl));
5198 * Note this check races against setting the flag just like regular
5201 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5202 cache_fpl_smr_exit(fpl);
5203 return (cache_fpl_handled_error(fpl, EACCES));
5206 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5207 if (__predict_false(error != 0)) {
5210 return (cache_fpl_partial(fpl));
5214 cache_fpl_smr_exit(fpl);
5215 return (cache_fpl_handled_error(fpl, error));
5217 return (cache_fpl_aborted(fpl));
5221 if (*(cnp->cn_nameptr) == '/') {
5222 fpl->dvp = cache_fpl_handle_root(fpl);
5223 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5224 if (seqc_in_modify(fpl->dvp_seqc)) {
5225 return (cache_fpl_aborted(fpl));
5228 * The main loop assumes that ->dvp points to a vnode belonging
5229 * to a filesystem which can do lockless lookup, but the absolute
5230 * symlink can be wandering off to one which does not.
5232 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5233 if (__predict_false(mp == NULL)) {
5234 return (cache_fpl_aborted(fpl));
5236 if (!cache_fplookup_mp_supported(mp)) {
5237 cache_fpl_checkpoint(fpl);
5238 return (cache_fpl_partial(fpl));
5245 cache_fplookup_next(struct cache_fpl *fpl)
5247 struct componentname *cnp;
5248 struct namecache *ncp;
5249 struct vnode *dvp, *tvp;
5258 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5259 if (cnp->cn_namelen == 1) {
5260 return (cache_fplookup_dot(fpl));
5262 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5263 return (cache_fplookup_dotdot(fpl));
5267 MPASS(!cache_fpl_isdotdot(cnp));
5269 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5270 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5271 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5275 if (__predict_false(ncp == NULL)) {
5276 return (cache_fplookup_noentry(fpl));
5279 tvp = atomic_load_ptr(&ncp->nc_vp);
5280 nc_flag = atomic_load_char(&ncp->nc_flag);
5281 if ((nc_flag & NCF_NEGATIVE) != 0) {
5282 return (cache_fplookup_neg(fpl, ncp, hash));
5285 if (!cache_ncp_canuse(ncp)) {
5286 return (cache_fpl_partial(fpl));
5290 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5291 if (seqc_in_modify(fpl->tvp_seqc)) {
5292 return (cache_fpl_partial(fpl));
5295 counter_u64_add(numposhits, 1);
5296 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5299 if (cache_fplookup_is_mp(fpl)) {
5300 error = cache_fplookup_cross_mount(fpl);
5306 cache_fplookup_mp_supported(struct mount *mp)
5310 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5316 * Walk up the mount stack (if any).
5318 * Correctness is provided in the following ways:
5319 * - all vnodes are protected from freeing with SMR
5320 * - struct mount objects are type stable making them always safe to access
5321 * - stability of the particular mount is provided by busying it
5322 * - relationship between the vnode which is mounted on and the mount is
5323 * verified with the vnode sequence counter after busying
5324 * - association between root vnode of the mount and the mount is protected
5327 * From that point on we can read the sequence counter of the root vnode
5328 * and get the next mount on the stack (if any) using the same protection.
5330 * By the end of successful walk we are guaranteed the reached state was
5331 * indeed present at least at some point which matches the regular lookup.
5333 static int __noinline
5334 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5336 struct mount *mp, *prev_mp;
5337 struct mount_pcpu *mpcpu, *prev_mpcpu;
5342 vp_seqc = fpl->tvp_seqc;
5344 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5345 mp = atomic_load_ptr(&vp->v_mountedhere);
5346 if (__predict_false(mp == NULL)) {
5352 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5353 if (prev_mp != NULL)
5354 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5355 return (cache_fpl_partial(fpl));
5357 if (prev_mp != NULL)
5358 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5359 if (!vn_seqc_consistent(vp, vp_seqc)) {
5360 vfs_op_thread_exit_crit(mp, mpcpu);
5361 return (cache_fpl_partial(fpl));
5363 if (!cache_fplookup_mp_supported(mp)) {
5364 vfs_op_thread_exit_crit(mp, mpcpu);
5365 return (cache_fpl_partial(fpl));
5367 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5369 vfs_op_thread_exit_crit(mp, mpcpu);
5370 return (cache_fpl_partial(fpl));
5372 vp_seqc = vn_seqc_read_any(vp);
5373 if (seqc_in_modify(vp_seqc)) {
5374 vfs_op_thread_exit_crit(mp, mpcpu);
5375 return (cache_fpl_partial(fpl));
5379 mp = atomic_load_ptr(&vp->v_mountedhere);
5384 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5386 fpl->tvp_seqc = vp_seqc;
5390 static int __noinline
5391 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5394 struct mount_pcpu *mpcpu;
5399 vp_seqc = fpl->tvp_seqc;
5401 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5402 mp = atomic_load_ptr(&vp->v_mountedhere);
5403 if (__predict_false(mp == NULL)) {
5407 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5408 return (cache_fpl_partial(fpl));
5410 if (!vn_seqc_consistent(vp, vp_seqc)) {
5411 vfs_op_thread_exit_crit(mp, mpcpu);
5412 return (cache_fpl_partial(fpl));
5414 if (!cache_fplookup_mp_supported(mp)) {
5415 vfs_op_thread_exit_crit(mp, mpcpu);
5416 return (cache_fpl_partial(fpl));
5418 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5419 if (__predict_false(vp == NULL)) {
5420 vfs_op_thread_exit_crit(mp, mpcpu);
5421 return (cache_fpl_partial(fpl));
5423 vp_seqc = vn_seqc_read_any(vp);
5424 vfs_op_thread_exit_crit(mp, mpcpu);
5425 if (seqc_in_modify(vp_seqc)) {
5426 return (cache_fpl_partial(fpl));
5428 mp = atomic_load_ptr(&vp->v_mountedhere);
5429 if (__predict_false(mp != NULL)) {
5431 * There are possibly more mount points on top.
5432 * Normally this does not happen so for simplicity just start
5435 return (cache_fplookup_climb_mount(fpl));
5439 fpl->tvp_seqc = vp_seqc;
5444 * Check if a vnode is mounted on.
5447 cache_fplookup_is_mp(struct cache_fpl *fpl)
5452 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5458 * The code was originally copy-pasted from regular lookup and despite
5459 * clean ups leaves performance on the table. Any modifications here
5460 * must take into account that in case off fallback the resulting
5461 * nameidata state has to be compatible with the original.
5465 * Debug ni_pathlen tracking.
5469 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5472 fpl->debug.ni_pathlen += n;
5473 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5474 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5478 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5481 fpl->debug.ni_pathlen -= n;
5482 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5483 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5487 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5490 cache_fpl_pathlen_add(fpl, 1);
5494 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5497 cache_fpl_pathlen_sub(fpl, 1);
5501 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5506 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5511 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5516 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5522 cache_fplookup_parse(struct cache_fpl *fpl)
5524 struct nameidata *ndp;
5525 struct componentname *cnp;
5535 * Find the end of this path component, it is either / or nul.
5537 * Store / as a temporary sentinel so that we only have one character
5538 * to test for. Pathnames tend to be short so this should not be
5539 * resulting in cache misses.
5541 * TODO: fix this to be word-sized.
5543 MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5544 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5545 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5546 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5547 fpl->nulchar, cnp->cn_pnbuf));
5548 KASSERT(*fpl->nulchar == '\0',
5549 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5551 hash = cache_get_hash_iter_start(dvp);
5552 *fpl->nulchar = '/';
5553 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5554 KASSERT(*cp != '\0',
5555 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5557 hash = cache_get_hash_iter(*cp, hash);
5560 *fpl->nulchar = '\0';
5561 fpl->hash = cache_get_hash_iter_finish(hash);
5563 cnp->cn_namelen = cp - cnp->cn_nameptr;
5564 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5568 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5569 * we are going to fail this lookup with ENAMETOOLONG (see below).
5571 if (cnp->cn_namelen <= NAME_MAX) {
5572 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5573 panic("%s: mismatched hash for [%s] len %ld", __func__,
5574 cnp->cn_nameptr, cnp->cn_namelen);
5580 * Hack: we have to check if the found path component's length exceeds
5581 * NAME_MAX. However, the condition is very rarely true and check can
5582 * be elided in the common case -- if an entry was found in the cache,
5583 * then it could not have been too long to begin with.
5589 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5591 struct nameidata *ndp;
5592 struct componentname *cnp;
5597 cnp->cn_nameptr = ndp->ni_next;
5598 KASSERT(*(cnp->cn_nameptr) == '/',
5599 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5600 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5602 cache_fpl_pathlen_dec(fpl);
5606 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5608 * Lockless lookup tries to elide checking for spurious slashes and should they
5609 * be present is guaranteed to fail to find an entry. In this case the caller
5610 * must check if the name starts with a slash and call this routine. It is
5611 * going to fast forward across the spurious slashes and set the state up for
5614 static int __noinline
5615 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5617 struct nameidata *ndp;
5618 struct componentname *cnp;
5623 MPASS(*(cnp->cn_nameptr) == '/');
5626 cache_fpl_pathlen_dec(fpl);
5627 } while (*(cnp->cn_nameptr) == '/');
5630 * Go back to one slash so that cache_fplookup_parse_advance has
5631 * something to skip.
5634 cache_fpl_pathlen_inc(fpl);
5637 * cache_fplookup_parse_advance starts from ndp->ni_next
5639 ndp->ni_next = cnp->cn_nameptr;
5642 * See cache_fplookup_dot.
5644 fpl->tvp = fpl->dvp;
5645 fpl->tvp_seqc = fpl->dvp_seqc;
5651 * Handle trailing slashes (e.g., "foo/").
5653 * If a trailing slash is found the terminal vnode must be a directory.
5654 * Regular lookup shortens the path by nulifying the first trailing slash and
5655 * sets the TRAILINGSLASH flag to denote this took place. There are several
5656 * checks on it performed later.
5658 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5659 * manner relying on an invariant that a non-directory vnode will get a miss.
5660 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5662 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5663 * and denotes this is the last path component, which avoids looping back.
5665 * Only plain lookups are supported for now to restrict corner cases to handle.
5667 static int __noinline
5668 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5673 struct nameidata *ndp;
5674 struct componentname *cnp;
5675 struct namecache *ncp;
5677 char *cn_nameptr_orig, *cn_nameptr_slash;
5684 tvp_seqc = fpl->tvp_seqc;
5686 MPASS(fpl->dvp == fpl->tvp);
5687 KASSERT(cache_fpl_istrailingslash(fpl),
5688 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5690 KASSERT(cnp->cn_nameptr[0] == '\0',
5691 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5693 KASSERT(cnp->cn_namelen == 0,
5694 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5696 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5698 if (cnp->cn_nameiop != LOOKUP) {
5699 return (cache_fpl_aborted(fpl));
5702 if (__predict_false(tvp->v_type != VDIR)) {
5703 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5704 return (cache_fpl_aborted(fpl));
5706 cache_fpl_smr_exit(fpl);
5707 return (cache_fpl_handled_error(fpl, ENOTDIR));
5711 * Denote the last component.
5713 ndp->ni_next = &cnp->cn_nameptr[0];
5714 MPASS(cache_fpl_islastcn(ndp));
5717 * Unwind trailing slashes.
5719 cn_nameptr_orig = cnp->cn_nameptr;
5720 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5722 if (cnp->cn_nameptr[0] != '/') {
5728 * Unwind to the beginning of the path component.
5730 * Note the path may or may not have started with a slash.
5732 cn_nameptr_slash = cnp->cn_nameptr;
5733 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5735 if (cnp->cn_nameptr[0] == '/') {
5739 if (cnp->cn_nameptr[0] == '/') {
5743 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5744 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5745 cache_fpl_checkpoint(fpl);
5748 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5749 if (ni_pathlen != fpl->debug.ni_pathlen) {
5750 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5751 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5752 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5757 * If this was a "./" lookup the parent directory is already correct.
5759 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5764 * Otherwise we need to look it up.
5767 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5768 if (__predict_false(ncp == NULL)) {
5769 return (cache_fpl_aborted(fpl));
5771 nc_flag = atomic_load_char(&ncp->nc_flag);
5772 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5773 return (cache_fpl_aborted(fpl));
5775 fpl->dvp = ncp->nc_dvp;
5776 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5777 if (seqc_in_modify(fpl->dvp_seqc)) {
5778 return (cache_fpl_aborted(fpl));
5784 * See the API contract for VOP_FPLOOKUP_VEXEC.
5786 static int __noinline
5787 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5789 struct componentname *cnp;
5795 dvp_seqc = fpl->dvp_seqc;
5798 * Hack: delayed empty path checking.
5800 if (cnp->cn_pnbuf[0] == '\0') {
5801 return (cache_fplookup_emptypath(fpl));
5805 * TODO: Due to ignoring trailing slashes lookup will perform a
5806 * permission check on the last dir when it should not be doing it. It
5807 * may fail, but said failure should be ignored. It is possible to fix
5808 * it up fully without resorting to regular lookup, but for now just
5811 if (cache_fpl_istrailingslash(fpl)) {
5812 return (cache_fpl_aborted(fpl));
5816 * Hack: delayed degenerate path checking.
5818 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5819 return (cache_fplookup_degenerate(fpl));
5823 * Hack: delayed name len checking.
5825 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5826 cache_fpl_smr_exit(fpl);
5827 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5831 * Hack: they may be looking up foo/bar, where foo is not a directory.
5832 * In such a case we need to return ENOTDIR, but we may happen to get
5833 * here with a different error.
5835 if (dvp->v_type != VDIR) {
5840 * Hack: handle O_SEARCH.
5842 * Open Group Base Specifications Issue 7, 2018 edition states:
5844 * If the access mode of the open file description associated with the
5845 * file descriptor is not O_SEARCH, the function shall check whether
5846 * directory searches are permitted using the current permissions of
5847 * the directory underlying the file descriptor. If the access mode is
5848 * O_SEARCH, the function shall not perform the check.
5851 * Regular lookup tests for the NOEXECCHECK flag for every path
5852 * component to decide whether to do the permission check. However,
5853 * since most lookups never have the flag (and when they do it is only
5854 * present for the first path component), lockless lookup only acts on
5855 * it if there is a permission problem. Here the flag is represented
5856 * with a boolean so that we don't have to clear it on the way out.
5858 * For simplicity this always aborts.
5859 * TODO: check if this is the first lookup and ignore the permission
5860 * problem. Note the flag has to survive fallback (if it happens to be
5864 return (cache_fpl_aborted(fpl));
5869 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5870 error = cache_fpl_aborted(fpl);
5872 cache_fpl_partial(fpl);
5876 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5877 error = cache_fpl_aborted(fpl);
5879 cache_fpl_smr_exit(fpl);
5880 cache_fpl_handled_error(fpl, error);
5888 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
5890 struct nameidata *ndp;
5891 struct componentname *cnp;
5898 cache_fpl_checkpoint(fpl);
5901 * The vnode at hand is almost always stable, skip checking for it.
5902 * Worst case this postpones the check towards the end of the iteration
5906 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
5908 mp = atomic_load_ptr(&dvp->v_mount);
5909 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
5910 return (cache_fpl_aborted(fpl));
5913 MPASS(fpl->tvp == NULL);
5916 cache_fplookup_parse(fpl);
5918 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
5919 if (__predict_false(error != 0)) {
5920 error = cache_fplookup_failed_vexec(fpl, error);
5924 error = cache_fplookup_next(fpl);
5925 if (__predict_false(cache_fpl_terminated(fpl))) {
5929 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
5931 if (fpl->tvp->v_type == VLNK) {
5932 error = cache_fplookup_symlink(fpl);
5933 if (cache_fpl_terminated(fpl)) {
5937 if (cache_fpl_islastcn(ndp)) {
5938 error = cache_fplookup_final(fpl);
5942 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
5943 error = cache_fpl_aborted(fpl);
5947 fpl->dvp = fpl->tvp;
5948 fpl->dvp_seqc = fpl->tvp_seqc;
5949 cache_fplookup_parse_advance(fpl);
5952 cache_fpl_checkpoint(fpl);
5959 * Fast path lookup protected with SMR and sequence counters.
5961 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
5963 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
5966 * Traditional vnode lookup conceptually looks like this:
5972 * vn_unlock(current);
5979 * Each jump to the next vnode is safe memory-wise and atomic with respect to
5980 * any modifications thanks to holding respective locks.
5982 * The same guarantee can be provided with a combination of safe memory
5983 * reclamation and sequence counters instead. If all operations which affect
5984 * the relationship between the current vnode and the one we are looking for
5985 * also modify the counter, we can verify whether all the conditions held as
5986 * we made the jump. This includes things like permissions, mount points etc.
5987 * Counter modification is provided by enclosing relevant places in
5988 * vn_seqc_write_begin()/end() calls.
5990 * Thus this translates to:
5993 * dvp_seqc = seqc_read_any(dvp);
5994 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
5998 * tvp_seqc = seqc_read_any(tvp);
5999 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6001 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6003 * dvp = tvp; // we know nothing of importance has changed
6004 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6008 * vget(); // secure the vnode
6009 * if (!seqc_consistent(tvp, tvp_seqc) // final check
6011 * // at this point we know nothing has changed for any parent<->child pair
6012 * // as they were crossed during the lookup, meaning we matched the guarantee
6013 * // of the locked variant
6016 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6017 * - they are called while within vfs_smr protection which they must never exit
6018 * - EAGAIN can be returned to denote checking could not be performed, it is
6019 * always valid to return it
6020 * - if the sequence counter has not changed the result must be valid
6021 * - if the sequence counter has changed both false positives and false negatives
6022 * are permitted (since the result will be rejected later)
6023 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6025 * Caveats to watch out for:
6026 * - vnodes are passed unlocked and unreferenced with nothing stopping
6027 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6028 * to use atomic_load_ptr to fetch it.
6029 * - the aforementioned object can also get freed, meaning absent other means it
6030 * should be protected with vfs_smr
6031 * - either safely checking permissions as they are modified or guaranteeing
6032 * their stability is left to the routine
6035 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6038 struct cache_fpl fpl;
6041 struct componentname *cnp;
6044 fpl.status = CACHE_FPL_STATUS_UNSET;
6047 fpl.cnp = cnp = &ndp->ni_cnd;
6048 MPASS(ndp->ni_lcf == 0);
6049 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6050 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6052 if ((cnp->cn_flags & SAVESTART) != 0) {
6053 MPASS(cnp->cn_nameiop != LOOKUP);
6055 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6057 if (__predict_false(!cache_can_fplookup(&fpl))) {
6058 *status = fpl.status;
6059 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6060 return (EOPNOTSUPP);
6063 cache_fpl_checkpoint_outer(&fpl);
6065 cache_fpl_smr_enter_initial(&fpl);
6067 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6069 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6070 fpl.fsearch = false;
6071 fpl.savename = (cnp->cn_flags & SAVENAME) != 0;
6072 fpl.tvp = NULL; /* for degenerate path handling */
6074 pwd = pwd_get_smr();
6076 ndp->ni_rootdir = pwd->pwd_rdir;
6077 ndp->ni_topdir = pwd->pwd_jdir;
6079 if (cnp->cn_pnbuf[0] == '/') {
6080 dvp = cache_fpl_handle_root(&fpl);
6081 MPASS(ndp->ni_resflags == 0);
6082 ndp->ni_resflags = NIRES_ABS;
6084 if (ndp->ni_dirfd == AT_FDCWD) {
6085 dvp = pwd->pwd_cdir;
6087 error = cache_fplookup_dirfd(&fpl, &dvp);
6088 if (__predict_false(error != 0)) {
6094 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6095 error = cache_fplookup_impl(dvp, &fpl);
6097 cache_fpl_smr_assert_not_entered(&fpl);
6098 cache_fpl_assert_status(&fpl);
6099 *status = fpl.status;
6100 if (SDT_PROBES_ENABLED()) {
6101 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6102 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6103 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6107 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6108 MPASS(error != CACHE_FPL_FAILED);
6110 MPASS(fpl.dvp == NULL);
6111 MPASS(fpl.tvp == NULL);
6112 MPASS(fpl.savename == false);
6114 ndp->ni_dvp = fpl.dvp;
6115 ndp->ni_vp = fpl.tvp;
6117 cnp->cn_flags |= HASBUF;
6119 cache_fpl_cleanup_cnp(cnp);