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(dotdothits, 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(poszaps, 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_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
583 char **retbuf, size_t *buflen, size_t addend);
584 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
585 char **retbuf, size_t *buflen);
586 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
587 char **retbuf, size_t *len, size_t addend);
589 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
592 cache_assert_vlp_locked(struct mtx *vlp)
596 mtx_assert(vlp, MA_OWNED);
600 cache_assert_vnode_locked(struct vnode *vp)
604 vlp = VP2VNODELOCK(vp);
605 cache_assert_vlp_locked(vlp);
609 * Directory vnodes with entries are held for two reasons:
610 * 1. make them less of a target for reclamation in vnlru
611 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
613 * It will be feasible to stop doing it altogether if all filesystems start
614 * supporting lockless lookup.
617 cache_hold_vnode(struct vnode *vp)
620 cache_assert_vnode_locked(vp);
621 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
623 counter_u64_add(numcachehv, 1);
627 cache_drop_vnode(struct vnode *vp)
631 * Called after all locks are dropped, meaning we can't assert
632 * on the state of v_cache_src.
635 counter_u64_add(numcachehv, -1);
641 static uma_zone_t __read_mostly cache_zone_small;
642 static uma_zone_t __read_mostly cache_zone_small_ts;
643 static uma_zone_t __read_mostly cache_zone_large;
644 static uma_zone_t __read_mostly cache_zone_large_ts;
647 cache_symlink_alloc(size_t size, int flags)
650 if (size < CACHE_ZONE_SMALL_SIZE) {
651 return (uma_zalloc_smr(cache_zone_small, flags));
653 if (size < CACHE_ZONE_LARGE_SIZE) {
654 return (uma_zalloc_smr(cache_zone_large, flags));
656 counter_u64_add(symlinktoobig, 1);
657 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
662 cache_symlink_free(char *string, size_t size)
665 MPASS(string != NULL);
666 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
667 ("%s: size %zu too big", __func__, size));
669 if (size < CACHE_ZONE_SMALL_SIZE) {
670 uma_zfree_smr(cache_zone_small, string);
673 if (size < CACHE_ZONE_LARGE_SIZE) {
674 uma_zfree_smr(cache_zone_large, string);
677 __assert_unreachable();
680 static struct namecache *
681 cache_alloc_uma(int len, bool ts)
683 struct namecache_ts *ncp_ts;
684 struct namecache *ncp;
686 if (__predict_false(ts)) {
687 if (len <= CACHE_PATH_CUTOFF)
688 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
690 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
691 ncp = &ncp_ts->nc_nc;
693 if (len <= CACHE_PATH_CUTOFF)
694 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
696 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
702 cache_free_uma(struct namecache *ncp)
704 struct namecache_ts *ncp_ts;
706 if (__predict_false(ncp->nc_flag & NCF_TS)) {
707 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
708 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
709 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
711 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
713 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
714 uma_zfree_smr(cache_zone_small, ncp);
716 uma_zfree_smr(cache_zone_large, ncp);
720 static struct namecache *
721 cache_alloc(int len, bool ts)
726 * Avoid blowout in namecache entries.
729 * 1. filesystems may end up trying to add an already existing entry
730 * (for example this can happen after a cache miss during concurrent
731 * lookup), in which case we will call cache_neg_evict despite not
733 * 2. the routine may fail to free anything and no provisions are made
734 * to make it try harder (see the inside for failure modes)
735 * 3. it only ever looks at negative entries.
737 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
738 if (cache_neg_evict_cond(lnumcache)) {
739 lnumcache = atomic_load_long(&numcache);
741 if (__predict_false(lnumcache >= ncsize)) {
742 atomic_subtract_long(&numcache, 1);
743 counter_u64_add(numdrops, 1);
746 return (cache_alloc_uma(len, ts));
750 cache_free(struct namecache *ncp)
754 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
755 cache_drop_vnode(ncp->nc_dvp);
758 atomic_subtract_long(&numcache, 1);
762 cache_free_batch(struct cache_freebatch *batch)
764 struct namecache *ncp, *nnp;
768 if (TAILQ_EMPTY(batch))
770 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
771 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
772 cache_drop_vnode(ncp->nc_dvp);
777 atomic_subtract_long(&numcache, i);
779 SDT_PROBE1(vfs, namecache, purge, batch, i);
785 * The code was made to use FNV in 2001 and this choice needs to be revisited.
787 * Short summary of the difficulty:
788 * The longest name which can be inserted is NAME_MAX characters in length (or
789 * 255 at the time of writing this comment), while majority of names used in
790 * practice are significantly shorter (mostly below 10). More importantly
791 * majority of lookups performed find names are even shorter than that.
793 * This poses a problem where hashes which do better than FNV past word size
794 * (or so) tend to come with additional overhead when finalizing the result,
795 * making them noticeably slower for the most commonly used range.
797 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
799 * When looking it up the most time consuming part by a large margin (at least
800 * on amd64) is hashing. Replacing FNV with something which pessimizes short
801 * input would make the slowest part stand out even more.
805 * TODO: With the value stored we can do better than computing the hash based
809 cache_prehash(struct vnode *vp)
812 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
816 cache_get_hash(char *name, u_char len, struct vnode *dvp)
819 return (fnv_32_buf(name, len, dvp->v_nchash));
823 cache_get_hash_iter_start(struct vnode *dvp)
826 return (dvp->v_nchash);
830 cache_get_hash_iter(char c, uint32_t hash)
833 return (fnv_32_buf(&c, 1, hash));
837 cache_get_hash_iter_finish(uint32_t hash)
843 static inline struct nchashhead *
844 NCP2BUCKET(struct namecache *ncp)
848 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
849 return (NCHHASH(hash));
852 static inline struct mtx *
853 NCP2BUCKETLOCK(struct namecache *ncp)
857 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
858 return (HASH2BUCKETLOCK(hash));
863 cache_assert_bucket_locked(struct namecache *ncp)
867 blp = NCP2BUCKETLOCK(ncp);
868 mtx_assert(blp, MA_OWNED);
872 cache_assert_bucket_unlocked(struct namecache *ncp)
876 blp = NCP2BUCKETLOCK(ncp);
877 mtx_assert(blp, MA_NOTOWNED);
880 #define cache_assert_bucket_locked(x) do { } while (0)
881 #define cache_assert_bucket_unlocked(x) do { } while (0)
884 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
886 _cache_sort_vnodes(void **p1, void **p2)
890 MPASS(*p1 != NULL || *p2 != NULL);
900 cache_lock_all_buckets(void)
904 for (i = 0; i < numbucketlocks; i++)
905 mtx_lock(&bucketlocks[i]);
909 cache_unlock_all_buckets(void)
913 for (i = 0; i < numbucketlocks; i++)
914 mtx_unlock(&bucketlocks[i]);
918 cache_lock_all_vnodes(void)
922 for (i = 0; i < numvnodelocks; i++)
923 mtx_lock(&vnodelocks[i]);
927 cache_unlock_all_vnodes(void)
931 for (i = 0; i < numvnodelocks; i++)
932 mtx_unlock(&vnodelocks[i]);
936 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
939 cache_sort_vnodes(&vlp1, &vlp2);
942 if (!mtx_trylock(vlp1))
945 if (!mtx_trylock(vlp2)) {
955 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
958 MPASS(vlp1 != NULL || vlp2 != NULL);
968 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
971 MPASS(vlp1 != NULL || vlp2 != NULL);
980 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
982 struct nchstats snap;
984 if (req->oldptr == NULL)
985 return (SYSCTL_OUT(req, 0, sizeof(snap)));
988 snap.ncs_goodhits = counter_u64_fetch(numposhits);
989 snap.ncs_neghits = counter_u64_fetch(numneghits);
990 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
991 counter_u64_fetch(numnegzaps);
992 snap.ncs_miss = counter_u64_fetch(nummisszap) +
993 counter_u64_fetch(nummiss);
995 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
997 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
998 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
999 "VFS cache effectiveness statistics");
1002 cache_recalc_neg_min(u_int val)
1005 neg_min = (ncsize * val) / 100;
1009 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1015 error = sysctl_handle_int(oidp, &val, 0, req);
1016 if (error != 0 || req->newptr == NULL)
1019 if (val == ncnegminpct)
1021 if (val < 0 || val > 99)
1024 cache_recalc_neg_min(val);
1028 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1029 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1030 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1034 * Grab an atomic snapshot of the name cache hash chain lengths
1036 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1037 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1038 "hash table stats");
1041 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1043 struct nchashhead *ncpp;
1044 struct namecache *ncp;
1045 int i, error, n_nchash, *cntbuf;
1048 n_nchash = nchash + 1; /* nchash is max index, not count */
1049 if (req->oldptr == NULL)
1050 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1051 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1052 cache_lock_all_buckets();
1053 if (n_nchash != nchash + 1) {
1054 cache_unlock_all_buckets();
1055 free(cntbuf, M_TEMP);
1058 /* Scan hash tables counting entries */
1059 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1060 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1062 cache_unlock_all_buckets();
1063 for (error = 0, i = 0; i < n_nchash; i++)
1064 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1066 free(cntbuf, M_TEMP);
1069 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1070 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1071 "nchash chain lengths");
1074 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1077 struct nchashhead *ncpp;
1078 struct namecache *ncp;
1080 int count, maxlength, used, pct;
1083 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1085 cache_lock_all_buckets();
1086 n_nchash = nchash + 1; /* nchash is max index, not count */
1090 /* Scan hash tables for applicable entries */
1091 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1093 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1098 if (maxlength < count)
1101 n_nchash = nchash + 1;
1102 cache_unlock_all_buckets();
1103 pct = (used * 100) / (n_nchash / 100);
1104 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1107 error = SYSCTL_OUT(req, &used, sizeof(used));
1110 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1113 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1118 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1119 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1120 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1124 * Negative entries management
1126 * Various workloads create plenty of negative entries and barely use them
1127 * afterwards. Moreover malicious users can keep performing bogus lookups
1128 * adding even more entries. For example "make tinderbox" as of writing this
1129 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1132 * As such, a rather aggressive eviction method is needed. The currently
1133 * employed method is a placeholder.
1135 * Entries are split over numneglists separate lists, each of which is further
1136 * split into hot and cold entries. Entries get promoted after getting a hit.
1137 * Eviction happens on addition of new entry.
1139 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1140 "Name cache negative entry statistics");
1142 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1143 "Number of negative cache entries");
1145 static COUNTER_U64_DEFINE_EARLY(neg_created);
1146 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1147 "Number of created negative entries");
1149 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1150 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1151 "Number of evicted negative entries");
1153 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1154 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1155 &neg_evict_skipped_empty,
1156 "Number of times evicting failed due to lack of entries");
1158 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1159 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1160 &neg_evict_skipped_missed,
1161 "Number of times evicting failed due to target entry disappearing");
1163 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1164 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1165 &neg_evict_skipped_contended,
1166 "Number of times evicting failed due to contention");
1168 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1169 "Number of cache hits (negative)");
1172 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1177 for (i = 0; i < numneglists; i++)
1178 out += neglists[i].nl_hotnum;
1180 return (SYSCTL_OUT(req, &out, sizeof(out)));
1182 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1183 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1184 "Number of hot negative entries");
1187 cache_neg_init(struct namecache *ncp)
1189 struct negstate *ns;
1191 ncp->nc_flag |= NCF_NEGATIVE;
1192 ns = NCP2NEGSTATE(ncp);
1195 counter_u64_add(neg_created, 1);
1198 #define CACHE_NEG_PROMOTION_THRESH 2
1201 cache_neg_hit_prep(struct namecache *ncp)
1203 struct negstate *ns;
1206 ns = NCP2NEGSTATE(ncp);
1207 n = atomic_load_char(&ns->neg_hit);
1209 if (n >= CACHE_NEG_PROMOTION_THRESH)
1211 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1214 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1218 * Nothing to do here but it is provided for completeness as some
1219 * cache_neg_hit_prep callers may end up returning without even
1220 * trying to promote.
1222 #define cache_neg_hit_abort(ncp) do { } while (0)
1225 cache_neg_hit_finish(struct namecache *ncp)
1228 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1229 counter_u64_add(numneghits, 1);
1233 * Move a negative entry to the hot list.
1236 cache_neg_promote_locked(struct namecache *ncp)
1239 struct negstate *ns;
1241 ns = NCP2NEGSTATE(ncp);
1242 nl = NCP2NEGLIST(ncp);
1243 mtx_assert(&nl->nl_lock, MA_OWNED);
1244 if ((ns->neg_flag & NEG_HOT) == 0) {
1245 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1246 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1248 ns->neg_flag |= NEG_HOT;
1253 * Move a hot negative entry to the cold list.
1256 cache_neg_demote_locked(struct namecache *ncp)
1259 struct negstate *ns;
1261 ns = NCP2NEGSTATE(ncp);
1262 nl = NCP2NEGLIST(ncp);
1263 mtx_assert(&nl->nl_lock, MA_OWNED);
1264 MPASS(ns->neg_flag & NEG_HOT);
1265 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1266 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1268 ns->neg_flag &= ~NEG_HOT;
1269 atomic_store_char(&ns->neg_hit, 0);
1273 * Move a negative entry to the hot list if it matches the lookup.
1275 * We have to take locks, but they may be contended and in the worst
1276 * case we may need to go off CPU. We don't want to spin within the
1277 * smr section and we can't block with it. Exiting the section means
1278 * the found entry could have been evicted. We are going to look it
1282 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1283 struct namecache *oncp, uint32_t hash)
1285 struct namecache *ncp;
1289 nl = NCP2NEGLIST(oncp);
1291 mtx_lock(&nl->nl_lock);
1293 * For hash iteration.
1298 * Avoid all surprises by only succeeding if we got the same entry and
1299 * bailing completely otherwise.
1300 * XXX There are no provisions to keep the vnode around, meaning we may
1301 * end up promoting a negative entry for a *new* vnode and returning
1302 * ENOENT on its account. This is the error we want to return anyway
1303 * and promotion is harmless.
1305 * In particular at this point there can be a new ncp which matches the
1306 * search but hashes to a different neglist.
1308 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1314 * No match to begin with.
1316 if (__predict_false(ncp == NULL)) {
1321 * The newly found entry may be something different...
1323 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1324 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1329 * ... and not even negative.
1331 nc_flag = atomic_load_char(&ncp->nc_flag);
1332 if ((nc_flag & NCF_NEGATIVE) == 0) {
1336 if (!cache_ncp_canuse(ncp)) {
1340 cache_neg_promote_locked(ncp);
1341 cache_neg_hit_finish(ncp);
1343 mtx_unlock(&nl->nl_lock);
1347 mtx_unlock(&nl->nl_lock);
1352 cache_neg_promote(struct namecache *ncp)
1356 nl = NCP2NEGLIST(ncp);
1357 mtx_lock(&nl->nl_lock);
1358 cache_neg_promote_locked(ncp);
1359 mtx_unlock(&nl->nl_lock);
1363 cache_neg_insert(struct namecache *ncp)
1367 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1368 cache_assert_bucket_locked(ncp);
1369 nl = NCP2NEGLIST(ncp);
1370 mtx_lock(&nl->nl_lock);
1371 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1372 mtx_unlock(&nl->nl_lock);
1373 atomic_add_long(&numneg, 1);
1377 cache_neg_remove(struct namecache *ncp)
1380 struct negstate *ns;
1382 cache_assert_bucket_locked(ncp);
1383 nl = NCP2NEGLIST(ncp);
1384 ns = NCP2NEGSTATE(ncp);
1385 mtx_lock(&nl->nl_lock);
1386 if ((ns->neg_flag & NEG_HOT) != 0) {
1387 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1390 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1392 mtx_unlock(&nl->nl_lock);
1393 atomic_subtract_long(&numneg, 1);
1396 static struct neglist *
1397 cache_neg_evict_select_list(void)
1402 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1403 nl = &neglists[c % numneglists];
1404 if (!mtx_trylock(&nl->nl_evict_lock)) {
1405 counter_u64_add(neg_evict_skipped_contended, 1);
1411 static struct namecache *
1412 cache_neg_evict_select_entry(struct neglist *nl)
1414 struct namecache *ncp, *lncp;
1415 struct negstate *ns, *lns;
1418 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1419 mtx_assert(&nl->nl_lock, MA_OWNED);
1420 ncp = TAILQ_FIRST(&nl->nl_list);
1424 lns = NCP2NEGSTATE(lncp);
1425 for (i = 1; i < 4; i++) {
1426 ncp = TAILQ_NEXT(ncp, nc_dst);
1429 ns = NCP2NEGSTATE(ncp);
1430 if (ns->neg_hit < lns->neg_hit) {
1439 cache_neg_evict(void)
1441 struct namecache *ncp, *ncp2;
1450 nl = cache_neg_evict_select_list();
1455 mtx_lock(&nl->nl_lock);
1456 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1458 cache_neg_demote_locked(ncp);
1460 ncp = cache_neg_evict_select_entry(nl);
1462 counter_u64_add(neg_evict_skipped_empty, 1);
1463 mtx_unlock(&nl->nl_lock);
1464 mtx_unlock(&nl->nl_evict_lock);
1467 nlen = ncp->nc_nlen;
1469 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1470 dvlp = VP2VNODELOCK(dvp);
1471 blp = HASH2BUCKETLOCK(hash);
1472 mtx_unlock(&nl->nl_lock);
1473 mtx_unlock(&nl->nl_evict_lock);
1477 * Note that since all locks were dropped above, the entry may be
1478 * gone or reallocated to be something else.
1480 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1481 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1482 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1486 counter_u64_add(neg_evict_skipped_missed, 1);
1490 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1491 MPASS(blp == NCP2BUCKETLOCK(ncp));
1492 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1494 cache_zap_locked(ncp);
1495 counter_u64_add(neg_evicted, 1);
1506 * Maybe evict a negative entry to create more room.
1508 * The ncnegfactor parameter limits what fraction of the total count
1509 * can comprise of negative entries. However, if the cache is just
1510 * warming up this leads to excessive evictions. As such, ncnegminpct
1511 * (recomputed to neg_min) dictates whether the above should be
1514 * Try evicting if the cache is close to full capacity regardless of
1515 * other considerations.
1518 cache_neg_evict_cond(u_long lnumcache)
1522 if (ncsize - 1000 < lnumcache)
1524 lnumneg = atomic_load_long(&numneg);
1525 if (lnumneg < neg_min)
1527 if (lnumneg * ncnegfactor < lnumcache)
1530 return (cache_neg_evict());
1534 * cache_zap_locked():
1536 * Removes a namecache entry from cache, whether it contains an actual
1537 * pointer to a vnode or if it is just a negative cache entry.
1540 cache_zap_locked(struct namecache *ncp)
1542 struct nchashhead *ncpp;
1543 struct vnode *dvp, *vp;
1548 if (!(ncp->nc_flag & NCF_NEGATIVE))
1549 cache_assert_vnode_locked(vp);
1550 cache_assert_vnode_locked(dvp);
1551 cache_assert_bucket_locked(ncp);
1553 cache_ncp_invalidate(ncp);
1555 ncpp = NCP2BUCKET(ncp);
1556 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1557 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1558 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1559 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1560 if (ncp == vp->v_cache_dd) {
1561 atomic_store_ptr(&vp->v_cache_dd, NULL);
1564 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1565 cache_neg_remove(ncp);
1567 if (ncp->nc_flag & NCF_ISDOTDOT) {
1568 if (ncp == dvp->v_cache_dd) {
1569 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1572 LIST_REMOVE(ncp, nc_src);
1573 if (LIST_EMPTY(&dvp->v_cache_src)) {
1574 ncp->nc_flag |= NCF_DVDROP;
1580 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1584 MPASS(ncp->nc_dvp == vp);
1585 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1586 cache_assert_vnode_locked(vp);
1588 blp = NCP2BUCKETLOCK(ncp);
1590 cache_zap_locked(ncp);
1595 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1598 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1601 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1602 cache_assert_vnode_locked(vp);
1604 if (ncp->nc_flag & NCF_NEGATIVE) {
1605 if (*vlpp != NULL) {
1609 cache_zap_negative_locked_vnode_kl(ncp, vp);
1613 pvlp = VP2VNODELOCK(vp);
1614 blp = NCP2BUCKETLOCK(ncp);
1615 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1616 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1618 if (*vlpp == vlp1 || *vlpp == vlp2) {
1622 if (*vlpp != NULL) {
1626 cache_sort_vnodes(&vlp1, &vlp2);
1631 if (!mtx_trylock(vlp1))
1637 cache_zap_locked(ncp);
1639 if (to_unlock != NULL)
1640 mtx_unlock(to_unlock);
1647 MPASS(*vlpp == NULL);
1653 * If trylocking failed we can get here. We know enough to take all needed locks
1654 * in the right order and re-lookup the entry.
1657 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1658 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1661 struct namecache *rncp;
1663 cache_assert_bucket_unlocked(ncp);
1665 cache_sort_vnodes(&dvlp, &vlp);
1666 cache_lock_vnodes(dvlp, vlp);
1668 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1669 if (rncp == ncp && rncp->nc_dvp == dvp &&
1670 rncp->nc_nlen == cnp->cn_namelen &&
1671 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1675 cache_zap_locked(rncp);
1677 cache_unlock_vnodes(dvlp, vlp);
1678 counter_u64_add(zap_bucket_relock_success, 1);
1683 cache_unlock_vnodes(dvlp, vlp);
1687 static int __noinline
1688 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1689 uint32_t hash, struct mtx *blp)
1691 struct mtx *dvlp, *vlp;
1694 cache_assert_bucket_locked(ncp);
1696 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1698 if (!(ncp->nc_flag & NCF_NEGATIVE))
1699 vlp = VP2VNODELOCK(ncp->nc_vp);
1700 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1701 cache_zap_locked(ncp);
1703 cache_unlock_vnodes(dvlp, vlp);
1709 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1712 static __noinline int
1713 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1715 struct namecache *ncp;
1717 struct mtx *dvlp, *dvlp2;
1721 if (cnp->cn_namelen == 2 &&
1722 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1723 dvlp = VP2VNODELOCK(dvp);
1727 ncp = dvp->v_cache_dd;
1732 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1735 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1736 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1738 MPASS(dvp->v_cache_dd == NULL);
1744 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1749 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1753 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1754 blp = HASH2BUCKETLOCK(hash);
1756 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1761 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1762 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1763 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1772 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1773 if (__predict_false(error != 0)) {
1777 counter_u64_add(numposzaps, 1);
1778 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1782 counter_u64_add(nummisszap, 1);
1783 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1787 static int __noinline
1788 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1789 struct timespec *tsp, int *ticksp)
1794 counter_u64_add(dothits, 1);
1795 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1802 * When we lookup "." we still can be asked to lock it
1805 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1806 if (ltype != VOP_ISLOCKED(*vpp)) {
1807 if (ltype == LK_EXCLUSIVE) {
1808 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1809 if (VN_IS_DOOMED((*vpp))) {
1810 /* forced unmount */
1816 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1821 static int __noinline
1822 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1823 struct timespec *tsp, int *ticksp)
1825 struct namecache_ts *ncp_ts;
1826 struct namecache *ncp;
1832 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1834 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1835 cache_remove_cnp(dvp, cnp);
1839 counter_u64_add(dotdothits, 1);
1841 dvlp = VP2VNODELOCK(dvp);
1843 ncp = dvp->v_cache_dd;
1845 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1849 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1850 if (ncp->nc_flag & NCF_NEGATIVE)
1857 goto negative_success;
1858 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1859 cache_out_ts(ncp, tsp, ticksp);
1860 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1861 NCF_DTS && tsp != NULL) {
1862 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1863 *tsp = ncp_ts->nc_dotdottime;
1867 ltype = VOP_ISLOCKED(dvp);
1869 vs = vget_prep(*vpp);
1871 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1872 vn_lock(dvp, ltype | LK_RETRY);
1873 if (VN_IS_DOOMED(dvp)) {
1885 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1886 if (cnp->cn_flags & ISLASTCN) {
1887 counter_u64_add(numnegzaps, 1);
1888 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1895 whiteout = (ncp->nc_flag & NCF_WHITE);
1896 cache_out_ts(ncp, tsp, ticksp);
1897 if (cache_neg_hit_prep(ncp))
1898 cache_neg_promote(ncp);
1900 cache_neg_hit_finish(ncp);
1903 cnp->cn_flags |= ISWHITEOUT;
1908 * Lookup a name in the name cache
1912 * - dvp: Parent directory in which to search.
1913 * - vpp: Return argument. Will contain desired vnode on cache hit.
1914 * - cnp: Parameters of the name search. The most interesting bits of
1915 * the cn_flags field have the following meanings:
1916 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1918 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1919 * - tsp: Return storage for cache timestamp. On a successful (positive
1920 * or negative) lookup, tsp will be filled with any timespec that
1921 * was stored when this cache entry was created. However, it will
1922 * be clear for "." entries.
1923 * - ticks: Return storage for alternate cache timestamp. On a successful
1924 * (positive or negative) lookup, it will contain the ticks value
1925 * that was current when the cache entry was created, unless cnp
1928 * Either both tsp and ticks have to be provided or neither of them.
1932 * - -1: A positive cache hit. vpp will contain the desired vnode.
1933 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1934 * to a forced unmount. vpp will not be modified. If the entry
1935 * is a whiteout, then the ISWHITEOUT flag will be set in
1937 * - 0: A cache miss. vpp will not be modified.
1941 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1942 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1943 * lock is not recursively acquired.
1945 static int __noinline
1946 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1947 struct timespec *tsp, int *ticksp)
1949 struct namecache *ncp;
1956 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1957 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1960 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1961 blp = HASH2BUCKETLOCK(hash);
1964 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1965 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1966 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1970 if (__predict_false(ncp == NULL)) {
1972 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
1973 counter_u64_add(nummiss, 1);
1977 if (ncp->nc_flag & NCF_NEGATIVE)
1978 goto negative_success;
1980 counter_u64_add(numposhits, 1);
1982 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1983 cache_out_ts(ncp, tsp, ticksp);
1985 vs = vget_prep(*vpp);
1987 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1995 * We don't get here with regular lookup apart from corner cases.
1997 if (__predict_true(cnp->cn_nameiop == CREATE)) {
1998 if (cnp->cn_flags & ISLASTCN) {
1999 counter_u64_add(numnegzaps, 1);
2000 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2001 if (__predict_false(error != 0)) {
2010 whiteout = (ncp->nc_flag & NCF_WHITE);
2011 cache_out_ts(ncp, tsp, ticksp);
2012 if (cache_neg_hit_prep(ncp))
2013 cache_neg_promote(ncp);
2015 cache_neg_hit_finish(ncp);
2018 cnp->cn_flags |= ISWHITEOUT;
2023 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2024 struct timespec *tsp, int *ticksp)
2026 struct namecache *ncp;
2030 bool whiteout, neg_promote;
2033 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2036 if (__predict_false(!doingcache)) {
2037 cnp->cn_flags &= ~MAKEENTRY;
2042 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2043 if (cnp->cn_namelen == 1)
2044 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2045 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2046 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2049 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2051 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2052 cache_remove_cnp(dvp, cnp);
2056 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2059 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2060 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2061 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2065 if (__predict_false(ncp == NULL)) {
2067 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2068 counter_u64_add(nummiss, 1);
2072 nc_flag = atomic_load_char(&ncp->nc_flag);
2073 if (nc_flag & NCF_NEGATIVE)
2074 goto negative_success;
2076 counter_u64_add(numposhits, 1);
2078 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2079 cache_out_ts(ncp, tsp, ticksp);
2081 if (!cache_ncp_canuse(ncp)) {
2086 vs = vget_prep_smr(*vpp);
2088 if (__predict_false(vs == VGET_NONE)) {
2092 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2099 if (cnp->cn_nameiop == CREATE) {
2100 if (cnp->cn_flags & ISLASTCN) {
2106 cache_out_ts(ncp, tsp, ticksp);
2107 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2108 neg_promote = cache_neg_hit_prep(ncp);
2109 if (!cache_ncp_canuse(ncp)) {
2110 cache_neg_hit_abort(ncp);
2116 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2119 cache_neg_hit_finish(ncp);
2123 cnp->cn_flags |= ISWHITEOUT;
2126 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2129 struct celockstate {
2133 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2134 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2137 cache_celockstate_init(struct celockstate *cel)
2140 bzero(cel, sizeof(*cel));
2144 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2147 struct mtx *vlp1, *vlp2;
2149 MPASS(cel->vlp[0] == NULL);
2150 MPASS(cel->vlp[1] == NULL);
2151 MPASS(cel->vlp[2] == NULL);
2153 MPASS(vp != NULL || dvp != NULL);
2155 vlp1 = VP2VNODELOCK(vp);
2156 vlp2 = VP2VNODELOCK(dvp);
2157 cache_sort_vnodes(&vlp1, &vlp2);
2168 cache_unlock_vnodes_cel(struct celockstate *cel)
2171 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2173 if (cel->vlp[0] != NULL)
2174 mtx_unlock(cel->vlp[0]);
2175 if (cel->vlp[1] != NULL)
2176 mtx_unlock(cel->vlp[1]);
2177 if (cel->vlp[2] != NULL)
2178 mtx_unlock(cel->vlp[2]);
2182 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2187 cache_assert_vlp_locked(cel->vlp[0]);
2188 cache_assert_vlp_locked(cel->vlp[1]);
2189 MPASS(cel->vlp[2] == NULL);
2192 vlp = VP2VNODELOCK(vp);
2195 if (vlp >= cel->vlp[1]) {
2198 if (mtx_trylock(vlp))
2200 cache_lock_vnodes_cel_3_failures++;
2201 cache_unlock_vnodes_cel(cel);
2202 if (vlp < cel->vlp[0]) {
2204 mtx_lock(cel->vlp[0]);
2205 mtx_lock(cel->vlp[1]);
2207 if (cel->vlp[0] != NULL)
2208 mtx_lock(cel->vlp[0]);
2210 mtx_lock(cel->vlp[1]);
2220 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2224 MPASS(cel->blp[0] == NULL);
2225 MPASS(cel->blp[1] == NULL);
2227 cache_sort_vnodes(&blp1, &blp2);
2238 cache_unlock_buckets_cel(struct celockstate *cel)
2241 if (cel->blp[0] != NULL)
2242 mtx_unlock(cel->blp[0]);
2243 mtx_unlock(cel->blp[1]);
2247 * Lock part of the cache affected by the insertion.
2249 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2250 * However, insertion can result in removal of an old entry. In this
2251 * case we have an additional vnode and bucketlock pair to lock.
2253 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2254 * preserving the locking order (smaller address first).
2257 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2260 struct namecache *ncp;
2261 struct mtx *blps[2];
2264 blps[0] = HASH2BUCKETLOCK(hash);
2267 cache_lock_vnodes_cel(cel, dvp, vp);
2268 if (vp == NULL || vp->v_type != VDIR)
2270 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2273 nc_flag = atomic_load_char(&ncp->nc_flag);
2274 if ((nc_flag & NCF_ISDOTDOT) == 0)
2276 MPASS(ncp->nc_dvp == vp);
2277 blps[1] = NCP2BUCKETLOCK(ncp);
2278 if ((nc_flag & NCF_NEGATIVE) != 0)
2280 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2283 * All vnodes got re-locked. Re-validate the state and if
2284 * nothing changed we are done. Otherwise restart.
2286 if (ncp == vp->v_cache_dd &&
2287 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2288 blps[1] == NCP2BUCKETLOCK(ncp) &&
2289 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2291 cache_unlock_vnodes_cel(cel);
2296 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2300 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2303 struct namecache *ncp;
2304 struct mtx *blps[2];
2307 blps[0] = HASH2BUCKETLOCK(hash);
2310 cache_lock_vnodes_cel(cel, dvp, vp);
2311 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2314 nc_flag = atomic_load_char(&ncp->nc_flag);
2315 if ((nc_flag & NCF_ISDOTDOT) == 0)
2317 MPASS(ncp->nc_dvp == dvp);
2318 blps[1] = NCP2BUCKETLOCK(ncp);
2319 if ((nc_flag & NCF_NEGATIVE) != 0)
2321 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2323 if (ncp == dvp->v_cache_dd &&
2324 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2325 blps[1] == NCP2BUCKETLOCK(ncp) &&
2326 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2328 cache_unlock_vnodes_cel(cel);
2333 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2337 cache_enter_unlock(struct celockstate *cel)
2340 cache_unlock_buckets_cel(cel);
2341 cache_unlock_vnodes_cel(cel);
2344 static void __noinline
2345 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2346 struct componentname *cnp)
2348 struct celockstate cel;
2349 struct namecache *ncp;
2353 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2355 len = cnp->cn_namelen;
2356 cache_celockstate_init(&cel);
2357 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2358 cache_enter_lock_dd(&cel, dvp, vp, hash);
2359 ncp = dvp->v_cache_dd;
2360 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2361 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2362 cache_zap_locked(ncp);
2366 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2367 cache_enter_unlock(&cel);
2373 * Add an entry to the cache.
2376 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2377 struct timespec *tsp, struct timespec *dtsp)
2379 struct celockstate cel;
2380 struct namecache *ncp, *n2, *ndd;
2381 struct namecache_ts *ncp_ts;
2382 struct nchashhead *ncpp;
2387 KASSERT(cnp->cn_namelen <= NAME_MAX,
2388 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2390 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2391 VNPASS(dvp->v_type != VNON, dvp);
2393 VNPASS(!VN_IS_DOOMED(vp), vp);
2394 VNPASS(vp->v_type != VNON, vp);
2396 if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
2398 ("%s: different vnodes for dot entry (%p; %p)\n", __func__,
2402 ("%s: same vnode for non-dot entry [%s] (%p)\n", __func__,
2403 cnp->cn_nameptr, dvp));
2407 if (__predict_false(!doingcache))
2412 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2413 if (cnp->cn_namelen == 1)
2415 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2416 cache_enter_dotdot_prep(dvp, vp, cnp);
2417 flag = NCF_ISDOTDOT;
2421 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2425 cache_celockstate_init(&cel);
2430 * Calculate the hash key and setup as much of the new
2431 * namecache entry as possible before acquiring the lock.
2433 ncp->nc_flag = flag | NCF_WIP;
2436 cache_neg_init(ncp);
2439 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2440 ncp_ts->nc_time = *tsp;
2441 ncp_ts->nc_ticks = ticks;
2442 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2444 ncp_ts->nc_dotdottime = *dtsp;
2445 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2448 len = ncp->nc_nlen = cnp->cn_namelen;
2449 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2450 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2451 ncp->nc_name[len] = '\0';
2452 cache_enter_lock(&cel, dvp, vp, hash);
2455 * See if this vnode or negative entry is already in the cache
2456 * with this name. This can happen with concurrent lookups of
2457 * the same path name.
2459 ncpp = NCHHASH(hash);
2460 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2461 if (n2->nc_dvp == dvp &&
2462 n2->nc_nlen == cnp->cn_namelen &&
2463 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2464 MPASS(cache_ncp_canuse(n2));
2465 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2467 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2468 __func__, NULL, vp, cnp->cn_nameptr));
2470 KASSERT(n2->nc_vp == vp,
2471 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2472 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2474 * Entries are supposed to be immutable unless in the
2475 * process of getting destroyed. Accommodating for
2476 * changing timestamps is possible but not worth it.
2477 * This should be harmless in terms of correctness, in
2478 * the worst case resulting in an earlier expiration.
2479 * Alternatively, the found entry can be replaced
2482 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2485 KASSERT((n2->nc_flag & NCF_TS) != 0,
2487 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2488 n2_ts->nc_time = ncp_ts->nc_time;
2489 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2491 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2492 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2496 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2498 goto out_unlock_free;
2502 if (flag == NCF_ISDOTDOT) {
2504 * See if we are trying to add .. entry, but some other lookup
2505 * has populated v_cache_dd pointer already.
2507 if (dvp->v_cache_dd != NULL)
2508 goto out_unlock_free;
2509 KASSERT(vp == NULL || vp->v_type == VDIR,
2510 ("wrong vnode type %p", vp));
2511 atomic_thread_fence_rel();
2512 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2516 if (flag != NCF_ISDOTDOT) {
2518 * For this case, the cache entry maps both the
2519 * directory name in it and the name ".." for the
2520 * directory's parent.
2522 if ((ndd = vp->v_cache_dd) != NULL) {
2523 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2524 cache_zap_locked(ndd);
2528 atomic_thread_fence_rel();
2529 atomic_store_ptr(&vp->v_cache_dd, ncp);
2530 } else if (vp->v_type != VDIR) {
2531 if (vp->v_cache_dd != NULL) {
2532 atomic_store_ptr(&vp->v_cache_dd, NULL);
2537 if (flag != NCF_ISDOTDOT) {
2538 if (LIST_EMPTY(&dvp->v_cache_src)) {
2539 cache_hold_vnode(dvp);
2541 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2545 * If the entry is "negative", we place it into the
2546 * "negative" cache queue, otherwise, we place it into the
2547 * destination vnode's cache entries queue.
2550 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2551 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2554 if (cnp->cn_flags & ISWHITEOUT)
2555 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2556 cache_neg_insert(ncp);
2557 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2562 * Insert the new namecache entry into the appropriate chain
2563 * within the cache entries table.
2565 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2567 atomic_thread_fence_rel();
2569 * Mark the entry as fully constructed.
2570 * It is immutable past this point until its removal.
2572 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2574 cache_enter_unlock(&cel);
2579 cache_enter_unlock(&cel);
2585 * A variant of the above accepting flags.
2587 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2589 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2590 * happens to match and it is doing it in an inefficient manner. It was added
2591 * to accommodate NFS which runs into a case where the target for a given name
2592 * may change from under it. Note this does nothing to solve the following
2593 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2594 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2597 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2598 struct timespec *tsp, struct timespec *dtsp, int flags)
2601 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2603 if (flags & VFS_CACHE_DROPOLD)
2604 cache_remove_cnp(dvp, cnp);
2605 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2609 cache_roundup_2(u_int val)
2613 for (res = 1; res <= val; res <<= 1)
2619 static struct nchashhead *
2620 nchinittbl(u_long elements, u_long *hashmask)
2622 struct nchashhead *hashtbl;
2625 hashsize = cache_roundup_2(elements) / 2;
2627 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2628 for (i = 0; i < hashsize; i++)
2629 CK_SLIST_INIT(&hashtbl[i]);
2630 *hashmask = hashsize - 1;
2635 ncfreetbl(struct nchashhead *hashtbl)
2638 free(hashtbl, M_VFSCACHE);
2642 * Name cache initialization, from vfs_init() when we are booting
2645 nchinit(void *dummy __unused)
2649 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2650 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2651 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2652 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2653 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2654 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2655 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2656 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2658 VFS_SMR_ZONE_SET(cache_zone_small);
2659 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2660 VFS_SMR_ZONE_SET(cache_zone_large);
2661 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2663 ncsize = desiredvnodes * ncsizefactor;
2664 cache_recalc_neg_min(ncnegminpct);
2665 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2666 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2667 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2669 if (ncbuckethash > nchash)
2670 ncbuckethash = nchash;
2671 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2673 for (i = 0; i < numbucketlocks; i++)
2674 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2675 ncvnodehash = ncbuckethash;
2676 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2678 for (i = 0; i < numvnodelocks; i++)
2679 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2681 for (i = 0; i < numneglists; i++) {
2682 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2683 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2684 TAILQ_INIT(&neglists[i].nl_list);
2685 TAILQ_INIT(&neglists[i].nl_hotlist);
2688 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2691 cache_vnode_init(struct vnode *vp)
2694 LIST_INIT(&vp->v_cache_src);
2695 TAILQ_INIT(&vp->v_cache_dst);
2696 vp->v_cache_dd = NULL;
2701 * Induce transient cache misses for lockless operation in cache_lookup() by
2702 * using a temporary hash table.
2704 * This will force a fs lookup.
2706 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2707 * to observe all CPUs not performing the lookup.
2710 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2713 MPASS(temphash < nchash);
2715 * Change the size. The new size is smaller and can safely be used
2716 * against the existing table. All lookups which now hash wrong will
2717 * result in a cache miss, which all callers are supposed to know how
2720 atomic_store_long(&nchash, temphash);
2721 atomic_thread_fence_rel();
2722 vfs_smr_synchronize();
2724 * At this point everyone sees the updated hash value, but they still
2725 * see the old table.
2727 atomic_store_ptr(&nchashtbl, temptbl);
2728 atomic_thread_fence_rel();
2729 vfs_smr_synchronize();
2731 * At this point everyone sees the updated table pointer and size pair.
2736 * Set the new hash table.
2738 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2739 * lockless operation in cache_lookup().
2742 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2745 MPASS(nchash < new_hash);
2747 * Change the pointer first. This wont result in out of bounds access
2748 * since the temporary table is guaranteed to be smaller.
2750 atomic_store_ptr(&nchashtbl, new_tbl);
2751 atomic_thread_fence_rel();
2752 vfs_smr_synchronize();
2754 * At this point everyone sees the updated pointer value, but they
2755 * still see the old size.
2757 atomic_store_long(&nchash, new_hash);
2758 atomic_thread_fence_rel();
2759 vfs_smr_synchronize();
2761 * At this point everyone sees the updated table pointer and size pair.
2766 cache_changesize(u_long newmaxvnodes)
2768 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2769 u_long new_nchash, old_nchash, temphash;
2770 struct namecache *ncp;
2775 newncsize = newmaxvnodes * ncsizefactor;
2776 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2777 if (newmaxvnodes < numbucketlocks)
2778 newmaxvnodes = numbucketlocks;
2780 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2781 /* If same hash table size, nothing to do */
2782 if (nchash == new_nchash) {
2783 ncfreetbl(new_nchashtbl);
2787 temptbl = nchinittbl(1, &temphash);
2790 * Move everything from the old hash table to the new table.
2791 * None of the namecache entries in the table can be removed
2792 * because to do so, they have to be removed from the hash table.
2794 cache_lock_all_vnodes();
2795 cache_lock_all_buckets();
2796 old_nchashtbl = nchashtbl;
2797 old_nchash = nchash;
2798 cache_changesize_set_temp(temptbl, temphash);
2799 for (i = 0; i <= old_nchash; i++) {
2800 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2801 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2803 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2804 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2808 cache_recalc_neg_min(ncnegminpct);
2809 cache_changesize_set_new(new_nchashtbl, new_nchash);
2810 cache_unlock_all_buckets();
2811 cache_unlock_all_vnodes();
2812 ncfreetbl(old_nchashtbl);
2817 * Remove all entries from and to a particular vnode.
2820 cache_purge_impl(struct vnode *vp)
2822 struct cache_freebatch batch;
2823 struct namecache *ncp;
2824 struct mtx *vlp, *vlp2;
2827 vlp = VP2VNODELOCK(vp);
2831 while (!LIST_EMPTY(&vp->v_cache_src)) {
2832 ncp = LIST_FIRST(&vp->v_cache_src);
2833 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2835 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2837 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2838 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2839 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2841 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2843 ncp = vp->v_cache_dd;
2845 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2846 ("lost dotdot link"));
2847 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2849 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2851 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2855 cache_free_batch(&batch);
2859 * Opportunistic check to see if there is anything to do.
2862 cache_has_entries(struct vnode *vp)
2865 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2866 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2872 cache_purge(struct vnode *vp)
2875 SDT_PROBE1(vfs, namecache, purge, done, vp);
2876 if (!cache_has_entries(vp))
2878 cache_purge_impl(vp);
2882 * Only to be used by vgone.
2885 cache_purge_vgone(struct vnode *vp)
2889 VNPASS(VN_IS_DOOMED(vp), vp);
2890 if (cache_has_entries(vp)) {
2891 cache_purge_impl(vp);
2896 * Serialize against a potential thread doing cache_purge.
2898 vlp = VP2VNODELOCK(vp);
2899 mtx_wait_unlocked(vlp);
2900 if (cache_has_entries(vp)) {
2901 cache_purge_impl(vp);
2908 * Remove all negative entries for a particular directory vnode.
2911 cache_purge_negative(struct vnode *vp)
2913 struct cache_freebatch batch;
2914 struct namecache *ncp, *nnp;
2917 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2918 if (LIST_EMPTY(&vp->v_cache_src))
2921 vlp = VP2VNODELOCK(vp);
2923 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2924 if (!(ncp->nc_flag & NCF_NEGATIVE))
2926 cache_zap_negative_locked_vnode_kl(ncp, vp);
2927 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2930 cache_free_batch(&batch);
2934 * Entry points for modifying VOP operations.
2937 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2938 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2941 ASSERT_VOP_IN_SEQC(fdvp);
2942 ASSERT_VOP_IN_SEQC(fvp);
2943 ASSERT_VOP_IN_SEQC(tdvp);
2945 ASSERT_VOP_IN_SEQC(tvp);
2950 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2951 ("%s: lingering negative entry", __func__));
2953 cache_remove_cnp(tdvp, tcnp);
2959 * Historically renaming was always purging all revelang entries,
2960 * but that's quite wasteful. In particular turns out that in many cases
2961 * the target file is immediately accessed after rename, inducing a cache
2964 * Recode this to reduce relocking and reuse the existing entry (if any)
2965 * instead of just removing it above and allocating a new one here.
2967 if (cache_rename_add) {
2968 cache_enter(tdvp, fvp, tcnp);
2973 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2976 ASSERT_VOP_IN_SEQC(dvp);
2977 ASSERT_VOP_IN_SEQC(vp);
2983 * Validate that if an entry exists it matches.
2986 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2988 struct namecache *ncp;
2992 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2993 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2995 blp = HASH2BUCKETLOCK(hash);
2997 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2998 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2999 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
3000 if (ncp->nc_vp != vp)
3001 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
3002 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3010 * Flush all entries referencing a particular filesystem.
3013 cache_purgevfs(struct mount *mp)
3015 struct vnode *vp, *mvp;
3016 size_t visited, purged;
3018 visited = purged = 0;
3020 * Somewhat wasteful iteration over all vnodes. Would be better to
3021 * support filtering and avoid the interlock to begin with.
3023 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3025 if (!cache_has_entries(vp)) {
3036 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3040 * Perform canonical checks and cache lookup and pass on to filesystem
3041 * through the vop_cachedlookup only if needed.
3045 vfs_cache_lookup(struct vop_lookup_args *ap)
3049 struct vnode **vpp = ap->a_vpp;
3050 struct componentname *cnp = ap->a_cnp;
3051 int flags = cnp->cn_flags;
3056 if (dvp->v_type != VDIR)
3059 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3060 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3063 error = vn_dir_check_exec(dvp, cnp);
3067 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3069 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3075 /* Implementation of the getcwd syscall. */
3077 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3083 buflen = uap->buflen;
3084 if (__predict_false(buflen < 2))
3086 if (buflen > MAXPATHLEN)
3087 buflen = MAXPATHLEN;
3089 buf = uma_zalloc(namei_zone, M_WAITOK);
3090 error = vn_getcwd(buf, &retbuf, &buflen);
3092 error = copyout(retbuf, uap->buf, buflen);
3093 uma_zfree(namei_zone, buf);
3098 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3104 pwd = pwd_get_smr();
3105 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3107 VFS_SMR_ASSERT_NOT_ENTERED();
3109 pwd = pwd_hold(curthread);
3110 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3116 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3123 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3124 size_t size, int flags, enum uio_seg pathseg)
3126 struct nameidata nd;
3127 char *retbuf, *freebuf;
3132 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
3133 pathseg, path, fd, &cap_fstat_rights, td);
3134 if ((error = namei(&nd)) != 0)
3137 if (nd.ni_vp->v_type == VREG && nd.ni_dvp->v_type != VDIR &&
3138 (nd.ni_vp->v_vflag & VV_ROOT) != 0) {
3140 * This happens if vp is a file mount. The call to
3141 * vn_fullpath_hardlink can panic if path resolution can't be
3142 * handled without the directory.
3144 * To resolve this, we find the vnode which was mounted on -
3145 * this should have a unique global path since we disallow
3146 * mounting on linked files.
3148 struct vnode *covered_vp;
3149 error = vn_lock(nd.ni_vp, LK_SHARED);
3152 covered_vp = nd.ni_vp->v_mount->mnt_vnodecovered;
3154 VOP_UNLOCK(nd.ni_vp);
3155 error = vn_fullpath(covered_vp, &retbuf, &freebuf);
3158 error = vn_fullpath_hardlink(nd.ni_vp, nd.ni_dvp, nd.ni_cnd.cn_nameptr,
3159 nd.ni_cnd.cn_namelen, &retbuf, &freebuf, &size);
3162 error = copyout(retbuf, buf, size);
3163 free(freebuf, M_TEMP);
3171 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3174 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3175 uap->flags, UIO_USERSPACE));
3179 * Retrieve the full filesystem path that correspond to a vnode from the name
3180 * cache (if available)
3183 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3190 if (__predict_false(vp == NULL))
3193 buflen = MAXPATHLEN;
3194 buf = malloc(buflen, M_TEMP, M_WAITOK);
3196 pwd = pwd_get_smr();
3197 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3198 VFS_SMR_ASSERT_NOT_ENTERED();
3200 pwd = pwd_hold(curthread);
3201 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3212 * This function is similar to vn_fullpath, but it attempts to lookup the
3213 * pathname relative to the global root mount point. This is required for the
3214 * auditing sub-system, as audited pathnames must be absolute, relative to the
3215 * global root mount point.
3218 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3224 if (__predict_false(vp == NULL))
3226 buflen = MAXPATHLEN;
3227 buf = malloc(buflen, M_TEMP, M_WAITOK);
3229 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3230 VFS_SMR_ASSERT_NOT_ENTERED();
3232 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3241 static struct namecache *
3242 vn_dd_from_dst(struct vnode *vp)
3244 struct namecache *ncp;
3246 cache_assert_vnode_locked(vp);
3247 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3248 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3255 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3258 struct namecache *ncp;
3262 vlp = VP2VNODELOCK(*vp);
3264 ncp = (*vp)->v_cache_dd;
3265 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3266 KASSERT(ncp == vn_dd_from_dst(*vp),
3267 ("%s: mismatch for dd entry (%p != %p)", __func__,
3268 ncp, vn_dd_from_dst(*vp)));
3270 ncp = vn_dd_from_dst(*vp);
3273 if (*buflen < ncp->nc_nlen) {
3276 counter_u64_add(numfullpathfail4, 1);
3278 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3282 *buflen -= ncp->nc_nlen;
3283 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3284 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3293 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3296 vn_lock(*vp, LK_SHARED | LK_RETRY);
3297 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3300 counter_u64_add(numfullpathfail2, 1);
3301 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3306 if (VN_IS_DOOMED(dvp)) {
3307 /* forced unmount */
3310 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3314 * *vp has its use count incremented still.
3321 * Resolve a directory to a pathname.
3323 * The name of the directory can always be found in the namecache or fetched
3324 * from the filesystem. There is also guaranteed to be only one parent, meaning
3325 * we can just follow vnodes up until we find the root.
3327 * The vnode must be referenced.
3330 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3331 size_t *len, size_t addend)
3333 #ifdef KDTRACE_HOOKS
3334 struct vnode *startvp = vp;
3339 bool slash_prefixed;
3341 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3342 VNPASS(vp->v_usecount > 0, vp);
3346 slash_prefixed = true;
3351 slash_prefixed = false;
3356 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3357 counter_u64_add(numfullpathcalls, 1);
3358 while (vp != rdir && vp != rootvnode) {
3360 * The vp vnode must be already fully constructed,
3361 * since it is either found in namecache or obtained
3362 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3363 * without obtaining the vnode lock.
3365 if ((vp->v_vflag & VV_ROOT) != 0) {
3366 vn_lock(vp, LK_RETRY | LK_SHARED);
3369 * With the vnode locked, check for races with
3370 * unmount, forced or not. Note that we
3371 * already verified that vp is not equal to
3372 * the root vnode, which means that
3373 * mnt_vnodecovered can be NULL only for the
3376 if (VN_IS_DOOMED(vp) ||
3377 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3378 vp1->v_mountedhere != vp->v_mount) {
3381 SDT_PROBE3(vfs, namecache, fullpath, return,
3391 if (vp->v_type != VDIR) {
3393 counter_u64_add(numfullpathfail1, 1);
3395 SDT_PROBE3(vfs, namecache, fullpath, return,
3399 error = vn_vptocnp(&vp, buf, &buflen);
3405 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3409 buf[--buflen] = '/';
3410 slash_prefixed = true;
3414 if (!slash_prefixed) {
3417 counter_u64_add(numfullpathfail4, 1);
3418 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3422 buf[--buflen] = '/';
3424 counter_u64_add(numfullpathfound, 1);
3427 *retbuf = buf + buflen;
3428 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3435 * Resolve an arbitrary vnode to a pathname.
3438 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3439 * resolve to a different path than the one used to find it
3440 * - namecache is not mandatory, meaning names are not guaranteed to be added
3441 * (in which case resolving fails)
3443 static void __inline
3444 cache_rev_failed_impl(int *reason, int line)
3449 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3452 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3453 char **retbuf, size_t *buflen, size_t addend)
3455 #ifdef KDTRACE_HOOKS
3456 struct vnode *startvp = vp;
3460 struct namecache *ncp;
3464 #ifdef KDTRACE_HOOKS
3467 seqc_t vp_seqc, tvp_seqc;
3470 VFS_SMR_ASSERT_ENTERED();
3472 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3477 orig_buflen = *buflen;
3480 MPASS(*buflen >= 2);
3482 buf[*buflen] = '\0';
3485 if (vp == rdir || vp == rootvnode) {
3493 #ifdef KDTRACE_HOOKS
3497 ncp = NULL; /* for sdt probe down below */
3498 vp_seqc = vn_seqc_read_any(vp);
3499 if (seqc_in_modify(vp_seqc)) {
3500 cache_rev_failed(&reason);
3505 #ifdef KDTRACE_HOOKS
3508 if ((vp->v_vflag & VV_ROOT) != 0) {
3509 mp = atomic_load_ptr(&vp->v_mount);
3511 cache_rev_failed(&reason);
3514 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3515 tvp_seqc = vn_seqc_read_any(tvp);
3516 if (seqc_in_modify(tvp_seqc)) {
3517 cache_rev_failed(&reason);
3520 if (!vn_seqc_consistent(vp, vp_seqc)) {
3521 cache_rev_failed(&reason);
3528 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3530 cache_rev_failed(&reason);
3533 nc_flag = atomic_load_char(&ncp->nc_flag);
3534 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3535 cache_rev_failed(&reason);
3538 if (ncp->nc_nlen >= *buflen) {
3539 cache_rev_failed(&reason);
3543 *buflen -= ncp->nc_nlen;
3544 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3548 tvp_seqc = vn_seqc_read_any(tvp);
3549 if (seqc_in_modify(tvp_seqc)) {
3550 cache_rev_failed(&reason);
3553 if (!vn_seqc_consistent(vp, vp_seqc)) {
3554 cache_rev_failed(&reason);
3558 * Acquire fence provided by vn_seqc_read_any above.
3560 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3561 cache_rev_failed(&reason);
3564 if (!cache_ncp_canuse(ncp)) {
3565 cache_rev_failed(&reason);
3570 if (vp == rdir || vp == rootvnode)
3575 *retbuf = buf + *buflen;
3576 *buflen = orig_buflen - *buflen + addend;
3577 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3581 *buflen = orig_buflen;
3582 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3588 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3591 size_t orig_buflen, addend;
3597 orig_buflen = *buflen;
3601 if (vp->v_type != VDIR) {
3603 buf[*buflen] = '\0';
3604 error = vn_vptocnp(&vp, buf, buflen);
3613 addend = orig_buflen - *buflen;
3616 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3620 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3622 * Since the namecache does not track hardlinks, the caller is
3623 * expected to first look up the target vnode with SAVENAME |
3624 * WANTPARENT flags passed to namei to get dvp and vp.
3626 * Then we have 2 cases:
3627 * - if the found vnode is a directory, the path can be constructed just by
3628 * following names up the chain
3629 * - otherwise we populate the buffer with the saved name and start resolving
3633 vn_fullpath_hardlink(struct vnode *vp, struct vnode *dvp,
3634 const char *hrdl_name, size_t hrdl_name_length,
3635 char **retbuf, char **freebuf, size_t *buflen)
3645 if (*buflen > MAXPATHLEN)
3646 *buflen = MAXPATHLEN;
3648 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3653 * Check for VBAD to work around the vp_crossmp bug in lookup().
3655 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3656 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3657 * If the type is VDIR (like in this very case) we can skip looking
3658 * at ni_dvp in the first place. However, since vnodes get passed here
3659 * unlocked the target may transition to doomed state (type == VBAD)
3660 * before we get to evaluate the condition. If this happens, we will
3661 * populate part of the buffer and descend to vn_fullpath_dir with
3662 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3664 * This should be atomic_load(&vp->v_type) but it is illegal to take
3665 * an address of a bit field, even if said field is sized to char.
3666 * Work around the problem by reading the value into a full-sized enum
3667 * and then re-reading it with atomic_load which will still prevent
3668 * the compiler from re-reading down the road.
3671 type = atomic_load_int(&type);
3677 addend = hrdl_name_length + 2;
3678 if (*buflen < addend) {
3683 tmpbuf = buf + *buflen;
3685 memcpy(&tmpbuf[1], hrdl_name, hrdl_name_length);
3686 tmpbuf[addend - 1] = '\0';
3691 pwd = pwd_get_smr();
3692 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3694 VFS_SMR_ASSERT_NOT_ENTERED();
3696 pwd = pwd_hold(curthread);
3698 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3714 vn_dir_dd_ino(struct vnode *vp)
3716 struct namecache *ncp;
3721 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3722 vlp = VP2VNODELOCK(vp);
3724 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3725 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3728 vs = vget_prep(ddvp);
3730 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3739 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3741 struct namecache *ncp;
3745 vlp = VP2VNODELOCK(vp);
3747 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3748 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3754 l = min(ncp->nc_nlen, buflen - 1);
3755 memcpy(buf, ncp->nc_name, l);
3762 * This function updates path string to vnode's full global path
3763 * and checks the size of the new path string against the pathlen argument.
3765 * Requires a locked, referenced vnode.
3766 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3768 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3769 * because it falls back to the ".." lookup if the namecache lookup fails.
3772 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3775 struct nameidata nd;
3780 ASSERT_VOP_ELOCKED(vp, __func__);
3782 /* Construct global filesystem path from vp. */
3784 error = vn_fullpath_global(vp, &rpath, &fbuf);
3791 if (strlen(rpath) >= pathlen) {
3793 error = ENAMETOOLONG;
3798 * Re-lookup the vnode by path to detect a possible rename.
3799 * As a side effect, the vnode is relocked.
3800 * If vnode was renamed, return ENOENT.
3802 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3803 UIO_SYSSPACE, path, td);
3809 NDFREE(&nd, NDF_ONLY_PNBUF);
3813 strcpy(path, rpath);
3825 * This is similar to vn_path_to_global_path but allows for regular
3826 * files which may not be present in the cache.
3828 * Requires a locked, referenced vnode.
3829 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3832 vn_path_to_global_path_hardlink(struct thread *td, struct vnode *vp,
3833 struct vnode *dvp, char *path, u_int pathlen, const char *leaf_name,
3836 struct nameidata nd;
3842 ASSERT_VOP_ELOCKED(vp, __func__);
3845 * Construct global filesystem path from dvp, vp and leaf
3849 error = vn_fullpath_hardlink(vp, dvp, leaf_name, leaf_length,
3850 &rpath, &fbuf, &len);
3857 if (strlen(rpath) >= pathlen) {
3859 error = ENAMETOOLONG;
3864 * Re-lookup the vnode by path to detect a possible rename.
3865 * As a side effect, the vnode is relocked.
3866 * If vnode was renamed, return ENOENT.
3868 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path, td);
3878 strcpy(path, rpath);
3891 db_print_vpath(struct vnode *vp)
3894 while (vp != NULL) {
3895 db_printf("%p: ", vp);
3896 if (vp == rootvnode) {
3900 if (vp->v_vflag & VV_ROOT) {
3901 db_printf("<mount point>");
3902 vp = vp->v_mount->mnt_vnodecovered;
3904 struct namecache *ncp;
3908 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3911 for (i = 0; i < ncp->nc_nlen; i++)
3912 db_printf("%c", *ncn++);
3925 DB_SHOW_COMMAND(vpath, db_show_vpath)
3930 db_printf("usage: show vpath <struct vnode *>\n");
3934 vp = (struct vnode *)addr;
3940 static int cache_fast_lookup = 1;
3942 #define CACHE_FPL_FAILED -2020
3945 cache_fast_lookup_enabled_recalc(void)
3951 mac_on = mac_vnode_check_lookup_enabled();
3952 mac_on |= mac_vnode_check_readlink_enabled();
3957 lookup_flag = atomic_load_int(&cache_fast_lookup);
3958 if (lookup_flag && !mac_on) {
3959 atomic_store_char(&cache_fast_lookup_enabled, true);
3961 atomic_store_char(&cache_fast_lookup_enabled, false);
3966 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
3970 old = atomic_load_int(&cache_fast_lookup);
3971 error = sysctl_handle_int(oidp, arg1, arg2, req);
3972 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
3973 cache_fast_lookup_enabled_recalc();
3976 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
3977 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
3980 * Components of nameidata (or objects it can point to) which may
3981 * need restoring in case fast path lookup fails.
3983 struct nameidata_outer {
3988 struct nameidata_saved {
3996 struct cache_fpl_debug {
4002 struct nameidata *ndp;
4003 struct componentname *cnp;
4010 struct nameidata_saved snd;
4011 struct nameidata_outer snd_outer;
4013 enum cache_fpl_status status:8;
4019 struct cache_fpl_debug debug;
4023 static bool cache_fplookup_mp_supported(struct mount *mp);
4024 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
4025 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
4026 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
4027 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
4028 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
4029 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
4030 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
4031 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
4032 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
4035 cache_fpl_cleanup_cnp(struct componentname *cnp)
4038 uma_zfree(namei_zone, cnp->cn_pnbuf);
4040 cnp->cn_pnbuf = NULL;
4041 cnp->cn_nameptr = NULL;
4045 static struct vnode *
4046 cache_fpl_handle_root(struct cache_fpl *fpl)
4048 struct nameidata *ndp;
4049 struct componentname *cnp;
4054 MPASS(*(cnp->cn_nameptr) == '/');
4056 cache_fpl_pathlen_dec(fpl);
4058 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4061 cache_fpl_pathlen_dec(fpl);
4062 } while (*(cnp->cn_nameptr) == '/');
4065 return (ndp->ni_rootdir);
4069 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
4072 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
4073 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
4077 cache_fpl_checkpoint(struct cache_fpl *fpl)
4081 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
4082 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4087 cache_fpl_restore_partial(struct cache_fpl *fpl)
4090 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4092 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4097 cache_fpl_restore_abort(struct cache_fpl *fpl)
4100 cache_fpl_restore_partial(fpl);
4102 * It is 0 on entry by API contract.
4104 fpl->ndp->ni_resflags = 0;
4105 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4106 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4110 #define cache_fpl_smr_assert_entered(fpl) ({ \
4111 struct cache_fpl *_fpl = (fpl); \
4112 MPASS(_fpl->in_smr == true); \
4113 VFS_SMR_ASSERT_ENTERED(); \
4115 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4116 struct cache_fpl *_fpl = (fpl); \
4117 MPASS(_fpl->in_smr == false); \
4118 VFS_SMR_ASSERT_NOT_ENTERED(); \
4121 cache_fpl_assert_status(struct cache_fpl *fpl)
4124 switch (fpl->status) {
4125 case CACHE_FPL_STATUS_UNSET:
4126 __assert_unreachable();
4128 case CACHE_FPL_STATUS_DESTROYED:
4129 case CACHE_FPL_STATUS_ABORTED:
4130 case CACHE_FPL_STATUS_PARTIAL:
4131 case CACHE_FPL_STATUS_HANDLED:
4136 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4137 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4138 #define cache_fpl_assert_status(fpl) do { } while (0)
4141 #define cache_fpl_smr_enter_initial(fpl) ({ \
4142 struct cache_fpl *_fpl = (fpl); \
4144 _fpl->in_smr = true; \
4147 #define cache_fpl_smr_enter(fpl) ({ \
4148 struct cache_fpl *_fpl = (fpl); \
4149 MPASS(_fpl->in_smr == false); \
4151 _fpl->in_smr = true; \
4154 #define cache_fpl_smr_exit(fpl) ({ \
4155 struct cache_fpl *_fpl = (fpl); \
4156 MPASS(_fpl->in_smr == true); \
4158 _fpl->in_smr = false; \
4162 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4165 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4166 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4167 ("%s: converting to abort from %d at %d, set at %d\n",
4168 __func__, fpl->status, line, fpl->line));
4170 cache_fpl_smr_assert_not_entered(fpl);
4171 fpl->status = CACHE_FPL_STATUS_ABORTED;
4173 return (CACHE_FPL_FAILED);
4176 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4178 static int __noinline
4179 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4181 struct nameidata *ndp;
4182 struct componentname *cnp;
4187 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4188 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4189 ("%s: converting to abort from %d at %d, set at %d\n",
4190 __func__, fpl->status, line, fpl->line));
4192 fpl->status = CACHE_FPL_STATUS_ABORTED;
4195 cache_fpl_smr_exit(fpl);
4196 cache_fpl_restore_abort(fpl);
4198 * Resolving symlinks overwrites data passed by the caller.
4201 if (ndp->ni_loopcnt > 0) {
4202 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4203 cache_fpl_cleanup_cnp(cnp);
4205 return (CACHE_FPL_FAILED);
4208 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4210 static int __noinline
4211 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4214 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4215 ("%s: setting to partial at %d, but already set to %d at %d\n",
4216 __func__, line, fpl->status, fpl->line));
4217 cache_fpl_smr_assert_entered(fpl);
4218 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4220 return (cache_fplookup_partial_setup(fpl));
4223 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4226 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4229 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4230 ("%s: setting to handled at %d, but already set to %d at %d\n",
4231 __func__, line, fpl->status, fpl->line));
4232 cache_fpl_smr_assert_not_entered(fpl);
4233 fpl->status = CACHE_FPL_STATUS_HANDLED;
4238 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4241 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4244 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4245 ("%s: setting to handled at %d, but already set to %d at %d\n",
4246 __func__, line, fpl->status, fpl->line));
4248 MPASS(error != CACHE_FPL_FAILED);
4249 cache_fpl_smr_assert_not_entered(fpl);
4250 fpl->status = CACHE_FPL_STATUS_HANDLED;
4254 fpl->savename = false;
4258 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4261 cache_fpl_terminated(struct cache_fpl *fpl)
4264 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4267 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4268 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4269 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | SAVENAME | SAVESTART | \
4270 WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | \
4273 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4274 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4276 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4277 "supported and internal flags overlap");
4280 cache_fpl_islastcn(struct nameidata *ndp)
4283 return (*ndp->ni_next == 0);
4287 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4290 MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4291 return (*(fpl->nulchar - 1) == '/');
4295 cache_fpl_isdotdot(struct componentname *cnp)
4298 if (cnp->cn_namelen == 2 &&
4299 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4305 cache_can_fplookup(struct cache_fpl *fpl)
4307 struct nameidata *ndp;
4308 struct componentname *cnp;
4313 td = cnp->cn_thread;
4315 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4316 cache_fpl_aborted_early(fpl);
4319 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4320 cache_fpl_aborted_early(fpl);
4323 if (IN_CAPABILITY_MODE(td)) {
4324 cache_fpl_aborted_early(fpl);
4327 if (AUDITING_TD(td)) {
4328 cache_fpl_aborted_early(fpl);
4331 if (ndp->ni_startdir != NULL) {
4332 cache_fpl_aborted_early(fpl);
4338 static int __noinline
4339 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4341 struct nameidata *ndp;
4342 struct componentname *cnp;
4349 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4350 if (__predict_false(error != 0)) {
4351 return (cache_fpl_aborted(fpl));
4353 fpl->fsearch = fsearch;
4354 if ((*vpp)->v_type != VDIR) {
4355 if (!((cnp->cn_flags & EMPTYPATH) != 0 && cnp->cn_pnbuf[0] == '\0')) {
4356 cache_fpl_smr_exit(fpl);
4357 return (cache_fpl_handled_error(fpl, ENOTDIR));
4363 static int __noinline
4364 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4367 struct componentname *cnp;
4373 cache_fpl_smr_exit(fpl);
4374 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4375 return (cache_fpl_handled_error(fpl, ENOENT));
4377 return (cache_fpl_aborted(fpl));
4381 * The target vnode is not supported, prepare for the slow path to take over.
4383 static int __noinline
4384 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4386 struct nameidata *ndp;
4387 struct componentname *cnp;
4397 dvp_seqc = fpl->dvp_seqc;
4399 if (!pwd_hold_smr(pwd)) {
4400 return (cache_fpl_aborted(fpl));
4404 * Note that seqc is checked before the vnode is locked, so by
4405 * the time regular lookup gets to it it may have moved.
4407 * Ultimately this does not affect correctness, any lookup errors
4408 * are userspace racing with itself. It is guaranteed that any
4409 * path which ultimately gets found could also have been found
4410 * by regular lookup going all the way in absence of concurrent
4413 dvs = vget_prep_smr(dvp);
4414 cache_fpl_smr_exit(fpl);
4415 if (__predict_false(dvs == VGET_NONE)) {
4417 return (cache_fpl_aborted(fpl));
4420 vget_finish_ref(dvp, dvs);
4421 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4424 return (cache_fpl_aborted(fpl));
4427 cache_fpl_restore_partial(fpl);
4429 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4430 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4431 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4435 ndp->ni_startdir = dvp;
4436 cnp->cn_flags |= MAKEENTRY;
4437 if (cache_fpl_islastcn(ndp))
4438 cnp->cn_flags |= ISLASTCN;
4439 if (cache_fpl_isdotdot(cnp))
4440 cnp->cn_flags |= ISDOTDOT;
4443 * Skip potential extra slashes parsing did not take care of.
4444 * cache_fplookup_skip_slashes explains the mechanism.
4446 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4449 cache_fpl_pathlen_dec(fpl);
4450 } while (*(cnp->cn_nameptr) == '/');
4453 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4455 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4456 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4457 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4458 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4465 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4467 struct componentname *cnp;
4474 tvp_seqc = fpl->tvp_seqc;
4476 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4477 lkflags = LK_SHARED;
4478 if ((cnp->cn_flags & LOCKSHARED) == 0)
4479 lkflags = LK_EXCLUSIVE;
4480 error = vget_finish(tvp, lkflags, tvs);
4481 if (__predict_false(error != 0)) {
4482 return (cache_fpl_aborted(fpl));
4485 vget_finish_ref(tvp, tvs);
4488 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4489 if ((cnp->cn_flags & LOCKLEAF) != 0)
4493 return (cache_fpl_aborted(fpl));
4496 return (cache_fpl_handled(fpl));
4500 * They want to possibly modify the state of the namecache.
4502 static int __noinline
4503 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4505 struct nameidata *ndp;
4506 struct componentname *cnp;
4508 struct vnode *dvp, *tvp;
4517 dvp_seqc = fpl->dvp_seqc;
4519 MPASS(*(cnp->cn_nameptr) != '/');
4520 MPASS(cache_fpl_islastcn(ndp));
4521 if ((cnp->cn_flags & LOCKPARENT) == 0)
4522 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4523 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4524 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4525 cnp->cn_nameiop == RENAME);
4526 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4527 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4529 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4530 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4534 * Regular lookup nulifies the slash, which we don't do here.
4535 * Don't take chances with filesystem routines seeing it for
4538 if (cache_fpl_istrailingslash(fpl)) {
4539 return (cache_fpl_partial(fpl));
4542 mp = atomic_load_ptr(&dvp->v_mount);
4543 if (__predict_false(mp == NULL)) {
4544 return (cache_fpl_aborted(fpl));
4547 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4548 cache_fpl_smr_exit(fpl);
4550 * Original code keeps not checking for CREATE which
4551 * might be a bug. For now let the old lookup decide.
4553 if (cnp->cn_nameiop == CREATE) {
4554 return (cache_fpl_aborted(fpl));
4556 return (cache_fpl_handled_error(fpl, EROFS));
4559 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4560 cache_fpl_smr_exit(fpl);
4561 return (cache_fpl_handled_error(fpl, EEXIST));
4565 * Secure access to dvp; check cache_fplookup_partial_setup for
4568 * XXX At least UFS requires its lookup routine to be called for
4569 * the last path component, which leads to some level of complication
4571 * - the target routine always locks the target vnode, but our caller
4572 * may not need it locked
4573 * - some of the VOP machinery asserts that the parent is locked, which
4574 * once more may be not required
4576 * TODO: add a flag for filesystems which don't need this.
4578 dvs = vget_prep_smr(dvp);
4579 cache_fpl_smr_exit(fpl);
4580 if (__predict_false(dvs == VGET_NONE)) {
4581 return (cache_fpl_aborted(fpl));
4584 vget_finish_ref(dvp, dvs);
4585 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4587 return (cache_fpl_aborted(fpl));
4590 error = vn_lock(dvp, LK_EXCLUSIVE);
4591 if (__predict_false(error != 0)) {
4593 return (cache_fpl_aborted(fpl));
4597 cnp->cn_flags |= ISLASTCN;
4599 cnp->cn_flags |= MAKEENTRY;
4600 if (cache_fpl_isdotdot(cnp))
4601 cnp->cn_flags |= ISDOTDOT;
4602 cnp->cn_lkflags = LK_EXCLUSIVE;
4603 error = VOP_LOOKUP(dvp, &tvp, cnp);
4611 return (cache_fpl_handled_error(fpl, error));
4614 return (cache_fpl_aborted(fpl));
4618 fpl->savename = (cnp->cn_flags & SAVENAME) != 0;
4621 if ((cnp->cn_flags & SAVESTART) != 0) {
4622 ndp->ni_startdir = dvp;
4623 vrefact(ndp->ni_startdir);
4624 cnp->cn_flags |= SAVENAME;
4625 fpl->savename = true;
4627 MPASS(error == EJUSTRETURN);
4628 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4631 return (cache_fpl_handled(fpl));
4635 * There are very hairy corner cases concerning various flag combinations
4636 * and locking state. In particular here we only hold one lock instead of
4639 * Skip the complexity as it is of no significance for normal workloads.
4641 if (__predict_false(tvp == dvp)) {
4644 return (cache_fpl_aborted(fpl));
4648 * If they want the symlink itself we are fine, but if they want to
4649 * follow it regular lookup has to be engaged.
4651 if (tvp->v_type == VLNK) {
4652 if ((cnp->cn_flags & FOLLOW) != 0) {
4655 return (cache_fpl_aborted(fpl));
4660 * Since we expect this to be the terminal vnode it should almost never
4663 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4666 return (cache_fpl_aborted(fpl));
4669 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4672 return (cache_fpl_handled_error(fpl, EEXIST));
4675 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4679 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4683 if ((cnp->cn_flags & SAVESTART) != 0) {
4684 ndp->ni_startdir = dvp;
4685 vrefact(ndp->ni_startdir);
4686 cnp->cn_flags |= SAVENAME;
4687 fpl->savename = true;
4690 return (cache_fpl_handled(fpl));
4693 static int __noinline
4694 cache_fplookup_modifying(struct cache_fpl *fpl)
4696 struct nameidata *ndp;
4700 if (!cache_fpl_islastcn(ndp)) {
4701 return (cache_fpl_partial(fpl));
4703 return (cache_fplookup_final_modifying(fpl));
4706 static int __noinline
4707 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4709 struct componentname *cnp;
4710 enum vgetstate dvs, tvs;
4711 struct vnode *dvp, *tvp;
4717 dvp_seqc = fpl->dvp_seqc;
4720 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4723 * This is less efficient than it can be for simplicity.
4725 dvs = vget_prep_smr(dvp);
4726 if (__predict_false(dvs == VGET_NONE)) {
4727 return (cache_fpl_aborted(fpl));
4729 tvs = vget_prep_smr(tvp);
4730 if (__predict_false(tvs == VGET_NONE)) {
4731 cache_fpl_smr_exit(fpl);
4732 vget_abort(dvp, dvs);
4733 return (cache_fpl_aborted(fpl));
4736 cache_fpl_smr_exit(fpl);
4738 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4739 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4740 if (__predict_false(error != 0)) {
4741 vget_abort(tvp, tvs);
4742 return (cache_fpl_aborted(fpl));
4745 vget_finish_ref(dvp, dvs);
4748 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4749 vget_abort(tvp, tvs);
4750 if ((cnp->cn_flags & LOCKPARENT) != 0)
4754 return (cache_fpl_aborted(fpl));
4757 error = cache_fplookup_final_child(fpl, tvs);
4758 if (__predict_false(error != 0)) {
4759 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4760 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4761 if ((cnp->cn_flags & LOCKPARENT) != 0)
4768 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4773 cache_fplookup_final(struct cache_fpl *fpl)
4775 struct componentname *cnp;
4777 struct vnode *dvp, *tvp;
4782 dvp_seqc = fpl->dvp_seqc;
4785 MPASS(*(cnp->cn_nameptr) != '/');
4787 if (cnp->cn_nameiop != LOOKUP) {
4788 return (cache_fplookup_final_modifying(fpl));
4791 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4792 return (cache_fplookup_final_withparent(fpl));
4794 tvs = vget_prep_smr(tvp);
4795 if (__predict_false(tvs == VGET_NONE)) {
4796 return (cache_fpl_partial(fpl));
4799 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4800 cache_fpl_smr_exit(fpl);
4801 vget_abort(tvp, tvs);
4802 return (cache_fpl_aborted(fpl));
4805 cache_fpl_smr_exit(fpl);
4806 return (cache_fplookup_final_child(fpl, tvs));
4810 * Comment from locked lookup:
4811 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4812 * directory, e.g. like "/." or ".".
4814 static int __noinline
4815 cache_fplookup_degenerate(struct cache_fpl *fpl)
4817 struct componentname *cnp;
4825 fpl->tvp = fpl->dvp;
4826 fpl->tvp_seqc = fpl->dvp_seqc;
4832 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4834 ("%s: encountered non-slash; string [%s]\n", __func__,
4839 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4840 cache_fpl_smr_exit(fpl);
4841 return (cache_fpl_handled_error(fpl, EISDIR));
4844 MPASS((cnp->cn_flags & SAVESTART) == 0);
4846 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4847 return (cache_fplookup_final_withparent(fpl));
4850 dvs = vget_prep_smr(dvp);
4851 cache_fpl_smr_exit(fpl);
4852 if (__predict_false(dvs == VGET_NONE)) {
4853 return (cache_fpl_aborted(fpl));
4856 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4857 lkflags = LK_SHARED;
4858 if ((cnp->cn_flags & LOCKSHARED) == 0)
4859 lkflags = LK_EXCLUSIVE;
4860 error = vget_finish(dvp, lkflags, dvs);
4861 if (__predict_false(error != 0)) {
4862 return (cache_fpl_aborted(fpl));
4865 vget_finish_ref(dvp, dvs);
4867 return (cache_fpl_handled(fpl));
4870 static int __noinline
4871 cache_fplookup_emptypath(struct cache_fpl *fpl)
4873 struct nameidata *ndp;
4874 struct componentname *cnp;
4879 fpl->tvp = fpl->dvp;
4880 fpl->tvp_seqc = fpl->dvp_seqc;
4886 MPASS(*cnp->cn_pnbuf == '\0');
4888 if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
4889 cache_fpl_smr_exit(fpl);
4890 return (cache_fpl_handled_error(fpl, ENOENT));
4893 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
4895 tvs = vget_prep_smr(tvp);
4896 cache_fpl_smr_exit(fpl);
4897 if (__predict_false(tvs == VGET_NONE)) {
4898 return (cache_fpl_aborted(fpl));
4901 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4902 lkflags = LK_SHARED;
4903 if ((cnp->cn_flags & LOCKSHARED) == 0)
4904 lkflags = LK_EXCLUSIVE;
4905 error = vget_finish(tvp, lkflags, tvs);
4906 if (__predict_false(error != 0)) {
4907 return (cache_fpl_aborted(fpl));
4910 vget_finish_ref(tvp, tvs);
4913 ndp->ni_resflags |= NIRES_EMPTYPATH;
4914 return (cache_fpl_handled(fpl));
4917 static int __noinline
4918 cache_fplookup_noentry(struct cache_fpl *fpl)
4920 struct nameidata *ndp;
4921 struct componentname *cnp;
4923 struct vnode *dvp, *tvp;
4930 dvp_seqc = fpl->dvp_seqc;
4932 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4933 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4934 if (cnp->cn_nameiop == LOOKUP)
4935 MPASS((cnp->cn_flags & NOCACHE) == 0);
4936 MPASS(!cache_fpl_isdotdot(cnp));
4939 * Hack: delayed name len checking.
4941 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4942 cache_fpl_smr_exit(fpl);
4943 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
4946 if (cnp->cn_nameptr[0] == '/') {
4947 return (cache_fplookup_skip_slashes(fpl));
4950 if (cnp->cn_pnbuf[0] == '\0') {
4951 return (cache_fplookup_emptypath(fpl));
4954 if (cnp->cn_nameptr[0] == '\0') {
4955 if (fpl->tvp == NULL) {
4956 return (cache_fplookup_degenerate(fpl));
4958 return (cache_fplookup_trailingslash(fpl));
4961 if (cnp->cn_nameiop != LOOKUP) {
4963 return (cache_fplookup_modifying(fpl));
4966 MPASS((cnp->cn_flags & SAVESTART) == 0);
4969 * Only try to fill in the component if it is the last one,
4970 * otherwise not only there may be several to handle but the
4971 * walk may be complicated.
4973 if (!cache_fpl_islastcn(ndp)) {
4974 return (cache_fpl_partial(fpl));
4978 * Regular lookup nulifies the slash, which we don't do here.
4979 * Don't take chances with filesystem routines seeing it for
4982 if (cache_fpl_istrailingslash(fpl)) {
4983 return (cache_fpl_partial(fpl));
4987 * Secure access to dvp; check cache_fplookup_partial_setup for
4990 dvs = vget_prep_smr(dvp);
4991 cache_fpl_smr_exit(fpl);
4992 if (__predict_false(dvs == VGET_NONE)) {
4993 return (cache_fpl_aborted(fpl));
4996 vget_finish_ref(dvp, dvs);
4997 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4999 return (cache_fpl_aborted(fpl));
5002 error = vn_lock(dvp, LK_SHARED);
5003 if (__predict_false(error != 0)) {
5005 return (cache_fpl_aborted(fpl));
5010 * TODO: provide variants which don't require locking either vnode.
5012 cnp->cn_flags |= ISLASTCN | MAKEENTRY;
5013 cnp->cn_lkflags = LK_SHARED;
5014 if ((cnp->cn_flags & LOCKSHARED) == 0) {
5015 cnp->cn_lkflags = LK_EXCLUSIVE;
5017 error = VOP_LOOKUP(dvp, &tvp, cnp);
5025 return (cache_fpl_handled_error(fpl, error));
5028 return (cache_fpl_aborted(fpl));
5032 if (!fpl->savename) {
5033 MPASS((cnp->cn_flags & SAVENAME) == 0);
5037 MPASS(error == EJUSTRETURN);
5038 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5040 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5043 return (cache_fpl_handled(fpl));
5046 if (tvp->v_type == VLNK) {
5047 if ((cnp->cn_flags & FOLLOW) != 0) {
5050 return (cache_fpl_aborted(fpl));
5054 if (__predict_false(cache_fplookup_is_mp(fpl))) {
5057 return (cache_fpl_aborted(fpl));
5060 if ((cnp->cn_flags & LOCKLEAF) == 0) {
5064 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5066 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5069 return (cache_fpl_handled(fpl));
5072 static int __noinline
5073 cache_fplookup_dot(struct cache_fpl *fpl)
5077 MPASS(!seqc_in_modify(fpl->dvp_seqc));
5079 if (__predict_false(fpl->dvp->v_type != VDIR)) {
5080 cache_fpl_smr_exit(fpl);
5081 return (cache_fpl_handled_error(fpl, ENOTDIR));
5085 * Just re-assign the value. seqc will be checked later for the first
5086 * non-dot path component in line and/or before deciding to return the
5089 fpl->tvp = fpl->dvp;
5090 fpl->tvp_seqc = fpl->dvp_seqc;
5092 counter_u64_add(dothits, 1);
5093 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
5096 if (cache_fplookup_is_mp(fpl)) {
5097 error = cache_fplookup_cross_mount(fpl);
5102 static int __noinline
5103 cache_fplookup_dotdot(struct cache_fpl *fpl)
5105 struct nameidata *ndp;
5106 struct componentname *cnp;
5107 struct namecache *ncp;
5116 MPASS(cache_fpl_isdotdot(cnp));
5119 * XXX this is racy the same way regular lookup is
5121 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5123 if (dvp == pr->pr_root)
5126 if (dvp == ndp->ni_rootdir ||
5127 dvp == ndp->ni_topdir ||
5131 fpl->tvp_seqc = vn_seqc_read_any(dvp);
5132 if (seqc_in_modify(fpl->tvp_seqc)) {
5133 return (cache_fpl_aborted(fpl));
5138 if ((dvp->v_vflag & VV_ROOT) != 0) {
5141 * The opposite of climb mount is needed here.
5143 return (cache_fpl_partial(fpl));
5146 if (__predict_false(dvp->v_type != VDIR)) {
5147 cache_fpl_smr_exit(fpl);
5148 return (cache_fpl_handled_error(fpl, ENOTDIR));
5151 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5153 return (cache_fpl_aborted(fpl));
5156 nc_flag = atomic_load_char(&ncp->nc_flag);
5157 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5158 if ((nc_flag & NCF_NEGATIVE) != 0)
5159 return (cache_fpl_aborted(fpl));
5160 fpl->tvp = ncp->nc_vp;
5162 fpl->tvp = ncp->nc_dvp;
5165 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5166 if (seqc_in_modify(fpl->tvp_seqc)) {
5167 return (cache_fpl_partial(fpl));
5171 * Acquire fence provided by vn_seqc_read_any above.
5173 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5174 return (cache_fpl_aborted(fpl));
5177 if (!cache_ncp_canuse(ncp)) {
5178 return (cache_fpl_aborted(fpl));
5181 counter_u64_add(dotdothits, 1);
5185 static int __noinline
5186 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5188 u_char nc_flag __diagused;
5192 nc_flag = atomic_load_char(&ncp->nc_flag);
5193 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5196 * If they want to create an entry we need to replace this one.
5198 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5200 return (cache_fplookup_modifying(fpl));
5202 neg_promote = cache_neg_hit_prep(ncp);
5203 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5204 cache_neg_hit_abort(ncp);
5205 return (cache_fpl_partial(fpl));
5208 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5210 cache_neg_hit_finish(ncp);
5211 cache_fpl_smr_exit(fpl);
5212 return (cache_fpl_handled_error(fpl, ENOENT));
5216 * Resolve a symlink. Called by filesystem-specific routines.
5219 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5222 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5224 struct nameidata *ndp;
5225 struct componentname *cnp;
5231 if (__predict_false(len == 0)) {
5235 if (__predict_false(len > MAXPATHLEN - 2)) {
5236 if (cache_fpl_istrailingslash(fpl)) {
5241 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5243 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5244 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5245 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5246 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5250 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5251 return (ENAMETOOLONG);
5254 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5259 if (ndp->ni_pathlen > 1) {
5260 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5262 if (cache_fpl_istrailingslash(fpl)) {
5264 cnp->cn_pnbuf[len] = '/';
5265 cnp->cn_pnbuf[len + 1] = '\0';
5267 cnp->cn_pnbuf[len] = '\0';
5270 bcopy(string, cnp->cn_pnbuf, len);
5272 ndp->ni_pathlen += adjust;
5273 cache_fpl_pathlen_add(fpl, adjust);
5274 cnp->cn_nameptr = cnp->cn_pnbuf;
5275 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5280 static int __noinline
5281 cache_fplookup_symlink(struct cache_fpl *fpl)
5284 struct nameidata *ndp;
5285 struct componentname *cnp;
5286 struct vnode *dvp, *tvp;
5294 if (cache_fpl_islastcn(ndp)) {
5295 if ((cnp->cn_flags & FOLLOW) == 0) {
5296 return (cache_fplookup_final(fpl));
5300 mp = atomic_load_ptr(&dvp->v_mount);
5301 if (__predict_false(mp == NULL)) {
5302 return (cache_fpl_aborted(fpl));
5306 * Note this check races against setting the flag just like regular
5309 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5310 cache_fpl_smr_exit(fpl);
5311 return (cache_fpl_handled_error(fpl, EACCES));
5314 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5315 if (__predict_false(error != 0)) {
5318 return (cache_fpl_partial(fpl));
5322 cache_fpl_smr_exit(fpl);
5323 return (cache_fpl_handled_error(fpl, error));
5325 return (cache_fpl_aborted(fpl));
5329 if (*(cnp->cn_nameptr) == '/') {
5330 fpl->dvp = cache_fpl_handle_root(fpl);
5331 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5332 if (seqc_in_modify(fpl->dvp_seqc)) {
5333 return (cache_fpl_aborted(fpl));
5336 * The main loop assumes that ->dvp points to a vnode belonging
5337 * to a filesystem which can do lockless lookup, but the absolute
5338 * symlink can be wandering off to one which does not.
5340 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5341 if (__predict_false(mp == NULL)) {
5342 return (cache_fpl_aborted(fpl));
5344 if (!cache_fplookup_mp_supported(mp)) {
5345 cache_fpl_checkpoint(fpl);
5346 return (cache_fpl_partial(fpl));
5353 cache_fplookup_next(struct cache_fpl *fpl)
5355 struct componentname *cnp;
5356 struct namecache *ncp;
5357 struct vnode *dvp, *tvp;
5366 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5367 if (cnp->cn_namelen == 1) {
5368 return (cache_fplookup_dot(fpl));
5370 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5371 return (cache_fplookup_dotdot(fpl));
5375 MPASS(!cache_fpl_isdotdot(cnp));
5377 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5378 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5379 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5383 if (__predict_false(ncp == NULL)) {
5384 return (cache_fplookup_noentry(fpl));
5387 tvp = atomic_load_ptr(&ncp->nc_vp);
5388 nc_flag = atomic_load_char(&ncp->nc_flag);
5389 if ((nc_flag & NCF_NEGATIVE) != 0) {
5390 return (cache_fplookup_neg(fpl, ncp, hash));
5393 if (!cache_ncp_canuse(ncp)) {
5394 return (cache_fpl_partial(fpl));
5398 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5399 if (seqc_in_modify(fpl->tvp_seqc)) {
5400 return (cache_fpl_partial(fpl));
5403 counter_u64_add(numposhits, 1);
5404 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5407 if (cache_fplookup_is_mp(fpl)) {
5408 error = cache_fplookup_cross_mount(fpl);
5414 cache_fplookup_mp_supported(struct mount *mp)
5418 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5424 * Walk up the mount stack (if any).
5426 * Correctness is provided in the following ways:
5427 * - all vnodes are protected from freeing with SMR
5428 * - struct mount objects are type stable making them always safe to access
5429 * - stability of the particular mount is provided by busying it
5430 * - relationship between the vnode which is mounted on and the mount is
5431 * verified with the vnode sequence counter after busying
5432 * - association between root vnode of the mount and the mount is protected
5435 * From that point on we can read the sequence counter of the root vnode
5436 * and get the next mount on the stack (if any) using the same protection.
5438 * By the end of successful walk we are guaranteed the reached state was
5439 * indeed present at least at some point which matches the regular lookup.
5441 static int __noinline
5442 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5444 struct mount *mp, *prev_mp;
5445 struct mount_pcpu *mpcpu, *prev_mpcpu;
5450 vp_seqc = fpl->tvp_seqc;
5452 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5453 mp = atomic_load_ptr(&vp->v_mountedhere);
5454 if (__predict_false(mp == NULL)) {
5460 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5461 if (prev_mp != NULL)
5462 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5463 return (cache_fpl_partial(fpl));
5465 if (prev_mp != NULL)
5466 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5467 if (!vn_seqc_consistent(vp, vp_seqc)) {
5468 vfs_op_thread_exit_crit(mp, mpcpu);
5469 return (cache_fpl_partial(fpl));
5471 if (!cache_fplookup_mp_supported(mp)) {
5472 vfs_op_thread_exit_crit(mp, mpcpu);
5473 return (cache_fpl_partial(fpl));
5475 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5477 vfs_op_thread_exit_crit(mp, mpcpu);
5478 return (cache_fpl_partial(fpl));
5480 vp_seqc = vn_seqc_read_any(vp);
5481 if (seqc_in_modify(vp_seqc)) {
5482 vfs_op_thread_exit_crit(mp, mpcpu);
5483 return (cache_fpl_partial(fpl));
5487 mp = atomic_load_ptr(&vp->v_mountedhere);
5492 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5494 fpl->tvp_seqc = vp_seqc;
5498 static int __noinline
5499 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5502 struct mount_pcpu *mpcpu;
5507 vp_seqc = fpl->tvp_seqc;
5509 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5510 mp = atomic_load_ptr(&vp->v_mountedhere);
5511 if (__predict_false(mp == NULL)) {
5515 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5516 return (cache_fpl_partial(fpl));
5518 if (!vn_seqc_consistent(vp, vp_seqc)) {
5519 vfs_op_thread_exit_crit(mp, mpcpu);
5520 return (cache_fpl_partial(fpl));
5522 if (!cache_fplookup_mp_supported(mp)) {
5523 vfs_op_thread_exit_crit(mp, mpcpu);
5524 return (cache_fpl_partial(fpl));
5526 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5527 if (__predict_false(vp == NULL)) {
5528 vfs_op_thread_exit_crit(mp, mpcpu);
5529 return (cache_fpl_partial(fpl));
5531 vp_seqc = vn_seqc_read_any(vp);
5532 vfs_op_thread_exit_crit(mp, mpcpu);
5533 if (seqc_in_modify(vp_seqc)) {
5534 return (cache_fpl_partial(fpl));
5536 mp = atomic_load_ptr(&vp->v_mountedhere);
5537 if (__predict_false(mp != NULL)) {
5539 * There are possibly more mount points on top.
5540 * Normally this does not happen so for simplicity just start
5543 return (cache_fplookup_climb_mount(fpl));
5547 fpl->tvp_seqc = vp_seqc;
5552 * Check if a vnode is mounted on.
5555 cache_fplookup_is_mp(struct cache_fpl *fpl)
5560 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5566 * The code was originally copy-pasted from regular lookup and despite
5567 * clean ups leaves performance on the table. Any modifications here
5568 * must take into account that in case off fallback the resulting
5569 * nameidata state has to be compatible with the original.
5573 * Debug ni_pathlen tracking.
5577 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5580 fpl->debug.ni_pathlen += n;
5581 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5582 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5586 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5589 fpl->debug.ni_pathlen -= n;
5590 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5591 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5595 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5598 cache_fpl_pathlen_add(fpl, 1);
5602 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5605 cache_fpl_pathlen_sub(fpl, 1);
5609 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5614 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5619 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5624 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5630 cache_fplookup_parse(struct cache_fpl *fpl)
5632 struct nameidata *ndp;
5633 struct componentname *cnp;
5643 * Find the end of this path component, it is either / or nul.
5645 * Store / as a temporary sentinel so that we only have one character
5646 * to test for. Pathnames tend to be short so this should not be
5647 * resulting in cache misses.
5649 * TODO: fix this to be word-sized.
5651 MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5652 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5653 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5654 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5655 fpl->nulchar, cnp->cn_pnbuf));
5656 KASSERT(*fpl->nulchar == '\0',
5657 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5659 hash = cache_get_hash_iter_start(dvp);
5660 *fpl->nulchar = '/';
5661 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5662 KASSERT(*cp != '\0',
5663 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5665 hash = cache_get_hash_iter(*cp, hash);
5668 *fpl->nulchar = '\0';
5669 fpl->hash = cache_get_hash_iter_finish(hash);
5671 cnp->cn_namelen = cp - cnp->cn_nameptr;
5672 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5676 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5677 * we are going to fail this lookup with ENAMETOOLONG (see below).
5679 if (cnp->cn_namelen <= NAME_MAX) {
5680 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5681 panic("%s: mismatched hash for [%s] len %ld", __func__,
5682 cnp->cn_nameptr, cnp->cn_namelen);
5688 * Hack: we have to check if the found path component's length exceeds
5689 * NAME_MAX. However, the condition is very rarely true and check can
5690 * be elided in the common case -- if an entry was found in the cache,
5691 * then it could not have been too long to begin with.
5697 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5699 struct nameidata *ndp;
5700 struct componentname *cnp;
5705 cnp->cn_nameptr = ndp->ni_next;
5706 KASSERT(*(cnp->cn_nameptr) == '/',
5707 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5708 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5710 cache_fpl_pathlen_dec(fpl);
5714 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5716 * Lockless lookup tries to elide checking for spurious slashes and should they
5717 * be present is guaranteed to fail to find an entry. In this case the caller
5718 * must check if the name starts with a slash and call this routine. It is
5719 * going to fast forward across the spurious slashes and set the state up for
5722 static int __noinline
5723 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5725 struct nameidata *ndp;
5726 struct componentname *cnp;
5731 MPASS(*(cnp->cn_nameptr) == '/');
5734 cache_fpl_pathlen_dec(fpl);
5735 } while (*(cnp->cn_nameptr) == '/');
5738 * Go back to one slash so that cache_fplookup_parse_advance has
5739 * something to skip.
5742 cache_fpl_pathlen_inc(fpl);
5745 * cache_fplookup_parse_advance starts from ndp->ni_next
5747 ndp->ni_next = cnp->cn_nameptr;
5750 * See cache_fplookup_dot.
5752 fpl->tvp = fpl->dvp;
5753 fpl->tvp_seqc = fpl->dvp_seqc;
5759 * Handle trailing slashes (e.g., "foo/").
5761 * If a trailing slash is found the terminal vnode must be a directory.
5762 * Regular lookup shortens the path by nulifying the first trailing slash and
5763 * sets the TRAILINGSLASH flag to denote this took place. There are several
5764 * checks on it performed later.
5766 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5767 * manner relying on an invariant that a non-directory vnode will get a miss.
5768 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5770 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5771 * and denotes this is the last path component, which avoids looping back.
5773 * Only plain lookups are supported for now to restrict corner cases to handle.
5775 static int __noinline
5776 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5781 struct nameidata *ndp;
5782 struct componentname *cnp;
5783 struct namecache *ncp;
5785 char *cn_nameptr_orig, *cn_nameptr_slash;
5792 tvp_seqc = fpl->tvp_seqc;
5794 MPASS(fpl->dvp == fpl->tvp);
5795 KASSERT(cache_fpl_istrailingslash(fpl),
5796 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5798 KASSERT(cnp->cn_nameptr[0] == '\0',
5799 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5801 KASSERT(cnp->cn_namelen == 0,
5802 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5804 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5806 if (cnp->cn_nameiop != LOOKUP) {
5807 return (cache_fpl_aborted(fpl));
5810 if (__predict_false(tvp->v_type != VDIR)) {
5811 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5812 return (cache_fpl_aborted(fpl));
5814 cache_fpl_smr_exit(fpl);
5815 return (cache_fpl_handled_error(fpl, ENOTDIR));
5819 * Denote the last component.
5821 ndp->ni_next = &cnp->cn_nameptr[0];
5822 MPASS(cache_fpl_islastcn(ndp));
5825 * Unwind trailing slashes.
5827 cn_nameptr_orig = cnp->cn_nameptr;
5828 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5830 if (cnp->cn_nameptr[0] != '/') {
5836 * Unwind to the beginning of the path component.
5838 * Note the path may or may not have started with a slash.
5840 cn_nameptr_slash = cnp->cn_nameptr;
5841 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5843 if (cnp->cn_nameptr[0] == '/') {
5847 if (cnp->cn_nameptr[0] == '/') {
5851 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5852 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5853 cache_fpl_checkpoint(fpl);
5856 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5857 if (ni_pathlen != fpl->debug.ni_pathlen) {
5858 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5859 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5860 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5865 * If this was a "./" lookup the parent directory is already correct.
5867 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5872 * Otherwise we need to look it up.
5875 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5876 if (__predict_false(ncp == NULL)) {
5877 return (cache_fpl_aborted(fpl));
5879 nc_flag = atomic_load_char(&ncp->nc_flag);
5880 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5881 return (cache_fpl_aborted(fpl));
5883 fpl->dvp = ncp->nc_dvp;
5884 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5885 if (seqc_in_modify(fpl->dvp_seqc)) {
5886 return (cache_fpl_aborted(fpl));
5892 * See the API contract for VOP_FPLOOKUP_VEXEC.
5894 static int __noinline
5895 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5897 struct componentname *cnp;
5903 dvp_seqc = fpl->dvp_seqc;
5906 * Hack: delayed empty path checking.
5908 if (cnp->cn_pnbuf[0] == '\0') {
5909 return (cache_fplookup_emptypath(fpl));
5913 * TODO: Due to ignoring trailing slashes lookup will perform a
5914 * permission check on the last dir when it should not be doing it. It
5915 * may fail, but said failure should be ignored. It is possible to fix
5916 * it up fully without resorting to regular lookup, but for now just
5919 if (cache_fpl_istrailingslash(fpl)) {
5920 return (cache_fpl_aborted(fpl));
5924 * Hack: delayed degenerate path checking.
5926 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5927 return (cache_fplookup_degenerate(fpl));
5931 * Hack: delayed name len checking.
5933 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5934 cache_fpl_smr_exit(fpl);
5935 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5939 * Hack: they may be looking up foo/bar, where foo is not a directory.
5940 * In such a case we need to return ENOTDIR, but we may happen to get
5941 * here with a different error.
5943 if (dvp->v_type != VDIR) {
5948 * Hack: handle O_SEARCH.
5950 * Open Group Base Specifications Issue 7, 2018 edition states:
5952 * If the access mode of the open file description associated with the
5953 * file descriptor is not O_SEARCH, the function shall check whether
5954 * directory searches are permitted using the current permissions of
5955 * the directory underlying the file descriptor. If the access mode is
5956 * O_SEARCH, the function shall not perform the check.
5959 * Regular lookup tests for the NOEXECCHECK flag for every path
5960 * component to decide whether to do the permission check. However,
5961 * since most lookups never have the flag (and when they do it is only
5962 * present for the first path component), lockless lookup only acts on
5963 * it if there is a permission problem. Here the flag is represented
5964 * with a boolean so that we don't have to clear it on the way out.
5966 * For simplicity this always aborts.
5967 * TODO: check if this is the first lookup and ignore the permission
5968 * problem. Note the flag has to survive fallback (if it happens to be
5972 return (cache_fpl_aborted(fpl));
5977 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5978 error = cache_fpl_aborted(fpl);
5980 cache_fpl_partial(fpl);
5984 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5985 error = cache_fpl_aborted(fpl);
5987 cache_fpl_smr_exit(fpl);
5988 cache_fpl_handled_error(fpl, error);
5996 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
5998 struct nameidata *ndp;
5999 struct componentname *cnp;
6006 cache_fpl_checkpoint(fpl);
6009 * The vnode at hand is almost always stable, skip checking for it.
6010 * Worst case this postpones the check towards the end of the iteration
6014 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
6016 mp = atomic_load_ptr(&dvp->v_mount);
6017 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
6018 return (cache_fpl_aborted(fpl));
6021 MPASS(fpl->tvp == NULL);
6024 cache_fplookup_parse(fpl);
6026 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
6027 if (__predict_false(error != 0)) {
6028 error = cache_fplookup_failed_vexec(fpl, error);
6032 error = cache_fplookup_next(fpl);
6033 if (__predict_false(cache_fpl_terminated(fpl))) {
6037 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
6039 if (fpl->tvp->v_type == VLNK) {
6040 error = cache_fplookup_symlink(fpl);
6041 if (cache_fpl_terminated(fpl)) {
6045 if (cache_fpl_islastcn(ndp)) {
6046 error = cache_fplookup_final(fpl);
6050 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
6051 error = cache_fpl_aborted(fpl);
6055 fpl->dvp = fpl->tvp;
6056 fpl->dvp_seqc = fpl->tvp_seqc;
6057 cache_fplookup_parse_advance(fpl);
6060 cache_fpl_checkpoint(fpl);
6067 * Fast path lookup protected with SMR and sequence counters.
6069 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
6071 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
6074 * Traditional vnode lookup conceptually looks like this:
6080 * vn_unlock(current);
6087 * Each jump to the next vnode is safe memory-wise and atomic with respect to
6088 * any modifications thanks to holding respective locks.
6090 * The same guarantee can be provided with a combination of safe memory
6091 * reclamation and sequence counters instead. If all operations which affect
6092 * the relationship between the current vnode and the one we are looking for
6093 * also modify the counter, we can verify whether all the conditions held as
6094 * we made the jump. This includes things like permissions, mount points etc.
6095 * Counter modification is provided by enclosing relevant places in
6096 * vn_seqc_write_begin()/end() calls.
6098 * Thus this translates to:
6101 * dvp_seqc = seqc_read_any(dvp);
6102 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
6106 * tvp_seqc = seqc_read_any(tvp);
6107 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6109 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6111 * dvp = tvp; // we know nothing of importance has changed
6112 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6116 * vget(); // secure the vnode
6117 * if (!seqc_consistent(tvp, tvp_seqc) // final check
6119 * // at this point we know nothing has changed for any parent<->child pair
6120 * // as they were crossed during the lookup, meaning we matched the guarantee
6121 * // of the locked variant
6124 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6125 * - they are called while within vfs_smr protection which they must never exit
6126 * - EAGAIN can be returned to denote checking could not be performed, it is
6127 * always valid to return it
6128 * - if the sequence counter has not changed the result must be valid
6129 * - if the sequence counter has changed both false positives and false negatives
6130 * are permitted (since the result will be rejected later)
6131 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6133 * Caveats to watch out for:
6134 * - vnodes are passed unlocked and unreferenced with nothing stopping
6135 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6136 * to use atomic_load_ptr to fetch it.
6137 * - the aforementioned object can also get freed, meaning absent other means it
6138 * should be protected with vfs_smr
6139 * - either safely checking permissions as they are modified or guaranteeing
6140 * their stability is left to the routine
6143 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6146 struct cache_fpl fpl;
6149 struct componentname *cnp;
6152 fpl.status = CACHE_FPL_STATUS_UNSET;
6155 fpl.cnp = cnp = &ndp->ni_cnd;
6156 MPASS(ndp->ni_lcf == 0);
6157 MPASS(curthread == cnp->cn_thread);
6158 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6159 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6161 if ((cnp->cn_flags & SAVESTART) != 0) {
6162 MPASS(cnp->cn_nameiop != LOOKUP);
6164 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6166 if (__predict_false(!cache_can_fplookup(&fpl))) {
6167 *status = fpl.status;
6168 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6169 return (EOPNOTSUPP);
6172 cache_fpl_checkpoint_outer(&fpl);
6174 cache_fpl_smr_enter_initial(&fpl);
6176 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6178 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6179 fpl.fsearch = false;
6180 fpl.savename = (cnp->cn_flags & SAVENAME) != 0;
6181 fpl.tvp = NULL; /* for degenerate path handling */
6183 pwd = pwd_get_smr();
6185 ndp->ni_rootdir = pwd->pwd_rdir;
6186 ndp->ni_topdir = pwd->pwd_jdir;
6188 if (cnp->cn_pnbuf[0] == '/') {
6189 dvp = cache_fpl_handle_root(&fpl);
6190 MPASS(ndp->ni_resflags == 0);
6191 ndp->ni_resflags = NIRES_ABS;
6193 if (ndp->ni_dirfd == AT_FDCWD) {
6194 dvp = pwd->pwd_cdir;
6196 error = cache_fplookup_dirfd(&fpl, &dvp);
6197 if (__predict_false(error != 0)) {
6203 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6204 error = cache_fplookup_impl(dvp, &fpl);
6206 cache_fpl_smr_assert_not_entered(&fpl);
6207 cache_fpl_assert_status(&fpl);
6208 *status = fpl.status;
6209 if (SDT_PROBES_ENABLED()) {
6210 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6211 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6212 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6216 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6217 MPASS(error != CACHE_FPL_FAILED);
6219 MPASS(fpl.dvp == NULL);
6220 MPASS(fpl.tvp == NULL);
6221 MPASS(fpl.savename == false);
6223 ndp->ni_dvp = fpl.dvp;
6224 ndp->ni_vp = fpl.tvp;
6226 cnp->cn_flags |= HASBUF;
6228 cache_fpl_cleanup_cnp(cnp);