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 <security/audit/audit.h>
75 #include <security/mac/mac_framework.h>
84 * High level overview of name caching in the VFS layer.
86 * Originally caching was implemented as part of UFS, later extracted to allow
87 * use by other filesystems. A decision was made to make it optional and
88 * completely detached from the rest of the kernel, which comes with limitations
89 * outlined near the end of this comment block.
91 * This fundamental choice needs to be revisited. In the meantime, the current
92 * state is described below. Significance of all notable routines is explained
93 * in comments placed above their implementation. Scattered thoroughout the
94 * file are TODO comments indicating shortcomings which can be fixed without
95 * reworking everything (most of the fixes will likely be reusable). Various
96 * details are omitted from this explanation to not clutter the overview, they
97 * have to be checked by reading the code and associated commentary.
99 * Keep in mind that it's individual path components which are cached, not full
100 * paths. That is, for a fully cached path "foo/bar/baz" there are 3 entries,
103 * I. Data organization
105 * Entries are described by "struct namecache" objects and stored in a hash
106 * table. See cache_get_hash for more information.
108 * "struct vnode" contains pointers to source entries (names which can be found
109 * when traversing through said vnode), destination entries (names of that
110 * vnode (see "Limitations" for a breakdown on the subject) and a pointer to
113 * The (directory vnode; name) tuple reliably determines the target entry if
116 * Since there are no small locks at this time (all are 32 bytes in size on
117 * LP64), the code works around the problem by introducing lock arrays to
118 * protect hash buckets and vnode lists.
120 * II. Filesystem integration
122 * Filesystems participating in name caching do the following:
123 * - set vop_lookup routine to vfs_cache_lookup
124 * - set vop_cachedlookup to whatever can perform the lookup if the above fails
125 * - if they support lockless lookup (see below), vop_fplookup_vexec and
126 * vop_fplookup_symlink are set along with the MNTK_FPLOOKUP flag on the
128 * - call cache_purge or cache_vop_* routines to eliminate stale entries as
130 * - call cache_enter to add entries depending on the MAKEENTRY flag
132 * With the above in mind, there are 2 entry points when doing lookups:
133 * - ... -> namei -> cache_fplookup -- this is the default
134 * - ... -> VOP_LOOKUP -> vfs_cache_lookup -- normally only called by namei
135 * should the above fail
137 * Example code flow how an entry is added:
138 * ... -> namei -> cache_fplookup -> cache_fplookup_noentry -> VOP_LOOKUP ->
139 * vfs_cache_lookup -> VOP_CACHEDLOOKUP -> ufs_lookup_ino -> cache_enter
141 * III. Performance considerations
143 * For lockless case forward lookup avoids any writes to shared areas apart
144 * from the terminal path component. In other words non-modifying lookups of
145 * different files don't suffer any scalability problems in the namecache.
146 * Looking up the same file is limited by VFS and goes beyond the scope of this
149 * At least on amd64 the single-threaded bottleneck for long paths is hashing
150 * (see cache_get_hash). There are cases where the code issues acquire fence
151 * multiple times, they can be combined on architectures which suffer from it.
153 * For locked case each encountered vnode has to be referenced and locked in
154 * order to be handed out to the caller (normally that's namei). This
155 * introduces significant hit single-threaded and serialization multi-threaded.
157 * Reverse lookup (e.g., "getcwd") fully scales provided it is fully cached --
158 * avoids any writes to shared areas to any components.
160 * Unrelated insertions are partially serialized on updating the global entry
161 * counter and possibly serialized on colliding bucket or vnode locks.
165 * Note not everything has an explicit dtrace probe nor it should have, thus
166 * some of the one-liners below depend on implementation details.
170 * # Check what lookups failed to be handled in a lockless manner. Column 1 is
171 * # line number, column 2 is status code (see cache_fpl_status)
172 * dtrace -n 'vfs:fplookup:lookup:done { @[arg1, arg2] = count(); }'
174 * # Lengths of names added by binary name
175 * dtrace -n 'fbt::cache_enter_time:entry { @[execname] = quantize(args[2]->cn_namelen); }'
177 * # Same as above but only those which exceed 64 characters
178 * dtrace -n 'fbt::cache_enter_time:entry /args[2]->cn_namelen > 64/ { @[execname] = quantize(args[2]->cn_namelen); }'
180 * # Who is performing lookups with spurious slashes (e.g., "foo//bar") and what
182 * dtrace -n 'fbt::cache_fplookup_skip_slashes:entry { @[execname, stringof(args[0]->cnp->cn_pnbuf)] = count(); }'
184 * V. Limitations and implementation defects
186 * - since it is possible there is no entry for an open file, tools like
187 * "procstat" may fail to resolve fd -> vnode -> path to anything
188 * - even if a filesystem adds an entry, it may get purged (e.g., due to memory
189 * shortage) in which case the above problem applies
190 * - hardlinks are not tracked, thus if a vnode is reachable in more than one
191 * way, resolving a name may return a different path than the one used to
192 * open it (even if said path is still valid)
193 * - by default entries are not added for newly created files
194 * - adding an entry may need to evict negative entry first, which happens in 2
195 * distinct places (evicting on lookup, adding in a later VOP) making it
196 * impossible to simply reuse it
197 * - there is a simple scheme to evict negative entries as the cache is approaching
198 * its capacity, but it is very unclear if doing so is a good idea to begin with
199 * - vnodes are subject to being recycled even if target inode is left in memory,
200 * which loses the name cache entries when it perhaps should not. in case of tmpfs
201 * names get duplicated -- kept by filesystem itself and namecache separately
202 * - struct namecache has a fixed size and comes in 2 variants, often wasting space.
203 * now hard to replace with malloc due to dependence on SMR.
204 * - lack of better integration with the kernel also turns nullfs into a layered
205 * filesystem instead of something which can take advantage of caching
208 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
211 SDT_PROVIDER_DECLARE(vfs);
212 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
214 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
216 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
218 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
220 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
221 "struct namecache *", "int", "int");
222 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
223 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
224 "char *", "struct vnode *");
225 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
226 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
227 "struct vnode *", "char *");
228 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
230 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
231 "struct vnode *", "char *");
232 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
234 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
235 "struct componentname *");
236 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
237 "struct componentname *");
238 SDT_PROBE_DEFINE3(vfs, namecache, purge, done, "struct vnode *", "size_t", "size_t");
239 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
240 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
241 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
242 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
244 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
246 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
248 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
250 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
251 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
252 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
254 static char __read_frequently cache_fast_lookup_enabled = true;
257 * This structure describes the elements in the cache of recent
258 * names looked up by namei.
264 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
265 "the state must fit in a union with a pointer without growing it");
268 LIST_ENTRY(namecache) nc_src; /* source vnode list */
269 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
270 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
271 struct vnode *nc_dvp; /* vnode of parent of name */
273 struct vnode *nu_vp; /* vnode the name refers to */
274 struct negstate nu_neg;/* negative entry state */
276 u_char nc_flag; /* flag bits */
277 u_char nc_nlen; /* length of name */
278 char nc_name[]; /* segment name + nul */
282 * struct namecache_ts repeats struct namecache layout up to the
284 * struct namecache_ts is used in place of struct namecache when time(s) need
285 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
286 * both a non-dotdot directory name plus dotdot for the directory's
289 * See below for alignment requirement.
291 struct namecache_ts {
292 struct timespec nc_time; /* timespec provided by fs */
293 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
294 int nc_ticks; /* ticks value when entry was added */
296 struct namecache nc_nc;
299 TAILQ_HEAD(cache_freebatch, namecache);
302 * At least mips n32 performs 64-bit accesses to timespec as found
303 * in namecache_ts and requires them to be aligned. Since others
304 * may be in the same spot suffer a little bit and enforce the
305 * alignment for everyone. Note this is a nop for 64-bit platforms.
307 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
310 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
311 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
312 * smaller and the value was bumped to retain the total size, but it
313 * was never re-evaluated for suitability. A simple test counting
314 * lengths during package building shows that the value of 45 covers
315 * about 86% of all added entries, reaching 99% at 65.
317 * Regardless of the above, use of dedicated zones instead of malloc may be
318 * inducing additional waste. This may be hard to address as said zones are
319 * tied to VFS SMR. Even if retaining them, the current split should be
323 #define CACHE_PATH_CUTOFF 45
324 #define CACHE_LARGE_PAD 6
326 #define CACHE_PATH_CUTOFF 41
327 #define CACHE_LARGE_PAD 2
330 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
331 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
332 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
333 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
335 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
336 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
337 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
338 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
340 #define nc_vp n_un.nu_vp
341 #define nc_neg n_un.nu_neg
344 * Flags in namecache.nc_flag
346 #define NCF_WHITE 0x01
347 #define NCF_ISDOTDOT 0x02
350 #define NCF_DVDROP 0x10
351 #define NCF_NEGATIVE 0x20
352 #define NCF_INVALID 0x40
356 * Flags in negstate.neg_flag
360 static bool cache_neg_evict_cond(u_long lnumcache);
363 * Mark an entry as invalid.
365 * This is called before it starts getting deconstructed.
368 cache_ncp_invalidate(struct namecache *ncp)
371 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
372 ("%s: entry %p already invalid", __func__, ncp));
373 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
374 atomic_thread_fence_rel();
378 * Check whether the entry can be safely used.
380 * All places which elide locks are supposed to call this after they are
381 * done with reading from an entry.
383 #define cache_ncp_canuse(ncp) ({ \
384 struct namecache *_ncp = (ncp); \
387 atomic_thread_fence_acq(); \
388 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
389 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0); \
393 * Like the above but also checks NCF_WHITE.
395 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
396 struct namecache *_ncp = (ncp); \
399 atomic_thread_fence_acq(); \
400 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
401 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
406 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
407 "Name cache parameters");
409 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
410 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
411 "Total namecache capacity");
413 u_int ncsizefactor = 2;
414 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
415 "Size factor for namecache");
417 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
418 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
419 "Ratio of negative namecache entries");
422 * Negative entry % of namecache capacity above which automatic eviction is allowed.
424 * Check cache_neg_evict_cond for details.
426 static u_int ncnegminpct = 3;
428 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
429 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
430 "Negative entry count above which automatic eviction is allowed");
433 * Structures associated with name caching.
435 #define NCHHASH(hash) \
436 (&nchashtbl[(hash) & nchash])
437 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
438 static u_long __read_mostly nchash; /* size of hash table */
439 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
440 "Size of namecache hash table");
441 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
442 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
444 struct nchstats nchstats; /* cache effectiveness statistics */
446 static u_int __exclusive_cache_line neg_cycle;
449 #define numneglists (ncneghash + 1)
452 struct mtx nl_evict_lock;
453 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
454 TAILQ_HEAD(, namecache) nl_list;
455 TAILQ_HEAD(, namecache) nl_hotlist;
457 } __aligned(CACHE_LINE_SIZE);
459 static struct neglist neglists[numneglists];
461 static inline struct neglist *
462 NCP2NEGLIST(struct namecache *ncp)
465 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
468 static inline struct negstate *
469 NCP2NEGSTATE(struct namecache *ncp)
472 MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
473 return (&ncp->nc_neg);
476 #define numbucketlocks (ncbuckethash + 1)
477 static u_int __read_mostly ncbuckethash;
478 static struct mtx_padalign __read_mostly *bucketlocks;
479 #define HASH2BUCKETLOCK(hash) \
480 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
482 #define numvnodelocks (ncvnodehash + 1)
483 static u_int __read_mostly ncvnodehash;
484 static struct mtx __read_mostly *vnodelocks;
485 static inline struct mtx *
486 VP2VNODELOCK(struct vnode *vp)
489 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
493 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
495 struct namecache_ts *ncp_ts;
497 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
498 (tsp == NULL && ticksp == NULL),
504 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
505 *tsp = ncp_ts->nc_time;
506 *ticksp = ncp_ts->nc_ticks;
510 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
511 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
512 "VFS namecache enabled");
515 /* Export size information to userland */
516 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
517 sizeof(struct namecache), "sizeof(struct namecache)");
520 * The new name cache statistics
522 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
523 "Name cache statistics");
525 #define STATNODE_ULONG(name, varname, descr) \
526 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
527 #define STATNODE_COUNTER(name, varname, descr) \
528 static COUNTER_U64_DEFINE_EARLY(varname); \
529 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
531 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
532 STATNODE_ULONG(count, numcache, "Number of cache entries");
533 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
534 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
535 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
536 STATNODE_COUNTER(dotdothits, dotdothits, "Number of '..' hits");
537 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
538 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
539 STATNODE_COUNTER(poszaps, numposzaps,
540 "Number of cache hits (positive) we do not want to cache");
541 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
542 STATNODE_COUNTER(negzaps, numnegzaps,
543 "Number of cache hits (negative) we do not want to cache");
544 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
545 /* These count for vn_getcwd(), too. */
546 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
547 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
548 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
549 "Number of fullpath search errors (VOP_VPTOCNP failures)");
550 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
551 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
552 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
555 * Debug or developer statistics.
557 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
558 "Name cache debugging");
559 #define DEBUGNODE_ULONG(name, varname, descr) \
560 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
561 #define DEBUGNODE_COUNTER(name, varname, descr) \
562 static COUNTER_U64_DEFINE_EARLY(varname); \
563 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
565 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
566 "Number of successful removals after relocking");
567 static long zap_bucket_fail;
568 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
569 static long zap_bucket_fail2;
570 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
571 static long cache_lock_vnodes_cel_3_failures;
572 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
573 "Number of times 3-way vnode locking failed");
575 static void cache_zap_locked(struct namecache *ncp);
576 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
577 char **retbuf, size_t *buflen, size_t addend);
578 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
579 char **retbuf, size_t *buflen);
580 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
581 char **retbuf, size_t *len, size_t addend);
583 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
586 cache_assert_vlp_locked(struct mtx *vlp)
590 mtx_assert(vlp, MA_OWNED);
594 cache_assert_vnode_locked(struct vnode *vp)
598 vlp = VP2VNODELOCK(vp);
599 cache_assert_vlp_locked(vlp);
603 * Directory vnodes with entries are held for two reasons:
604 * 1. make them less of a target for reclamation in vnlru
605 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
607 * It will be feasible to stop doing it altogether if all filesystems start
608 * supporting lockless lookup.
611 cache_hold_vnode(struct vnode *vp)
614 cache_assert_vnode_locked(vp);
615 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
617 counter_u64_add(numcachehv, 1);
621 cache_drop_vnode(struct vnode *vp)
625 * Called after all locks are dropped, meaning we can't assert
626 * on the state of v_cache_src.
629 counter_u64_add(numcachehv, -1);
635 static uma_zone_t __read_mostly cache_zone_small;
636 static uma_zone_t __read_mostly cache_zone_small_ts;
637 static uma_zone_t __read_mostly cache_zone_large;
638 static uma_zone_t __read_mostly cache_zone_large_ts;
641 cache_symlink_alloc(size_t size, int flags)
644 if (size < CACHE_ZONE_SMALL_SIZE) {
645 return (uma_zalloc_smr(cache_zone_small, flags));
647 if (size < CACHE_ZONE_LARGE_SIZE) {
648 return (uma_zalloc_smr(cache_zone_large, flags));
650 counter_u64_add(symlinktoobig, 1);
651 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
656 cache_symlink_free(char *string, size_t size)
659 MPASS(string != NULL);
660 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
661 ("%s: size %zu too big", __func__, size));
663 if (size < CACHE_ZONE_SMALL_SIZE) {
664 uma_zfree_smr(cache_zone_small, string);
667 if (size < CACHE_ZONE_LARGE_SIZE) {
668 uma_zfree_smr(cache_zone_large, string);
671 __assert_unreachable();
674 static struct namecache *
675 cache_alloc_uma(int len, bool ts)
677 struct namecache_ts *ncp_ts;
678 struct namecache *ncp;
680 if (__predict_false(ts)) {
681 if (len <= CACHE_PATH_CUTOFF)
682 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
684 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
685 ncp = &ncp_ts->nc_nc;
687 if (len <= CACHE_PATH_CUTOFF)
688 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
690 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
696 cache_free_uma(struct namecache *ncp)
698 struct namecache_ts *ncp_ts;
700 if (__predict_false(ncp->nc_flag & NCF_TS)) {
701 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
702 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
703 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
705 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
707 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
708 uma_zfree_smr(cache_zone_small, ncp);
710 uma_zfree_smr(cache_zone_large, ncp);
714 static struct namecache *
715 cache_alloc(int len, bool ts)
720 * Avoid blowout in namecache entries.
723 * 1. filesystems may end up trying to add an already existing entry
724 * (for example this can happen after a cache miss during concurrent
725 * lookup), in which case we will call cache_neg_evict despite not
727 * 2. the routine may fail to free anything and no provisions are made
728 * to make it try harder (see the inside for failure modes)
729 * 3. it only ever looks at negative entries.
731 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
732 if (cache_neg_evict_cond(lnumcache)) {
733 lnumcache = atomic_load_long(&numcache);
735 if (__predict_false(lnumcache >= ncsize)) {
736 atomic_subtract_long(&numcache, 1);
737 counter_u64_add(numdrops, 1);
740 return (cache_alloc_uma(len, ts));
744 cache_free(struct namecache *ncp)
748 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
749 cache_drop_vnode(ncp->nc_dvp);
752 atomic_subtract_long(&numcache, 1);
756 cache_free_batch(struct cache_freebatch *batch)
758 struct namecache *ncp, *nnp;
762 if (TAILQ_EMPTY(batch))
764 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
765 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
766 cache_drop_vnode(ncp->nc_dvp);
771 atomic_subtract_long(&numcache, i);
773 SDT_PROBE1(vfs, namecache, purge, batch, i);
779 * The code was made to use FNV in 2001 and this choice needs to be revisited.
781 * Short summary of the difficulty:
782 * The longest name which can be inserted is NAME_MAX characters in length (or
783 * 255 at the time of writing this comment), while majority of names used in
784 * practice are significantly shorter (mostly below 10). More importantly
785 * majority of lookups performed find names are even shorter than that.
787 * This poses a problem where hashes which do better than FNV past word size
788 * (or so) tend to come with additional overhead when finalizing the result,
789 * making them noticeably slower for the most commonly used range.
791 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
793 * When looking it up the most time consuming part by a large margin (at least
794 * on amd64) is hashing. Replacing FNV with something which pessimizes short
795 * input would make the slowest part stand out even more.
799 * TODO: With the value stored we can do better than computing the hash based
803 cache_prehash(struct vnode *vp)
806 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
810 cache_get_hash(char *name, u_char len, struct vnode *dvp)
813 return (fnv_32_buf(name, len, dvp->v_nchash));
817 cache_get_hash_iter_start(struct vnode *dvp)
820 return (dvp->v_nchash);
824 cache_get_hash_iter(char c, uint32_t hash)
827 return (fnv_32_buf(&c, 1, hash));
831 cache_get_hash_iter_finish(uint32_t hash)
837 static inline struct nchashhead *
838 NCP2BUCKET(struct namecache *ncp)
842 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
843 return (NCHHASH(hash));
846 static inline struct mtx *
847 NCP2BUCKETLOCK(struct namecache *ncp)
851 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
852 return (HASH2BUCKETLOCK(hash));
857 cache_assert_bucket_locked(struct namecache *ncp)
861 blp = NCP2BUCKETLOCK(ncp);
862 mtx_assert(blp, MA_OWNED);
866 cache_assert_bucket_unlocked(struct namecache *ncp)
870 blp = NCP2BUCKETLOCK(ncp);
871 mtx_assert(blp, MA_NOTOWNED);
874 #define cache_assert_bucket_locked(x) do { } while (0)
875 #define cache_assert_bucket_unlocked(x) do { } while (0)
878 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
880 _cache_sort_vnodes(void **p1, void **p2)
884 MPASS(*p1 != NULL || *p2 != NULL);
894 cache_lock_all_buckets(void)
898 for (i = 0; i < numbucketlocks; i++)
899 mtx_lock(&bucketlocks[i]);
903 cache_unlock_all_buckets(void)
907 for (i = 0; i < numbucketlocks; i++)
908 mtx_unlock(&bucketlocks[i]);
912 cache_lock_all_vnodes(void)
916 for (i = 0; i < numvnodelocks; i++)
917 mtx_lock(&vnodelocks[i]);
921 cache_unlock_all_vnodes(void)
925 for (i = 0; i < numvnodelocks; i++)
926 mtx_unlock(&vnodelocks[i]);
930 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
933 cache_sort_vnodes(&vlp1, &vlp2);
936 if (!mtx_trylock(vlp1))
939 if (!mtx_trylock(vlp2)) {
949 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
952 MPASS(vlp1 != NULL || vlp2 != NULL);
962 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
965 MPASS(vlp1 != NULL || vlp2 != NULL);
974 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
976 struct nchstats snap;
978 if (req->oldptr == NULL)
979 return (SYSCTL_OUT(req, 0, sizeof(snap)));
982 snap.ncs_goodhits = counter_u64_fetch(numposhits);
983 snap.ncs_neghits = counter_u64_fetch(numneghits);
984 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
985 counter_u64_fetch(numnegzaps);
986 snap.ncs_miss = counter_u64_fetch(nummisszap) +
987 counter_u64_fetch(nummiss);
989 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
991 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
992 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
993 "VFS cache effectiveness statistics");
996 cache_recalc_neg_min(u_int val)
999 neg_min = (ncsize * val) / 100;
1003 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1009 error = sysctl_handle_int(oidp, &val, 0, req);
1010 if (error != 0 || req->newptr == NULL)
1013 if (val == ncnegminpct)
1015 if (val < 0 || val > 99)
1018 cache_recalc_neg_min(val);
1022 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1023 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1024 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1028 * Grab an atomic snapshot of the name cache hash chain lengths
1030 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1031 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1032 "hash table stats");
1035 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1037 struct nchashhead *ncpp;
1038 struct namecache *ncp;
1039 int i, error, n_nchash, *cntbuf;
1042 n_nchash = nchash + 1; /* nchash is max index, not count */
1043 if (req->oldptr == NULL)
1044 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1045 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1046 cache_lock_all_buckets();
1047 if (n_nchash != nchash + 1) {
1048 cache_unlock_all_buckets();
1049 free(cntbuf, M_TEMP);
1052 /* Scan hash tables counting entries */
1053 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1054 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1056 cache_unlock_all_buckets();
1057 for (error = 0, i = 0; i < n_nchash; i++)
1058 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1060 free(cntbuf, M_TEMP);
1063 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1064 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1065 "nchash chain lengths");
1068 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1071 struct nchashhead *ncpp;
1072 struct namecache *ncp;
1074 int count, maxlength, used, pct;
1077 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1079 cache_lock_all_buckets();
1080 n_nchash = nchash + 1; /* nchash is max index, not count */
1084 /* Scan hash tables for applicable entries */
1085 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1087 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1092 if (maxlength < count)
1095 n_nchash = nchash + 1;
1096 cache_unlock_all_buckets();
1097 pct = (used * 100) / (n_nchash / 100);
1098 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1101 error = SYSCTL_OUT(req, &used, sizeof(used));
1104 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1107 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1112 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1113 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1114 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1118 * Negative entries management
1120 * Various workloads create plenty of negative entries and barely use them
1121 * afterwards. Moreover malicious users can keep performing bogus lookups
1122 * adding even more entries. For example "make tinderbox" as of writing this
1123 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1126 * As such, a rather aggressive eviction method is needed. The currently
1127 * employed method is a placeholder.
1129 * Entries are split over numneglists separate lists, each of which is further
1130 * split into hot and cold entries. Entries get promoted after getting a hit.
1131 * Eviction happens on addition of new entry.
1133 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1134 "Name cache negative entry statistics");
1136 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1137 "Number of negative cache entries");
1139 static COUNTER_U64_DEFINE_EARLY(neg_created);
1140 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1141 "Number of created negative entries");
1143 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1144 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1145 "Number of evicted negative entries");
1147 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1148 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1149 &neg_evict_skipped_empty,
1150 "Number of times evicting failed due to lack of entries");
1152 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1153 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1154 &neg_evict_skipped_missed,
1155 "Number of times evicting failed due to target entry disappearing");
1157 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1158 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1159 &neg_evict_skipped_contended,
1160 "Number of times evicting failed due to contention");
1162 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1163 "Number of cache hits (negative)");
1166 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1171 for (i = 0; i < numneglists; i++)
1172 out += neglists[i].nl_hotnum;
1174 return (SYSCTL_OUT(req, &out, sizeof(out)));
1176 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1177 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1178 "Number of hot negative entries");
1181 cache_neg_init(struct namecache *ncp)
1183 struct negstate *ns;
1185 ncp->nc_flag |= NCF_NEGATIVE;
1186 ns = NCP2NEGSTATE(ncp);
1189 counter_u64_add(neg_created, 1);
1192 #define CACHE_NEG_PROMOTION_THRESH 2
1195 cache_neg_hit_prep(struct namecache *ncp)
1197 struct negstate *ns;
1200 ns = NCP2NEGSTATE(ncp);
1201 n = atomic_load_char(&ns->neg_hit);
1203 if (n >= CACHE_NEG_PROMOTION_THRESH)
1205 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1208 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1212 * Nothing to do here but it is provided for completeness as some
1213 * cache_neg_hit_prep callers may end up returning without even
1214 * trying to promote.
1216 #define cache_neg_hit_abort(ncp) do { } while (0)
1219 cache_neg_hit_finish(struct namecache *ncp)
1222 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1223 counter_u64_add(numneghits, 1);
1227 * Move a negative entry to the hot list.
1230 cache_neg_promote_locked(struct namecache *ncp)
1233 struct negstate *ns;
1235 ns = NCP2NEGSTATE(ncp);
1236 nl = NCP2NEGLIST(ncp);
1237 mtx_assert(&nl->nl_lock, MA_OWNED);
1238 if ((ns->neg_flag & NEG_HOT) == 0) {
1239 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1240 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1242 ns->neg_flag |= NEG_HOT;
1247 * Move a hot negative entry to the cold list.
1250 cache_neg_demote_locked(struct namecache *ncp)
1253 struct negstate *ns;
1255 ns = NCP2NEGSTATE(ncp);
1256 nl = NCP2NEGLIST(ncp);
1257 mtx_assert(&nl->nl_lock, MA_OWNED);
1258 MPASS(ns->neg_flag & NEG_HOT);
1259 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1260 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1262 ns->neg_flag &= ~NEG_HOT;
1263 atomic_store_char(&ns->neg_hit, 0);
1267 * Move a negative entry to the hot list if it matches the lookup.
1269 * We have to take locks, but they may be contended and in the worst
1270 * case we may need to go off CPU. We don't want to spin within the
1271 * smr section and we can't block with it. Exiting the section means
1272 * the found entry could have been evicted. We are going to look it
1276 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1277 struct namecache *oncp, uint32_t hash)
1279 struct namecache *ncp;
1283 nl = NCP2NEGLIST(oncp);
1285 mtx_lock(&nl->nl_lock);
1287 * For hash iteration.
1292 * Avoid all surprises by only succeeding if we got the same entry and
1293 * bailing completely otherwise.
1294 * XXX There are no provisions to keep the vnode around, meaning we may
1295 * end up promoting a negative entry for a *new* vnode and returning
1296 * ENOENT on its account. This is the error we want to return anyway
1297 * and promotion is harmless.
1299 * In particular at this point there can be a new ncp which matches the
1300 * search but hashes to a different neglist.
1302 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1308 * No match to begin with.
1310 if (__predict_false(ncp == NULL)) {
1315 * The newly found entry may be something different...
1317 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1318 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1323 * ... and not even negative.
1325 nc_flag = atomic_load_char(&ncp->nc_flag);
1326 if ((nc_flag & NCF_NEGATIVE) == 0) {
1330 if (!cache_ncp_canuse(ncp)) {
1334 cache_neg_promote_locked(ncp);
1335 cache_neg_hit_finish(ncp);
1337 mtx_unlock(&nl->nl_lock);
1341 mtx_unlock(&nl->nl_lock);
1346 cache_neg_promote(struct namecache *ncp)
1350 nl = NCP2NEGLIST(ncp);
1351 mtx_lock(&nl->nl_lock);
1352 cache_neg_promote_locked(ncp);
1353 mtx_unlock(&nl->nl_lock);
1357 cache_neg_insert(struct namecache *ncp)
1361 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1362 cache_assert_bucket_locked(ncp);
1363 nl = NCP2NEGLIST(ncp);
1364 mtx_lock(&nl->nl_lock);
1365 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1366 mtx_unlock(&nl->nl_lock);
1367 atomic_add_long(&numneg, 1);
1371 cache_neg_remove(struct namecache *ncp)
1374 struct negstate *ns;
1376 cache_assert_bucket_locked(ncp);
1377 nl = NCP2NEGLIST(ncp);
1378 ns = NCP2NEGSTATE(ncp);
1379 mtx_lock(&nl->nl_lock);
1380 if ((ns->neg_flag & NEG_HOT) != 0) {
1381 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1384 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1386 mtx_unlock(&nl->nl_lock);
1387 atomic_subtract_long(&numneg, 1);
1390 static struct neglist *
1391 cache_neg_evict_select_list(void)
1396 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1397 nl = &neglists[c % numneglists];
1398 if (!mtx_trylock(&nl->nl_evict_lock)) {
1399 counter_u64_add(neg_evict_skipped_contended, 1);
1405 static struct namecache *
1406 cache_neg_evict_select_entry(struct neglist *nl)
1408 struct namecache *ncp, *lncp;
1409 struct negstate *ns, *lns;
1412 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1413 mtx_assert(&nl->nl_lock, MA_OWNED);
1414 ncp = TAILQ_FIRST(&nl->nl_list);
1418 lns = NCP2NEGSTATE(lncp);
1419 for (i = 1; i < 4; i++) {
1420 ncp = TAILQ_NEXT(ncp, nc_dst);
1423 ns = NCP2NEGSTATE(ncp);
1424 if (ns->neg_hit < lns->neg_hit) {
1433 cache_neg_evict(void)
1435 struct namecache *ncp, *ncp2;
1444 nl = cache_neg_evict_select_list();
1449 mtx_lock(&nl->nl_lock);
1450 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1452 cache_neg_demote_locked(ncp);
1454 ncp = cache_neg_evict_select_entry(nl);
1456 counter_u64_add(neg_evict_skipped_empty, 1);
1457 mtx_unlock(&nl->nl_lock);
1458 mtx_unlock(&nl->nl_evict_lock);
1461 nlen = ncp->nc_nlen;
1463 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1464 dvlp = VP2VNODELOCK(dvp);
1465 blp = HASH2BUCKETLOCK(hash);
1466 mtx_unlock(&nl->nl_lock);
1467 mtx_unlock(&nl->nl_evict_lock);
1471 * Note that since all locks were dropped above, the entry may be
1472 * gone or reallocated to be something else.
1474 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1475 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1476 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1480 counter_u64_add(neg_evict_skipped_missed, 1);
1484 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1485 MPASS(blp == NCP2BUCKETLOCK(ncp));
1486 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1488 cache_zap_locked(ncp);
1489 counter_u64_add(neg_evicted, 1);
1500 * Maybe evict a negative entry to create more room.
1502 * The ncnegfactor parameter limits what fraction of the total count
1503 * can comprise of negative entries. However, if the cache is just
1504 * warming up this leads to excessive evictions. As such, ncnegminpct
1505 * (recomputed to neg_min) dictates whether the above should be
1508 * Try evicting if the cache is close to full capacity regardless of
1509 * other considerations.
1512 cache_neg_evict_cond(u_long lnumcache)
1516 if (ncsize - 1000 < lnumcache)
1518 lnumneg = atomic_load_long(&numneg);
1519 if (lnumneg < neg_min)
1521 if (lnumneg * ncnegfactor < lnumcache)
1524 return (cache_neg_evict());
1528 * cache_zap_locked():
1530 * Removes a namecache entry from cache, whether it contains an actual
1531 * pointer to a vnode or if it is just a negative cache entry.
1534 cache_zap_locked(struct namecache *ncp)
1536 struct nchashhead *ncpp;
1537 struct vnode *dvp, *vp;
1542 if (!(ncp->nc_flag & NCF_NEGATIVE))
1543 cache_assert_vnode_locked(vp);
1544 cache_assert_vnode_locked(dvp);
1545 cache_assert_bucket_locked(ncp);
1547 cache_ncp_invalidate(ncp);
1549 ncpp = NCP2BUCKET(ncp);
1550 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1551 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1552 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1553 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1554 if (ncp == vp->v_cache_dd) {
1555 atomic_store_ptr(&vp->v_cache_dd, NULL);
1558 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1559 cache_neg_remove(ncp);
1561 if (ncp->nc_flag & NCF_ISDOTDOT) {
1562 if (ncp == dvp->v_cache_dd) {
1563 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1566 LIST_REMOVE(ncp, nc_src);
1567 if (LIST_EMPTY(&dvp->v_cache_src)) {
1568 ncp->nc_flag |= NCF_DVDROP;
1574 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1578 MPASS(ncp->nc_dvp == vp);
1579 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1580 cache_assert_vnode_locked(vp);
1582 blp = NCP2BUCKETLOCK(ncp);
1584 cache_zap_locked(ncp);
1589 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1592 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1595 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1596 cache_assert_vnode_locked(vp);
1598 if (ncp->nc_flag & NCF_NEGATIVE) {
1599 if (*vlpp != NULL) {
1603 cache_zap_negative_locked_vnode_kl(ncp, vp);
1607 pvlp = VP2VNODELOCK(vp);
1608 blp = NCP2BUCKETLOCK(ncp);
1609 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1610 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1612 if (*vlpp == vlp1 || *vlpp == vlp2) {
1616 if (*vlpp != NULL) {
1620 cache_sort_vnodes(&vlp1, &vlp2);
1625 if (!mtx_trylock(vlp1))
1631 cache_zap_locked(ncp);
1633 if (to_unlock != NULL)
1634 mtx_unlock(to_unlock);
1641 MPASS(*vlpp == NULL);
1647 * If trylocking failed we can get here. We know enough to take all needed locks
1648 * in the right order and re-lookup the entry.
1651 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1652 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1655 struct namecache *rncp;
1657 cache_assert_bucket_unlocked(ncp);
1659 cache_sort_vnodes(&dvlp, &vlp);
1660 cache_lock_vnodes(dvlp, vlp);
1662 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1663 if (rncp == ncp && rncp->nc_dvp == dvp &&
1664 rncp->nc_nlen == cnp->cn_namelen &&
1665 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1669 cache_zap_locked(rncp);
1671 cache_unlock_vnodes(dvlp, vlp);
1672 counter_u64_add(zap_bucket_relock_success, 1);
1677 cache_unlock_vnodes(dvlp, vlp);
1681 static int __noinline
1682 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1683 uint32_t hash, struct mtx *blp)
1685 struct mtx *dvlp, *vlp;
1688 cache_assert_bucket_locked(ncp);
1690 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1692 if (!(ncp->nc_flag & NCF_NEGATIVE))
1693 vlp = VP2VNODELOCK(ncp->nc_vp);
1694 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1695 cache_zap_locked(ncp);
1697 cache_unlock_vnodes(dvlp, vlp);
1703 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1706 static __noinline int
1707 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1709 struct namecache *ncp;
1711 struct mtx *dvlp, *dvlp2;
1715 if (cnp->cn_namelen == 2 &&
1716 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1717 dvlp = VP2VNODELOCK(dvp);
1721 ncp = dvp->v_cache_dd;
1726 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1729 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1730 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1732 MPASS(dvp->v_cache_dd == NULL);
1738 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1743 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1747 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1748 blp = HASH2BUCKETLOCK(hash);
1750 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1755 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1756 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1757 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1766 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1767 if (__predict_false(error != 0)) {
1771 counter_u64_add(numposzaps, 1);
1772 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1776 counter_u64_add(nummisszap, 1);
1777 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1781 static int __noinline
1782 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1783 struct timespec *tsp, int *ticksp)
1788 counter_u64_add(dothits, 1);
1789 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1796 * When we lookup "." we still can be asked to lock it
1799 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1800 if (ltype != VOP_ISLOCKED(*vpp)) {
1801 if (ltype == LK_EXCLUSIVE) {
1802 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1803 if (VN_IS_DOOMED((*vpp))) {
1804 /* forced unmount */
1810 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1815 static int __noinline
1816 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1817 struct timespec *tsp, int *ticksp)
1819 struct namecache_ts *ncp_ts;
1820 struct namecache *ncp;
1826 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1828 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1829 cache_remove_cnp(dvp, cnp);
1833 counter_u64_add(dotdothits, 1);
1835 dvlp = VP2VNODELOCK(dvp);
1837 ncp = dvp->v_cache_dd;
1839 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1843 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1844 if (ncp->nc_flag & NCF_NEGATIVE)
1851 goto negative_success;
1852 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1853 cache_out_ts(ncp, tsp, ticksp);
1854 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1855 NCF_DTS && tsp != NULL) {
1856 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1857 *tsp = ncp_ts->nc_dotdottime;
1861 ltype = VOP_ISLOCKED(dvp);
1863 vs = vget_prep(*vpp);
1865 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1866 vn_lock(dvp, ltype | LK_RETRY);
1867 if (VN_IS_DOOMED(dvp)) {
1879 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1880 if (cnp->cn_flags & ISLASTCN) {
1881 counter_u64_add(numnegzaps, 1);
1882 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1889 whiteout = (ncp->nc_flag & NCF_WHITE);
1890 cache_out_ts(ncp, tsp, ticksp);
1891 if (cache_neg_hit_prep(ncp))
1892 cache_neg_promote(ncp);
1894 cache_neg_hit_finish(ncp);
1897 cnp->cn_flags |= ISWHITEOUT;
1902 * Lookup a name in the name cache
1906 * - dvp: Parent directory in which to search.
1907 * - vpp: Return argument. Will contain desired vnode on cache hit.
1908 * - cnp: Parameters of the name search. The most interesting bits of
1909 * the cn_flags field have the following meanings:
1910 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1912 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1913 * - tsp: Return storage for cache timestamp. On a successful (positive
1914 * or negative) lookup, tsp will be filled with any timespec that
1915 * was stored when this cache entry was created. However, it will
1916 * be clear for "." entries.
1917 * - ticks: Return storage for alternate cache timestamp. On a successful
1918 * (positive or negative) lookup, it will contain the ticks value
1919 * that was current when the cache entry was created, unless cnp
1922 * Either both tsp and ticks have to be provided or neither of them.
1926 * - -1: A positive cache hit. vpp will contain the desired vnode.
1927 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1928 * to a forced unmount. vpp will not be modified. If the entry
1929 * is a whiteout, then the ISWHITEOUT flag will be set in
1931 * - 0: A cache miss. vpp will not be modified.
1935 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1936 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1937 * lock is not recursively acquired.
1939 static int __noinline
1940 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1941 struct timespec *tsp, int *ticksp)
1943 struct namecache *ncp;
1950 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1951 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1954 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1955 blp = HASH2BUCKETLOCK(hash);
1958 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1959 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1960 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1964 if (__predict_false(ncp == NULL)) {
1966 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
1967 counter_u64_add(nummiss, 1);
1971 if (ncp->nc_flag & NCF_NEGATIVE)
1972 goto negative_success;
1974 counter_u64_add(numposhits, 1);
1976 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1977 cache_out_ts(ncp, tsp, ticksp);
1979 vs = vget_prep(*vpp);
1981 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1989 * We don't get here with regular lookup apart from corner cases.
1991 if (__predict_true(cnp->cn_nameiop == CREATE)) {
1992 if (cnp->cn_flags & ISLASTCN) {
1993 counter_u64_add(numnegzaps, 1);
1994 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1995 if (__predict_false(error != 0)) {
2004 whiteout = (ncp->nc_flag & NCF_WHITE);
2005 cache_out_ts(ncp, tsp, ticksp);
2006 if (cache_neg_hit_prep(ncp))
2007 cache_neg_promote(ncp);
2009 cache_neg_hit_finish(ncp);
2012 cnp->cn_flags |= ISWHITEOUT;
2017 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2018 struct timespec *tsp, int *ticksp)
2020 struct namecache *ncp;
2024 bool whiteout, neg_promote;
2027 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2030 if (__predict_false(!doingcache)) {
2031 cnp->cn_flags &= ~MAKEENTRY;
2036 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2037 if (cnp->cn_namelen == 1)
2038 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2039 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2040 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2043 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2045 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2046 cache_remove_cnp(dvp, cnp);
2050 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2053 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2054 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2055 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2059 if (__predict_false(ncp == NULL)) {
2061 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2062 counter_u64_add(nummiss, 1);
2066 nc_flag = atomic_load_char(&ncp->nc_flag);
2067 if (nc_flag & NCF_NEGATIVE)
2068 goto negative_success;
2070 counter_u64_add(numposhits, 1);
2072 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2073 cache_out_ts(ncp, tsp, ticksp);
2075 if (!cache_ncp_canuse(ncp)) {
2080 vs = vget_prep_smr(*vpp);
2082 if (__predict_false(vs == VGET_NONE)) {
2086 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2093 if (cnp->cn_nameiop == CREATE) {
2094 if (cnp->cn_flags & ISLASTCN) {
2100 cache_out_ts(ncp, tsp, ticksp);
2101 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2102 neg_promote = cache_neg_hit_prep(ncp);
2103 if (!cache_ncp_canuse(ncp)) {
2104 cache_neg_hit_abort(ncp);
2110 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2113 cache_neg_hit_finish(ncp);
2117 cnp->cn_flags |= ISWHITEOUT;
2120 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2123 struct celockstate {
2127 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2128 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2131 cache_celockstate_init(struct celockstate *cel)
2134 bzero(cel, sizeof(*cel));
2138 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2141 struct mtx *vlp1, *vlp2;
2143 MPASS(cel->vlp[0] == NULL);
2144 MPASS(cel->vlp[1] == NULL);
2145 MPASS(cel->vlp[2] == NULL);
2147 MPASS(vp != NULL || dvp != NULL);
2149 vlp1 = VP2VNODELOCK(vp);
2150 vlp2 = VP2VNODELOCK(dvp);
2151 cache_sort_vnodes(&vlp1, &vlp2);
2162 cache_unlock_vnodes_cel(struct celockstate *cel)
2165 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2167 if (cel->vlp[0] != NULL)
2168 mtx_unlock(cel->vlp[0]);
2169 if (cel->vlp[1] != NULL)
2170 mtx_unlock(cel->vlp[1]);
2171 if (cel->vlp[2] != NULL)
2172 mtx_unlock(cel->vlp[2]);
2176 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2181 cache_assert_vlp_locked(cel->vlp[0]);
2182 cache_assert_vlp_locked(cel->vlp[1]);
2183 MPASS(cel->vlp[2] == NULL);
2186 vlp = VP2VNODELOCK(vp);
2189 if (vlp >= cel->vlp[1]) {
2192 if (mtx_trylock(vlp))
2194 cache_lock_vnodes_cel_3_failures++;
2195 cache_unlock_vnodes_cel(cel);
2196 if (vlp < cel->vlp[0]) {
2198 mtx_lock(cel->vlp[0]);
2199 mtx_lock(cel->vlp[1]);
2201 if (cel->vlp[0] != NULL)
2202 mtx_lock(cel->vlp[0]);
2204 mtx_lock(cel->vlp[1]);
2214 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2218 MPASS(cel->blp[0] == NULL);
2219 MPASS(cel->blp[1] == NULL);
2221 cache_sort_vnodes(&blp1, &blp2);
2232 cache_unlock_buckets_cel(struct celockstate *cel)
2235 if (cel->blp[0] != NULL)
2236 mtx_unlock(cel->blp[0]);
2237 mtx_unlock(cel->blp[1]);
2241 * Lock part of the cache affected by the insertion.
2243 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2244 * However, insertion can result in removal of an old entry. In this
2245 * case we have an additional vnode and bucketlock pair to lock.
2247 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2248 * preserving the locking order (smaller address first).
2251 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2254 struct namecache *ncp;
2255 struct mtx *blps[2];
2258 blps[0] = HASH2BUCKETLOCK(hash);
2261 cache_lock_vnodes_cel(cel, dvp, vp);
2262 if (vp == NULL || vp->v_type != VDIR)
2264 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2267 nc_flag = atomic_load_char(&ncp->nc_flag);
2268 if ((nc_flag & NCF_ISDOTDOT) == 0)
2270 MPASS(ncp->nc_dvp == vp);
2271 blps[1] = NCP2BUCKETLOCK(ncp);
2272 if ((nc_flag & NCF_NEGATIVE) != 0)
2274 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2277 * All vnodes got re-locked. Re-validate the state and if
2278 * nothing changed we are done. Otherwise restart.
2280 if (ncp == vp->v_cache_dd &&
2281 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2282 blps[1] == NCP2BUCKETLOCK(ncp) &&
2283 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2285 cache_unlock_vnodes_cel(cel);
2290 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2294 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2297 struct namecache *ncp;
2298 struct mtx *blps[2];
2301 blps[0] = HASH2BUCKETLOCK(hash);
2304 cache_lock_vnodes_cel(cel, dvp, vp);
2305 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2308 nc_flag = atomic_load_char(&ncp->nc_flag);
2309 if ((nc_flag & NCF_ISDOTDOT) == 0)
2311 MPASS(ncp->nc_dvp == dvp);
2312 blps[1] = NCP2BUCKETLOCK(ncp);
2313 if ((nc_flag & NCF_NEGATIVE) != 0)
2315 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2317 if (ncp == dvp->v_cache_dd &&
2318 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2319 blps[1] == NCP2BUCKETLOCK(ncp) &&
2320 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2322 cache_unlock_vnodes_cel(cel);
2327 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2331 cache_enter_unlock(struct celockstate *cel)
2334 cache_unlock_buckets_cel(cel);
2335 cache_unlock_vnodes_cel(cel);
2338 static void __noinline
2339 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2340 struct componentname *cnp)
2342 struct celockstate cel;
2343 struct namecache *ncp;
2347 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2349 len = cnp->cn_namelen;
2350 cache_celockstate_init(&cel);
2351 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2352 cache_enter_lock_dd(&cel, dvp, vp, hash);
2353 ncp = dvp->v_cache_dd;
2354 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2355 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2356 cache_zap_locked(ncp);
2360 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2361 cache_enter_unlock(&cel);
2367 * Add an entry to the cache.
2370 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2371 struct timespec *tsp, struct timespec *dtsp)
2373 struct celockstate cel;
2374 struct namecache *ncp, *n2, *ndd;
2375 struct namecache_ts *ncp_ts;
2376 struct nchashhead *ncpp;
2381 KASSERT(cnp->cn_namelen <= NAME_MAX,
2382 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2384 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2385 VNPASS(dvp->v_type != VNON, dvp);
2387 VNPASS(!VN_IS_DOOMED(vp), vp);
2388 VNPASS(vp->v_type != VNON, vp);
2390 if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
2392 ("%s: different vnodes for dot entry (%p; %p)\n", __func__,
2396 ("%s: same vnode for non-dot entry [%s] (%p)\n", __func__,
2397 cnp->cn_nameptr, dvp));
2401 if (__predict_false(!doingcache))
2406 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2407 if (cnp->cn_namelen == 1)
2409 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2410 cache_enter_dotdot_prep(dvp, vp, cnp);
2411 flag = NCF_ISDOTDOT;
2415 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2419 cache_celockstate_init(&cel);
2424 * Calculate the hash key and setup as much of the new
2425 * namecache entry as possible before acquiring the lock.
2427 ncp->nc_flag = flag | NCF_WIP;
2430 cache_neg_init(ncp);
2433 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2434 ncp_ts->nc_time = *tsp;
2435 ncp_ts->nc_ticks = ticks;
2436 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2438 ncp_ts->nc_dotdottime = *dtsp;
2439 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2442 len = ncp->nc_nlen = cnp->cn_namelen;
2443 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2444 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2445 ncp->nc_name[len] = '\0';
2446 cache_enter_lock(&cel, dvp, vp, hash);
2449 * See if this vnode or negative entry is already in the cache
2450 * with this name. This can happen with concurrent lookups of
2451 * the same path name.
2453 ncpp = NCHHASH(hash);
2454 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2455 if (n2->nc_dvp == dvp &&
2456 n2->nc_nlen == cnp->cn_namelen &&
2457 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2458 MPASS(cache_ncp_canuse(n2));
2459 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2461 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2462 __func__, NULL, vp, cnp->cn_nameptr));
2464 KASSERT(n2->nc_vp == vp,
2465 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2466 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2468 * Entries are supposed to be immutable unless in the
2469 * process of getting destroyed. Accommodating for
2470 * changing timestamps is possible but not worth it.
2471 * This should be harmless in terms of correctness, in
2472 * the worst case resulting in an earlier expiration.
2473 * Alternatively, the found entry can be replaced
2476 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2479 KASSERT((n2->nc_flag & NCF_TS) != 0,
2481 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2482 n2_ts->nc_time = ncp_ts->nc_time;
2483 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2485 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2486 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2490 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2492 goto out_unlock_free;
2496 if (flag == NCF_ISDOTDOT) {
2498 * See if we are trying to add .. entry, but some other lookup
2499 * has populated v_cache_dd pointer already.
2501 if (dvp->v_cache_dd != NULL)
2502 goto out_unlock_free;
2503 KASSERT(vp == NULL || vp->v_type == VDIR,
2504 ("wrong vnode type %p", vp));
2505 atomic_thread_fence_rel();
2506 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2510 if (flag != NCF_ISDOTDOT) {
2512 * For this case, the cache entry maps both the
2513 * directory name in it and the name ".." for the
2514 * directory's parent.
2516 if ((ndd = vp->v_cache_dd) != NULL) {
2517 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2518 cache_zap_locked(ndd);
2522 atomic_thread_fence_rel();
2523 atomic_store_ptr(&vp->v_cache_dd, ncp);
2524 } else if (vp->v_type != VDIR) {
2525 if (vp->v_cache_dd != NULL) {
2526 atomic_store_ptr(&vp->v_cache_dd, NULL);
2531 if (flag != NCF_ISDOTDOT) {
2532 if (LIST_EMPTY(&dvp->v_cache_src)) {
2533 cache_hold_vnode(dvp);
2535 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2539 * If the entry is "negative", we place it into the
2540 * "negative" cache queue, otherwise, we place it into the
2541 * destination vnode's cache entries queue.
2544 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2545 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2548 if (cnp->cn_flags & ISWHITEOUT)
2549 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2550 cache_neg_insert(ncp);
2551 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2556 * Insert the new namecache entry into the appropriate chain
2557 * within the cache entries table.
2559 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2561 atomic_thread_fence_rel();
2563 * Mark the entry as fully constructed.
2564 * It is immutable past this point until its removal.
2566 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2568 cache_enter_unlock(&cel);
2573 cache_enter_unlock(&cel);
2579 * A variant of the above accepting flags.
2581 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2583 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2584 * happens to match and it is doing it in an inefficient manner. It was added
2585 * to accommodate NFS which runs into a case where the target for a given name
2586 * may change from under it. Note this does nothing to solve the following
2587 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2588 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2591 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2592 struct timespec *tsp, struct timespec *dtsp, int flags)
2595 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2597 if (flags & VFS_CACHE_DROPOLD)
2598 cache_remove_cnp(dvp, cnp);
2599 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2603 cache_roundup_2(u_int val)
2607 for (res = 1; res <= val; res <<= 1)
2613 static struct nchashhead *
2614 nchinittbl(u_long elements, u_long *hashmask)
2616 struct nchashhead *hashtbl;
2619 hashsize = cache_roundup_2(elements) / 2;
2621 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2622 for (i = 0; i < hashsize; i++)
2623 CK_SLIST_INIT(&hashtbl[i]);
2624 *hashmask = hashsize - 1;
2629 ncfreetbl(struct nchashhead *hashtbl)
2632 free(hashtbl, M_VFSCACHE);
2636 * Name cache initialization, from vfs_init() when we are booting
2639 nchinit(void *dummy __unused)
2643 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2644 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2645 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2646 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2647 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2648 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2649 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2650 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2652 VFS_SMR_ZONE_SET(cache_zone_small);
2653 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2654 VFS_SMR_ZONE_SET(cache_zone_large);
2655 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2657 ncsize = desiredvnodes * ncsizefactor;
2658 cache_recalc_neg_min(ncnegminpct);
2659 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2660 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2661 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2663 if (ncbuckethash > nchash)
2664 ncbuckethash = nchash;
2665 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2667 for (i = 0; i < numbucketlocks; i++)
2668 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2669 ncvnodehash = ncbuckethash;
2670 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2672 for (i = 0; i < numvnodelocks; i++)
2673 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2675 for (i = 0; i < numneglists; i++) {
2676 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2677 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2678 TAILQ_INIT(&neglists[i].nl_list);
2679 TAILQ_INIT(&neglists[i].nl_hotlist);
2682 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2685 cache_vnode_init(struct vnode *vp)
2688 LIST_INIT(&vp->v_cache_src);
2689 TAILQ_INIT(&vp->v_cache_dst);
2690 vp->v_cache_dd = NULL;
2695 * Induce transient cache misses for lockless operation in cache_lookup() by
2696 * using a temporary hash table.
2698 * This will force a fs lookup.
2700 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2701 * to observe all CPUs not performing the lookup.
2704 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2707 MPASS(temphash < nchash);
2709 * Change the size. The new size is smaller and can safely be used
2710 * against the existing table. All lookups which now hash wrong will
2711 * result in a cache miss, which all callers are supposed to know how
2714 atomic_store_long(&nchash, temphash);
2715 atomic_thread_fence_rel();
2716 vfs_smr_synchronize();
2718 * At this point everyone sees the updated hash value, but they still
2719 * see the old table.
2721 atomic_store_ptr(&nchashtbl, temptbl);
2722 atomic_thread_fence_rel();
2723 vfs_smr_synchronize();
2725 * At this point everyone sees the updated table pointer and size pair.
2730 * Set the new hash table.
2732 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2733 * lockless operation in cache_lookup().
2736 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2739 MPASS(nchash < new_hash);
2741 * Change the pointer first. This wont result in out of bounds access
2742 * since the temporary table is guaranteed to be smaller.
2744 atomic_store_ptr(&nchashtbl, new_tbl);
2745 atomic_thread_fence_rel();
2746 vfs_smr_synchronize();
2748 * At this point everyone sees the updated pointer value, but they
2749 * still see the old size.
2751 atomic_store_long(&nchash, new_hash);
2752 atomic_thread_fence_rel();
2753 vfs_smr_synchronize();
2755 * At this point everyone sees the updated table pointer and size pair.
2760 cache_changesize(u_long newmaxvnodes)
2762 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2763 u_long new_nchash, old_nchash, temphash;
2764 struct namecache *ncp;
2769 newncsize = newmaxvnodes * ncsizefactor;
2770 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2771 if (newmaxvnodes < numbucketlocks)
2772 newmaxvnodes = numbucketlocks;
2774 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2775 /* If same hash table size, nothing to do */
2776 if (nchash == new_nchash) {
2777 ncfreetbl(new_nchashtbl);
2781 temptbl = nchinittbl(1, &temphash);
2784 * Move everything from the old hash table to the new table.
2785 * None of the namecache entries in the table can be removed
2786 * because to do so, they have to be removed from the hash table.
2788 cache_lock_all_vnodes();
2789 cache_lock_all_buckets();
2790 old_nchashtbl = nchashtbl;
2791 old_nchash = nchash;
2792 cache_changesize_set_temp(temptbl, temphash);
2793 for (i = 0; i <= old_nchash; i++) {
2794 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2795 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2797 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2798 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2802 cache_recalc_neg_min(ncnegminpct);
2803 cache_changesize_set_new(new_nchashtbl, new_nchash);
2804 cache_unlock_all_buckets();
2805 cache_unlock_all_vnodes();
2806 ncfreetbl(old_nchashtbl);
2811 * Remove all entries from and to a particular vnode.
2814 cache_purge_impl(struct vnode *vp)
2816 struct cache_freebatch batch;
2817 struct namecache *ncp;
2818 struct mtx *vlp, *vlp2;
2821 vlp = VP2VNODELOCK(vp);
2825 while (!LIST_EMPTY(&vp->v_cache_src)) {
2826 ncp = LIST_FIRST(&vp->v_cache_src);
2827 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2829 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2831 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2832 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2833 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2835 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2837 ncp = vp->v_cache_dd;
2839 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2840 ("lost dotdot link"));
2841 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2843 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2845 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2849 cache_free_batch(&batch);
2853 * Opportunistic check to see if there is anything to do.
2856 cache_has_entries(struct vnode *vp)
2859 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2860 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2866 cache_purge(struct vnode *vp)
2869 SDT_PROBE1(vfs, namecache, purge, done, vp);
2870 if (!cache_has_entries(vp))
2872 cache_purge_impl(vp);
2876 * Only to be used by vgone.
2879 cache_purge_vgone(struct vnode *vp)
2883 VNPASS(VN_IS_DOOMED(vp), vp);
2884 if (cache_has_entries(vp)) {
2885 cache_purge_impl(vp);
2890 * Serialize against a potential thread doing cache_purge.
2892 vlp = VP2VNODELOCK(vp);
2893 mtx_wait_unlocked(vlp);
2894 if (cache_has_entries(vp)) {
2895 cache_purge_impl(vp);
2902 * Remove all negative entries for a particular directory vnode.
2905 cache_purge_negative(struct vnode *vp)
2907 struct cache_freebatch batch;
2908 struct namecache *ncp, *nnp;
2911 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2912 if (LIST_EMPTY(&vp->v_cache_src))
2915 vlp = VP2VNODELOCK(vp);
2917 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2918 if (!(ncp->nc_flag & NCF_NEGATIVE))
2920 cache_zap_negative_locked_vnode_kl(ncp, vp);
2921 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2924 cache_free_batch(&batch);
2928 * Entry points for modifying VOP operations.
2931 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2932 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2935 ASSERT_VOP_IN_SEQC(fdvp);
2936 ASSERT_VOP_IN_SEQC(fvp);
2937 ASSERT_VOP_IN_SEQC(tdvp);
2939 ASSERT_VOP_IN_SEQC(tvp);
2944 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2945 ("%s: lingering negative entry", __func__));
2947 cache_remove_cnp(tdvp, tcnp);
2953 * Historically renaming was always purging all revelang entries,
2954 * but that's quite wasteful. In particular turns out that in many cases
2955 * the target file is immediately accessed after rename, inducing a cache
2958 * Recode this to reduce relocking and reuse the existing entry (if any)
2959 * instead of just removing it above and allocating a new one here.
2961 cache_enter(tdvp, fvp, tcnp);
2965 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2968 ASSERT_VOP_IN_SEQC(dvp);
2969 ASSERT_VOP_IN_SEQC(vp);
2975 * Validate that if an entry exists it matches.
2978 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2980 struct namecache *ncp;
2984 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2985 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2987 blp = HASH2BUCKETLOCK(hash);
2989 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2990 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2991 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2992 if (ncp->nc_vp != vp)
2993 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
2994 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3001 cache_assert_no_entries(struct vnode *vp)
3004 VNPASS(TAILQ_EMPTY(&vp->v_cache_dst), vp);
3005 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
3006 VNPASS(vp->v_cache_dd == NULL, vp);
3011 * Flush all entries referencing a particular filesystem.
3014 cache_purgevfs(struct mount *mp)
3016 struct vnode *vp, *mvp;
3017 size_t visited __sdt_used, purged __sdt_used;
3019 visited = purged = 0;
3021 * Somewhat wasteful iteration over all vnodes. Would be better to
3022 * support filtering and avoid the interlock to begin with.
3024 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3026 if (!cache_has_entries(vp)) {
3037 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3041 * Perform canonical checks and cache lookup and pass on to filesystem
3042 * through the vop_cachedlookup only if needed.
3046 vfs_cache_lookup(struct vop_lookup_args *ap)
3050 struct vnode **vpp = ap->a_vpp;
3051 struct componentname *cnp = ap->a_cnp;
3052 int flags = cnp->cn_flags;
3057 if (dvp->v_type != VDIR)
3060 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3061 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3064 error = vn_dir_check_exec(dvp, cnp);
3068 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3070 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3076 /* Implementation of the getcwd syscall. */
3078 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3084 buflen = uap->buflen;
3085 if (__predict_false(buflen < 2))
3087 if (buflen > MAXPATHLEN)
3088 buflen = MAXPATHLEN;
3090 buf = uma_zalloc(namei_zone, M_WAITOK);
3091 error = vn_getcwd(buf, &retbuf, &buflen);
3093 error = copyout(retbuf, uap->buf, buflen);
3094 uma_zfree(namei_zone, buf);
3099 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3105 pwd = pwd_get_smr();
3106 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3108 VFS_SMR_ASSERT_NOT_ENTERED();
3110 pwd = pwd_hold(curthread);
3111 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3117 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3124 * Canonicalize a path by walking it forward and back.
3127 * - Nothing guarantees the integrity of the entire chain. Consider the case
3128 * where the path "foo/bar/baz/qux" is passed, but "bar" is moved out of
3129 * "foo" into "quux" during the backwards walk. The result will be
3130 * "quux/bar/baz/qux", which could not have been obtained by an incremental
3131 * walk in userspace. Moreover, the path we return is inaccessible if the
3132 * calling thread lacks permission to traverse "quux".
3135 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3136 size_t size, int flags, enum uio_seg pathseg)
3138 struct nameidata nd;
3139 char *retbuf, *freebuf;
3144 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | WANTPARENT | AUDITVNODE1,
3145 pathseg, path, fd, &cap_fstat_rights);
3146 if ((error = namei(&nd)) != 0)
3149 if (nd.ni_vp->v_type == VREG && nd.ni_dvp->v_type != VDIR &&
3150 (nd.ni_vp->v_vflag & VV_ROOT) != 0) {
3152 * This happens if vp is a file mount. The call to
3153 * vn_fullpath_hardlink can panic if path resolution can't be
3154 * handled without the directory.
3156 * To resolve this, we find the vnode which was mounted on -
3157 * this should have a unique global path since we disallow
3158 * mounting on linked files.
3160 struct vnode *covered_vp;
3161 error = vn_lock(nd.ni_vp, LK_SHARED);
3164 covered_vp = nd.ni_vp->v_mount->mnt_vnodecovered;
3166 VOP_UNLOCK(nd.ni_vp);
3167 error = vn_fullpath(covered_vp, &retbuf, &freebuf);
3170 error = vn_fullpath_hardlink(nd.ni_vp, nd.ni_dvp, nd.ni_cnd.cn_nameptr,
3171 nd.ni_cnd.cn_namelen, &retbuf, &freebuf, &size);
3174 error = copyout(retbuf, buf, size);
3175 free(freebuf, M_TEMP);
3185 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3188 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3189 uap->flags, UIO_USERSPACE));
3193 * Retrieve the full filesystem path that correspond to a vnode from the name
3194 * cache (if available)
3197 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3204 if (__predict_false(vp == NULL))
3207 buflen = MAXPATHLEN;
3208 buf = malloc(buflen, M_TEMP, M_WAITOK);
3210 pwd = pwd_get_smr();
3211 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3212 VFS_SMR_ASSERT_NOT_ENTERED();
3214 pwd = pwd_hold(curthread);
3215 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3226 * This function is similar to vn_fullpath, but it attempts to lookup the
3227 * pathname relative to the global root mount point. This is required for the
3228 * auditing sub-system, as audited pathnames must be absolute, relative to the
3229 * global root mount point.
3232 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3238 if (__predict_false(vp == NULL))
3240 buflen = MAXPATHLEN;
3241 buf = malloc(buflen, M_TEMP, M_WAITOK);
3243 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3244 VFS_SMR_ASSERT_NOT_ENTERED();
3246 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3255 static struct namecache *
3256 vn_dd_from_dst(struct vnode *vp)
3258 struct namecache *ncp;
3260 cache_assert_vnode_locked(vp);
3261 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3262 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3269 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3272 struct namecache *ncp;
3276 vlp = VP2VNODELOCK(*vp);
3278 ncp = (*vp)->v_cache_dd;
3279 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3280 KASSERT(ncp == vn_dd_from_dst(*vp),
3281 ("%s: mismatch for dd entry (%p != %p)", __func__,
3282 ncp, vn_dd_from_dst(*vp)));
3284 ncp = vn_dd_from_dst(*vp);
3287 if (*buflen < ncp->nc_nlen) {
3290 counter_u64_add(numfullpathfail4, 1);
3292 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3296 *buflen -= ncp->nc_nlen;
3297 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3298 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3307 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3310 vn_lock(*vp, LK_SHARED | LK_RETRY);
3311 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3314 counter_u64_add(numfullpathfail2, 1);
3315 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3320 if (VN_IS_DOOMED(dvp)) {
3321 /* forced unmount */
3324 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3328 * *vp has its use count incremented still.
3335 * Resolve a directory to a pathname.
3337 * The name of the directory can always be found in the namecache or fetched
3338 * from the filesystem. There is also guaranteed to be only one parent, meaning
3339 * we can just follow vnodes up until we find the root.
3341 * The vnode must be referenced.
3344 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3345 size_t *len, size_t addend)
3347 #ifdef KDTRACE_HOOKS
3348 struct vnode *startvp = vp;
3353 bool slash_prefixed;
3355 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3356 VNPASS(vp->v_usecount > 0, vp);
3360 slash_prefixed = true;
3365 slash_prefixed = false;
3370 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3371 counter_u64_add(numfullpathcalls, 1);
3372 while (vp != rdir && vp != rootvnode) {
3374 * The vp vnode must be already fully constructed,
3375 * since it is either found in namecache or obtained
3376 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3377 * without obtaining the vnode lock.
3379 if ((vp->v_vflag & VV_ROOT) != 0) {
3380 vn_lock(vp, LK_RETRY | LK_SHARED);
3383 * With the vnode locked, check for races with
3384 * unmount, forced or not. Note that we
3385 * already verified that vp is not equal to
3386 * the root vnode, which means that
3387 * mnt_vnodecovered can be NULL only for the
3390 if (VN_IS_DOOMED(vp) ||
3391 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3392 vp1->v_mountedhere != vp->v_mount) {
3395 SDT_PROBE3(vfs, namecache, fullpath, return,
3405 if (vp->v_type != VDIR) {
3407 counter_u64_add(numfullpathfail1, 1);
3409 SDT_PROBE3(vfs, namecache, fullpath, return,
3413 error = vn_vptocnp(&vp, buf, &buflen);
3419 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3423 buf[--buflen] = '/';
3424 slash_prefixed = true;
3428 if (!slash_prefixed) {
3431 counter_u64_add(numfullpathfail4, 1);
3432 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3436 buf[--buflen] = '/';
3438 counter_u64_add(numfullpathfound, 1);
3441 *retbuf = buf + buflen;
3442 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3449 * Resolve an arbitrary vnode to a pathname.
3452 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3453 * resolve to a different path than the one used to find it
3454 * - namecache is not mandatory, meaning names are not guaranteed to be added
3455 * (in which case resolving fails)
3457 static void __inline
3458 cache_rev_failed_impl(int *reason, int line)
3463 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3466 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3467 char **retbuf, size_t *buflen, size_t addend)
3469 #ifdef KDTRACE_HOOKS
3470 struct vnode *startvp = vp;
3474 struct namecache *ncp;
3478 #ifdef KDTRACE_HOOKS
3481 seqc_t vp_seqc, tvp_seqc;
3484 VFS_SMR_ASSERT_ENTERED();
3486 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3491 orig_buflen = *buflen;
3494 MPASS(*buflen >= 2);
3496 buf[*buflen] = '\0';
3499 if (vp == rdir || vp == rootvnode) {
3507 #ifdef KDTRACE_HOOKS
3511 ncp = NULL; /* for sdt probe down below */
3512 vp_seqc = vn_seqc_read_any(vp);
3513 if (seqc_in_modify(vp_seqc)) {
3514 cache_rev_failed(&reason);
3519 #ifdef KDTRACE_HOOKS
3522 if ((vp->v_vflag & VV_ROOT) != 0) {
3523 mp = atomic_load_ptr(&vp->v_mount);
3525 cache_rev_failed(&reason);
3528 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3529 tvp_seqc = vn_seqc_read_any(tvp);
3530 if (seqc_in_modify(tvp_seqc)) {
3531 cache_rev_failed(&reason);
3534 if (!vn_seqc_consistent(vp, vp_seqc)) {
3535 cache_rev_failed(&reason);
3542 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3544 cache_rev_failed(&reason);
3547 nc_flag = atomic_load_char(&ncp->nc_flag);
3548 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3549 cache_rev_failed(&reason);
3552 if (ncp->nc_nlen >= *buflen) {
3553 cache_rev_failed(&reason);
3557 *buflen -= ncp->nc_nlen;
3558 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3562 tvp_seqc = vn_seqc_read_any(tvp);
3563 if (seqc_in_modify(tvp_seqc)) {
3564 cache_rev_failed(&reason);
3567 if (!vn_seqc_consistent(vp, vp_seqc)) {
3568 cache_rev_failed(&reason);
3572 * Acquire fence provided by vn_seqc_read_any above.
3574 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3575 cache_rev_failed(&reason);
3578 if (!cache_ncp_canuse(ncp)) {
3579 cache_rev_failed(&reason);
3584 if (vp == rdir || vp == rootvnode)
3589 *retbuf = buf + *buflen;
3590 *buflen = orig_buflen - *buflen + addend;
3591 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3595 *buflen = orig_buflen;
3596 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3602 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3605 size_t orig_buflen, addend;
3611 orig_buflen = *buflen;
3615 if (vp->v_type != VDIR) {
3617 buf[*buflen] = '\0';
3618 error = vn_vptocnp(&vp, buf, buflen);
3627 addend = orig_buflen - *buflen;
3630 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3634 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3636 * Since the namecache does not track hardlinks, the caller is expected to
3637 * first look up the target vnode with WANTPARENT flag passed to namei to get
3640 * Then we have 2 cases:
3641 * - if the found vnode is a directory, the path can be constructed just by
3642 * following names up the chain
3643 * - otherwise we populate the buffer with the saved name and start resolving
3647 vn_fullpath_hardlink(struct vnode *vp, struct vnode *dvp,
3648 const char *hrdl_name, size_t hrdl_name_length,
3649 char **retbuf, char **freebuf, size_t *buflen)
3655 __enum_uint8(vtype) type;
3659 if (*buflen > MAXPATHLEN)
3660 *buflen = MAXPATHLEN;
3662 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3667 * Check for VBAD to work around the vp_crossmp bug in lookup().
3669 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3670 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3671 * If the type is VDIR (like in this very case) we can skip looking
3672 * at ni_dvp in the first place. However, since vnodes get passed here
3673 * unlocked the target may transition to doomed state (type == VBAD)
3674 * before we get to evaluate the condition. If this happens, we will
3675 * populate part of the buffer and descend to vn_fullpath_dir with
3676 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3678 type = atomic_load_8(&vp->v_type);
3684 addend = hrdl_name_length + 2;
3685 if (*buflen < addend) {
3690 tmpbuf = buf + *buflen;
3692 memcpy(&tmpbuf[1], hrdl_name, hrdl_name_length);
3693 tmpbuf[addend - 1] = '\0';
3698 pwd = pwd_get_smr();
3699 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3701 VFS_SMR_ASSERT_NOT_ENTERED();
3703 pwd = pwd_hold(curthread);
3705 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3721 vn_dir_dd_ino(struct vnode *vp)
3723 struct namecache *ncp;
3728 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3729 vlp = VP2VNODELOCK(vp);
3731 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3732 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3735 vs = vget_prep(ddvp);
3737 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3746 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3748 struct namecache *ncp;
3752 vlp = VP2VNODELOCK(vp);
3754 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3755 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3761 l = min(ncp->nc_nlen, buflen - 1);
3762 memcpy(buf, ncp->nc_name, l);
3769 * This function updates path string to vnode's full global path
3770 * and checks the size of the new path string against the pathlen argument.
3772 * Requires a locked, referenced vnode.
3773 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3775 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3776 * because it falls back to the ".." lookup if the namecache lookup fails.
3779 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3782 struct nameidata nd;
3787 ASSERT_VOP_ELOCKED(vp, __func__);
3789 /* Construct global filesystem path from vp. */
3791 error = vn_fullpath_global(vp, &rpath, &fbuf);
3798 if (strlen(rpath) >= pathlen) {
3800 error = ENAMETOOLONG;
3805 * Re-lookup the vnode by path to detect a possible rename.
3806 * As a side effect, the vnode is relocked.
3807 * If vnode was renamed, return ENOENT.
3809 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3819 strcpy(path, rpath);
3831 * This is similar to vn_path_to_global_path but allows for regular
3832 * files which may not be present in the cache.
3834 * Requires a locked, referenced vnode.
3835 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3838 vn_path_to_global_path_hardlink(struct thread *td, struct vnode *vp,
3839 struct vnode *dvp, char *path, u_int pathlen, const char *leaf_name,
3842 struct nameidata nd;
3848 ASSERT_VOP_ELOCKED(vp, __func__);
3851 * Construct global filesystem path from dvp, vp and leaf
3856 error = vn_fullpath_hardlink(vp, dvp, leaf_name, leaf_length,
3857 &rpath, &fbuf, &len);
3864 if (strlen(rpath) >= pathlen) {
3866 error = ENAMETOOLONG;
3871 * Re-lookup the vnode by path to detect a possible rename.
3872 * As a side effect, the vnode is relocked.
3873 * If vnode was renamed, return ENOENT.
3875 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3885 strcpy(path, rpath);
3898 db_print_vpath(struct vnode *vp)
3901 while (vp != NULL) {
3902 db_printf("%p: ", vp);
3903 if (vp == rootvnode) {
3907 if (vp->v_vflag & VV_ROOT) {
3908 db_printf("<mount point>");
3909 vp = vp->v_mount->mnt_vnodecovered;
3911 struct namecache *ncp;
3915 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3918 for (i = 0; i < ncp->nc_nlen; i++)
3919 db_printf("%c", *ncn++);
3932 DB_SHOW_COMMAND(vpath, db_show_vpath)
3937 db_printf("usage: show vpath <struct vnode *>\n");
3941 vp = (struct vnode *)addr;
3947 static int cache_fast_lookup = 1;
3949 #define CACHE_FPL_FAILED -2020
3952 cache_vop_bad_vexec(struct vop_fplookup_vexec_args *v)
3954 vn_printf(v->a_vp, "no proper vop_fplookup_vexec\n");
3955 panic("no proper vop_fplookup_vexec");
3959 cache_vop_bad_symlink(struct vop_fplookup_symlink_args *v)
3961 vn_printf(v->a_vp, "no proper vop_fplookup_symlink\n");
3962 panic("no proper vop_fplookup_symlink");
3966 cache_vop_vector_register(struct vop_vector *v)
3971 if (v->vop_fplookup_vexec != NULL) {
3974 if (v->vop_fplookup_symlink != NULL) {
3983 v->vop_fplookup_vexec = cache_vop_bad_vexec;
3984 v->vop_fplookup_symlink = cache_vop_bad_symlink;
3988 printf("%s: invalid vop vector %p -- either all or none fplookup vops "
3989 "need to be provided", __func__, v);
3990 if (v->vop_fplookup_vexec == NULL) {
3991 printf("%s: missing vop_fplookup_vexec\n", __func__);
3993 if (v->vop_fplookup_symlink == NULL) {
3994 printf("%s: missing vop_fplookup_symlink\n", __func__);
3996 panic("bad vop vector %p", v);
4001 cache_validate_vop_vector(struct mount *mp, struct vop_vector *vops)
4006 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4009 if (vops->vop_fplookup_vexec == NULL ||
4010 vops->vop_fplookup_vexec == cache_vop_bad_vexec)
4011 panic("bad vop_fplookup_vexec on vector %p for filesystem %s",
4012 vops, mp->mnt_vfc->vfc_name);
4014 if (vops->vop_fplookup_symlink == NULL ||
4015 vops->vop_fplookup_symlink == cache_vop_bad_symlink)
4016 panic("bad vop_fplookup_symlink on vector %p for filesystem %s",
4017 vops, mp->mnt_vfc->vfc_name);
4022 cache_fast_lookup_enabled_recalc(void)
4028 mac_on = mac_vnode_check_lookup_enabled();
4029 mac_on |= mac_vnode_check_readlink_enabled();
4034 lookup_flag = atomic_load_int(&cache_fast_lookup);
4035 if (lookup_flag && !mac_on) {
4036 atomic_store_char(&cache_fast_lookup_enabled, true);
4038 atomic_store_char(&cache_fast_lookup_enabled, false);
4043 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
4047 old = atomic_load_int(&cache_fast_lookup);
4048 error = sysctl_handle_int(oidp, arg1, arg2, req);
4049 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
4050 cache_fast_lookup_enabled_recalc();
4053 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
4054 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
4057 * Components of nameidata (or objects it can point to) which may
4058 * need restoring in case fast path lookup fails.
4060 struct nameidata_outer {
4065 struct nameidata_saved {
4073 struct cache_fpl_debug {
4079 struct nameidata *ndp;
4080 struct componentname *cnp;
4087 struct nameidata_saved snd;
4088 struct nameidata_outer snd_outer;
4090 enum cache_fpl_status status:8;
4095 struct cache_fpl_debug debug;
4099 static bool cache_fplookup_mp_supported(struct mount *mp);
4100 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
4101 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
4102 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
4103 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
4104 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
4105 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
4106 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
4107 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
4108 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
4111 cache_fpl_cleanup_cnp(struct componentname *cnp)
4114 uma_zfree(namei_zone, cnp->cn_pnbuf);
4115 cnp->cn_pnbuf = NULL;
4116 cnp->cn_nameptr = NULL;
4119 static struct vnode *
4120 cache_fpl_handle_root(struct cache_fpl *fpl)
4122 struct nameidata *ndp;
4123 struct componentname *cnp;
4128 MPASS(*(cnp->cn_nameptr) == '/');
4130 cache_fpl_pathlen_dec(fpl);
4132 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4135 cache_fpl_pathlen_dec(fpl);
4136 } while (*(cnp->cn_nameptr) == '/');
4139 return (ndp->ni_rootdir);
4143 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
4146 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
4147 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
4151 cache_fpl_checkpoint(struct cache_fpl *fpl)
4155 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
4156 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4161 cache_fpl_restore_partial(struct cache_fpl *fpl)
4164 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4166 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4171 cache_fpl_restore_abort(struct cache_fpl *fpl)
4174 cache_fpl_restore_partial(fpl);
4176 * It is 0 on entry by API contract.
4178 fpl->ndp->ni_resflags = 0;
4179 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4180 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4184 #define cache_fpl_smr_assert_entered(fpl) ({ \
4185 struct cache_fpl *_fpl = (fpl); \
4186 MPASS(_fpl->in_smr == true); \
4187 VFS_SMR_ASSERT_ENTERED(); \
4189 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4190 struct cache_fpl *_fpl = (fpl); \
4191 MPASS(_fpl->in_smr == false); \
4192 VFS_SMR_ASSERT_NOT_ENTERED(); \
4195 cache_fpl_assert_status(struct cache_fpl *fpl)
4198 switch (fpl->status) {
4199 case CACHE_FPL_STATUS_UNSET:
4200 __assert_unreachable();
4202 case CACHE_FPL_STATUS_DESTROYED:
4203 case CACHE_FPL_STATUS_ABORTED:
4204 case CACHE_FPL_STATUS_PARTIAL:
4205 case CACHE_FPL_STATUS_HANDLED:
4210 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4211 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4212 #define cache_fpl_assert_status(fpl) do { } while (0)
4215 #define cache_fpl_smr_enter_initial(fpl) ({ \
4216 struct cache_fpl *_fpl = (fpl); \
4218 _fpl->in_smr = true; \
4221 #define cache_fpl_smr_enter(fpl) ({ \
4222 struct cache_fpl *_fpl = (fpl); \
4223 MPASS(_fpl->in_smr == false); \
4225 _fpl->in_smr = true; \
4228 #define cache_fpl_smr_exit(fpl) ({ \
4229 struct cache_fpl *_fpl = (fpl); \
4230 MPASS(_fpl->in_smr == true); \
4232 _fpl->in_smr = false; \
4236 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4239 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4240 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4241 ("%s: converting to abort from %d at %d, set at %d\n",
4242 __func__, fpl->status, line, fpl->line));
4244 cache_fpl_smr_assert_not_entered(fpl);
4245 fpl->status = CACHE_FPL_STATUS_ABORTED;
4247 return (CACHE_FPL_FAILED);
4250 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4252 static int __noinline
4253 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4255 struct nameidata *ndp;
4256 struct componentname *cnp;
4261 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4262 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4263 ("%s: converting to abort from %d at %d, set at %d\n",
4264 __func__, fpl->status, line, fpl->line));
4266 fpl->status = CACHE_FPL_STATUS_ABORTED;
4269 cache_fpl_smr_exit(fpl);
4270 cache_fpl_restore_abort(fpl);
4272 * Resolving symlinks overwrites data passed by the caller.
4275 if (ndp->ni_loopcnt > 0) {
4276 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4277 cache_fpl_cleanup_cnp(cnp);
4279 return (CACHE_FPL_FAILED);
4282 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4284 static int __noinline
4285 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4288 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4289 ("%s: setting to partial at %d, but already set to %d at %d\n",
4290 __func__, line, fpl->status, fpl->line));
4291 cache_fpl_smr_assert_entered(fpl);
4292 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4294 return (cache_fplookup_partial_setup(fpl));
4297 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4300 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4303 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4304 ("%s: setting to handled at %d, but already set to %d at %d\n",
4305 __func__, line, fpl->status, fpl->line));
4306 cache_fpl_smr_assert_not_entered(fpl);
4307 fpl->status = CACHE_FPL_STATUS_HANDLED;
4312 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4315 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4318 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4319 ("%s: setting to handled at %d, but already set to %d at %d\n",
4320 __func__, line, fpl->status, fpl->line));
4322 MPASS(error != CACHE_FPL_FAILED);
4323 cache_fpl_smr_assert_not_entered(fpl);
4324 fpl->status = CACHE_FPL_STATUS_HANDLED;
4331 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4334 cache_fpl_terminated(struct cache_fpl *fpl)
4337 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4340 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4341 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4342 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | ISRESTARTED | WILLBEDIR | \
4343 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | OPENREAD | \
4344 OPENWRITE | WANTIOCTLCAPS)
4346 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4347 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4349 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4350 "supported and internal flags overlap");
4353 cache_fpl_islastcn(struct nameidata *ndp)
4356 return (*ndp->ni_next == 0);
4360 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4363 MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4364 return (*(fpl->nulchar - 1) == '/');
4368 cache_fpl_isdotdot(struct componentname *cnp)
4371 if (cnp->cn_namelen == 2 &&
4372 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4378 cache_can_fplookup(struct cache_fpl *fpl)
4380 struct nameidata *ndp;
4381 struct componentname *cnp;
4388 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4389 cache_fpl_aborted_early(fpl);
4392 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4393 cache_fpl_aborted_early(fpl);
4396 if (IN_CAPABILITY_MODE(td)) {
4397 cache_fpl_aborted_early(fpl);
4400 if (AUDITING_TD(td)) {
4401 cache_fpl_aborted_early(fpl);
4404 if (ndp->ni_startdir != NULL) {
4405 cache_fpl_aborted_early(fpl);
4411 static int __noinline
4412 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4414 struct nameidata *ndp;
4415 struct componentname *cnp;
4422 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4423 if (__predict_false(error != 0)) {
4424 return (cache_fpl_aborted(fpl));
4426 fpl->fsearch = fsearch;
4427 if ((*vpp)->v_type != VDIR) {
4428 if (!((cnp->cn_flags & EMPTYPATH) != 0 && cnp->cn_pnbuf[0] == '\0')) {
4429 cache_fpl_smr_exit(fpl);
4430 return (cache_fpl_handled_error(fpl, ENOTDIR));
4436 static int __noinline
4437 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4440 struct componentname *cnp;
4446 cache_fpl_smr_exit(fpl);
4447 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4448 return (cache_fpl_handled_error(fpl, ENOENT));
4450 return (cache_fpl_aborted(fpl));
4454 * The target vnode is not supported, prepare for the slow path to take over.
4456 static int __noinline
4457 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4459 struct nameidata *ndp;
4460 struct componentname *cnp;
4470 dvp_seqc = fpl->dvp_seqc;
4472 if (!pwd_hold_smr(pwd)) {
4473 return (cache_fpl_aborted(fpl));
4477 * Note that seqc is checked before the vnode is locked, so by
4478 * the time regular lookup gets to it it may have moved.
4480 * Ultimately this does not affect correctness, any lookup errors
4481 * are userspace racing with itself. It is guaranteed that any
4482 * path which ultimately gets found could also have been found
4483 * by regular lookup going all the way in absence of concurrent
4486 dvs = vget_prep_smr(dvp);
4487 cache_fpl_smr_exit(fpl);
4488 if (__predict_false(dvs == VGET_NONE)) {
4490 return (cache_fpl_aborted(fpl));
4493 vget_finish_ref(dvp, dvs);
4494 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4497 return (cache_fpl_aborted(fpl));
4500 cache_fpl_restore_partial(fpl);
4502 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4503 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4504 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4508 ndp->ni_startdir = dvp;
4509 cnp->cn_flags |= MAKEENTRY;
4510 if (cache_fpl_islastcn(ndp))
4511 cnp->cn_flags |= ISLASTCN;
4512 if (cache_fpl_isdotdot(cnp))
4513 cnp->cn_flags |= ISDOTDOT;
4516 * Skip potential extra slashes parsing did not take care of.
4517 * cache_fplookup_skip_slashes explains the mechanism.
4519 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4522 cache_fpl_pathlen_dec(fpl);
4523 } while (*(cnp->cn_nameptr) == '/');
4526 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4528 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4529 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4530 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4531 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4538 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4540 struct componentname *cnp;
4547 tvp_seqc = fpl->tvp_seqc;
4549 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4550 lkflags = LK_SHARED;
4551 if ((cnp->cn_flags & LOCKSHARED) == 0)
4552 lkflags = LK_EXCLUSIVE;
4553 error = vget_finish(tvp, lkflags, tvs);
4554 if (__predict_false(error != 0)) {
4555 return (cache_fpl_aborted(fpl));
4558 vget_finish_ref(tvp, tvs);
4561 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4562 if ((cnp->cn_flags & LOCKLEAF) != 0)
4566 return (cache_fpl_aborted(fpl));
4569 return (cache_fpl_handled(fpl));
4573 * They want to possibly modify the state of the namecache.
4575 static int __noinline
4576 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4578 struct nameidata *ndp __diagused;
4579 struct componentname *cnp;
4581 struct vnode *dvp, *tvp;
4590 dvp_seqc = fpl->dvp_seqc;
4592 MPASS(*(cnp->cn_nameptr) != '/');
4593 MPASS(cache_fpl_islastcn(ndp));
4594 if ((cnp->cn_flags & LOCKPARENT) == 0)
4595 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4596 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4597 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4598 cnp->cn_nameiop == RENAME);
4599 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4600 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4602 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4603 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4607 * Regular lookup nulifies the slash, which we don't do here.
4608 * Don't take chances with filesystem routines seeing it for
4611 if (cache_fpl_istrailingslash(fpl)) {
4612 return (cache_fpl_partial(fpl));
4615 mp = atomic_load_ptr(&dvp->v_mount);
4616 if (__predict_false(mp == NULL)) {
4617 return (cache_fpl_aborted(fpl));
4620 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4621 cache_fpl_smr_exit(fpl);
4623 * Original code keeps not checking for CREATE which
4624 * might be a bug. For now let the old lookup decide.
4626 if (cnp->cn_nameiop == CREATE) {
4627 return (cache_fpl_aborted(fpl));
4629 return (cache_fpl_handled_error(fpl, EROFS));
4632 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4633 cache_fpl_smr_exit(fpl);
4634 return (cache_fpl_handled_error(fpl, EEXIST));
4638 * Secure access to dvp; check cache_fplookup_partial_setup for
4641 * XXX At least UFS requires its lookup routine to be called for
4642 * the last path component, which leads to some level of complication
4644 * - the target routine always locks the target vnode, but our caller
4645 * may not need it locked
4646 * - some of the VOP machinery asserts that the parent is locked, which
4647 * once more may be not required
4649 * TODO: add a flag for filesystems which don't need this.
4651 dvs = vget_prep_smr(dvp);
4652 cache_fpl_smr_exit(fpl);
4653 if (__predict_false(dvs == VGET_NONE)) {
4654 return (cache_fpl_aborted(fpl));
4657 vget_finish_ref(dvp, dvs);
4658 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4660 return (cache_fpl_aborted(fpl));
4663 error = vn_lock(dvp, LK_EXCLUSIVE);
4664 if (__predict_false(error != 0)) {
4666 return (cache_fpl_aborted(fpl));
4670 cnp->cn_flags |= ISLASTCN;
4672 cnp->cn_flags |= MAKEENTRY;
4673 if (cache_fpl_isdotdot(cnp))
4674 cnp->cn_flags |= ISDOTDOT;
4675 cnp->cn_lkflags = LK_EXCLUSIVE;
4676 error = VOP_LOOKUP(dvp, &tvp, cnp);
4684 return (cache_fpl_handled_error(fpl, error));
4687 return (cache_fpl_aborted(fpl));
4693 MPASS(error == EJUSTRETURN);
4694 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4697 return (cache_fpl_handled(fpl));
4701 * There are very hairy corner cases concerning various flag combinations
4702 * and locking state. In particular here we only hold one lock instead of
4705 * Skip the complexity as it is of no significance for normal workloads.
4707 if (__predict_false(tvp == dvp)) {
4710 return (cache_fpl_aborted(fpl));
4714 * If they want the symlink itself we are fine, but if they want to
4715 * follow it regular lookup has to be engaged.
4717 if (tvp->v_type == VLNK) {
4718 if ((cnp->cn_flags & FOLLOW) != 0) {
4721 return (cache_fpl_aborted(fpl));
4726 * Since we expect this to be the terminal vnode it should almost never
4729 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4732 return (cache_fpl_aborted(fpl));
4735 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4738 return (cache_fpl_handled_error(fpl, EEXIST));
4741 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4745 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4749 return (cache_fpl_handled(fpl));
4752 static int __noinline
4753 cache_fplookup_modifying(struct cache_fpl *fpl)
4755 struct nameidata *ndp;
4759 if (!cache_fpl_islastcn(ndp)) {
4760 return (cache_fpl_partial(fpl));
4762 return (cache_fplookup_final_modifying(fpl));
4765 static int __noinline
4766 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4768 struct componentname *cnp;
4769 enum vgetstate dvs, tvs;
4770 struct vnode *dvp, *tvp;
4776 dvp_seqc = fpl->dvp_seqc;
4779 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4782 * This is less efficient than it can be for simplicity.
4784 dvs = vget_prep_smr(dvp);
4785 if (__predict_false(dvs == VGET_NONE)) {
4786 return (cache_fpl_aborted(fpl));
4788 tvs = vget_prep_smr(tvp);
4789 if (__predict_false(tvs == VGET_NONE)) {
4790 cache_fpl_smr_exit(fpl);
4791 vget_abort(dvp, dvs);
4792 return (cache_fpl_aborted(fpl));
4795 cache_fpl_smr_exit(fpl);
4797 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4798 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4799 if (__predict_false(error != 0)) {
4800 vget_abort(tvp, tvs);
4801 return (cache_fpl_aborted(fpl));
4804 vget_finish_ref(dvp, dvs);
4807 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4808 vget_abort(tvp, tvs);
4809 if ((cnp->cn_flags & LOCKPARENT) != 0)
4813 return (cache_fpl_aborted(fpl));
4816 error = cache_fplookup_final_child(fpl, tvs);
4817 if (__predict_false(error != 0)) {
4818 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4819 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4820 if ((cnp->cn_flags & LOCKPARENT) != 0)
4827 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4832 cache_fplookup_final(struct cache_fpl *fpl)
4834 struct componentname *cnp;
4836 struct vnode *dvp, *tvp;
4841 dvp_seqc = fpl->dvp_seqc;
4844 MPASS(*(cnp->cn_nameptr) != '/');
4846 if (cnp->cn_nameiop != LOOKUP) {
4847 return (cache_fplookup_final_modifying(fpl));
4850 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4851 return (cache_fplookup_final_withparent(fpl));
4853 tvs = vget_prep_smr(tvp);
4854 if (__predict_false(tvs == VGET_NONE)) {
4855 return (cache_fpl_partial(fpl));
4858 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4859 cache_fpl_smr_exit(fpl);
4860 vget_abort(tvp, tvs);
4861 return (cache_fpl_aborted(fpl));
4864 cache_fpl_smr_exit(fpl);
4865 return (cache_fplookup_final_child(fpl, tvs));
4869 * Comment from locked lookup:
4870 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4871 * directory, e.g. like "/." or ".".
4873 static int __noinline
4874 cache_fplookup_degenerate(struct cache_fpl *fpl)
4876 struct componentname *cnp;
4884 fpl->tvp = fpl->dvp;
4885 fpl->tvp_seqc = fpl->dvp_seqc;
4891 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4893 ("%s: encountered non-slash; string [%s]\n", __func__,
4898 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4899 cache_fpl_smr_exit(fpl);
4900 return (cache_fpl_handled_error(fpl, EISDIR));
4903 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4904 return (cache_fplookup_final_withparent(fpl));
4907 dvs = vget_prep_smr(dvp);
4908 cache_fpl_smr_exit(fpl);
4909 if (__predict_false(dvs == VGET_NONE)) {
4910 return (cache_fpl_aborted(fpl));
4913 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4914 lkflags = LK_SHARED;
4915 if ((cnp->cn_flags & LOCKSHARED) == 0)
4916 lkflags = LK_EXCLUSIVE;
4917 error = vget_finish(dvp, lkflags, dvs);
4918 if (__predict_false(error != 0)) {
4919 return (cache_fpl_aborted(fpl));
4922 vget_finish_ref(dvp, dvs);
4924 return (cache_fpl_handled(fpl));
4927 static int __noinline
4928 cache_fplookup_emptypath(struct cache_fpl *fpl)
4930 struct nameidata *ndp;
4931 struct componentname *cnp;
4936 fpl->tvp = fpl->dvp;
4937 fpl->tvp_seqc = fpl->dvp_seqc;
4943 MPASS(*cnp->cn_pnbuf == '\0');
4945 if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
4946 cache_fpl_smr_exit(fpl);
4947 return (cache_fpl_handled_error(fpl, ENOENT));
4950 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
4952 tvs = vget_prep_smr(tvp);
4953 cache_fpl_smr_exit(fpl);
4954 if (__predict_false(tvs == VGET_NONE)) {
4955 return (cache_fpl_aborted(fpl));
4958 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4959 lkflags = LK_SHARED;
4960 if ((cnp->cn_flags & LOCKSHARED) == 0)
4961 lkflags = LK_EXCLUSIVE;
4962 error = vget_finish(tvp, lkflags, tvs);
4963 if (__predict_false(error != 0)) {
4964 return (cache_fpl_aborted(fpl));
4967 vget_finish_ref(tvp, tvs);
4970 ndp->ni_resflags |= NIRES_EMPTYPATH;
4971 return (cache_fpl_handled(fpl));
4974 static int __noinline
4975 cache_fplookup_noentry(struct cache_fpl *fpl)
4977 struct nameidata *ndp;
4978 struct componentname *cnp;
4980 struct vnode *dvp, *tvp;
4987 dvp_seqc = fpl->dvp_seqc;
4989 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4990 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4991 if (cnp->cn_nameiop == LOOKUP)
4992 MPASS((cnp->cn_flags & NOCACHE) == 0);
4993 MPASS(!cache_fpl_isdotdot(cnp));
4996 * Hack: delayed name len checking.
4998 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4999 cache_fpl_smr_exit(fpl);
5000 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5003 if (cnp->cn_nameptr[0] == '/') {
5004 return (cache_fplookup_skip_slashes(fpl));
5007 if (cnp->cn_pnbuf[0] == '\0') {
5008 return (cache_fplookup_emptypath(fpl));
5011 if (cnp->cn_nameptr[0] == '\0') {
5012 if (fpl->tvp == NULL) {
5013 return (cache_fplookup_degenerate(fpl));
5015 return (cache_fplookup_trailingslash(fpl));
5018 if (cnp->cn_nameiop != LOOKUP) {
5020 return (cache_fplookup_modifying(fpl));
5024 * Only try to fill in the component if it is the last one,
5025 * otherwise not only there may be several to handle but the
5026 * walk may be complicated.
5028 if (!cache_fpl_islastcn(ndp)) {
5029 return (cache_fpl_partial(fpl));
5033 * Regular lookup nulifies the slash, which we don't do here.
5034 * Don't take chances with filesystem routines seeing it for
5037 if (cache_fpl_istrailingslash(fpl)) {
5038 return (cache_fpl_partial(fpl));
5042 * Secure access to dvp; check cache_fplookup_partial_setup for
5045 dvs = vget_prep_smr(dvp);
5046 cache_fpl_smr_exit(fpl);
5047 if (__predict_false(dvs == VGET_NONE)) {
5048 return (cache_fpl_aborted(fpl));
5051 vget_finish_ref(dvp, dvs);
5052 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5054 return (cache_fpl_aborted(fpl));
5057 error = vn_lock(dvp, LK_SHARED);
5058 if (__predict_false(error != 0)) {
5060 return (cache_fpl_aborted(fpl));
5065 * TODO: provide variants which don't require locking either vnode.
5067 cnp->cn_flags |= ISLASTCN | MAKEENTRY;
5068 cnp->cn_lkflags = LK_SHARED;
5069 if ((cnp->cn_flags & LOCKSHARED) == 0) {
5070 cnp->cn_lkflags = LK_EXCLUSIVE;
5072 error = VOP_LOOKUP(dvp, &tvp, cnp);
5080 return (cache_fpl_handled_error(fpl, error));
5083 return (cache_fpl_aborted(fpl));
5089 MPASS(error == EJUSTRETURN);
5090 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5092 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5095 return (cache_fpl_handled(fpl));
5098 if (tvp->v_type == VLNK) {
5099 if ((cnp->cn_flags & FOLLOW) != 0) {
5102 return (cache_fpl_aborted(fpl));
5106 if (__predict_false(cache_fplookup_is_mp(fpl))) {
5109 return (cache_fpl_aborted(fpl));
5112 if ((cnp->cn_flags & LOCKLEAF) == 0) {
5116 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5118 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5121 return (cache_fpl_handled(fpl));
5124 static int __noinline
5125 cache_fplookup_dot(struct cache_fpl *fpl)
5129 MPASS(!seqc_in_modify(fpl->dvp_seqc));
5131 if (__predict_false(fpl->dvp->v_type != VDIR)) {
5132 cache_fpl_smr_exit(fpl);
5133 return (cache_fpl_handled_error(fpl, ENOTDIR));
5137 * Just re-assign the value. seqc will be checked later for the first
5138 * non-dot path component in line and/or before deciding to return the
5141 fpl->tvp = fpl->dvp;
5142 fpl->tvp_seqc = fpl->dvp_seqc;
5144 counter_u64_add(dothits, 1);
5145 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
5148 if (cache_fplookup_is_mp(fpl)) {
5149 error = cache_fplookup_cross_mount(fpl);
5154 static int __noinline
5155 cache_fplookup_dotdot(struct cache_fpl *fpl)
5157 struct nameidata *ndp;
5158 struct componentname *cnp;
5159 struct namecache *ncp;
5168 MPASS(cache_fpl_isdotdot(cnp));
5171 * XXX this is racy the same way regular lookup is
5173 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5175 if (dvp == pr->pr_root)
5178 if (dvp == ndp->ni_rootdir ||
5179 dvp == ndp->ni_topdir ||
5183 fpl->tvp_seqc = vn_seqc_read_any(dvp);
5184 if (seqc_in_modify(fpl->tvp_seqc)) {
5185 return (cache_fpl_aborted(fpl));
5190 if ((dvp->v_vflag & VV_ROOT) != 0) {
5193 * The opposite of climb mount is needed here.
5195 return (cache_fpl_partial(fpl));
5198 if (__predict_false(dvp->v_type != VDIR)) {
5199 cache_fpl_smr_exit(fpl);
5200 return (cache_fpl_handled_error(fpl, ENOTDIR));
5203 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5205 return (cache_fpl_aborted(fpl));
5208 nc_flag = atomic_load_char(&ncp->nc_flag);
5209 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5210 if ((nc_flag & NCF_NEGATIVE) != 0)
5211 return (cache_fpl_aborted(fpl));
5212 fpl->tvp = ncp->nc_vp;
5214 fpl->tvp = ncp->nc_dvp;
5217 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5218 if (seqc_in_modify(fpl->tvp_seqc)) {
5219 return (cache_fpl_partial(fpl));
5223 * Acquire fence provided by vn_seqc_read_any above.
5225 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5226 return (cache_fpl_aborted(fpl));
5229 if (!cache_ncp_canuse(ncp)) {
5230 return (cache_fpl_aborted(fpl));
5233 counter_u64_add(dotdothits, 1);
5237 static int __noinline
5238 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5240 u_char nc_flag __diagused;
5244 nc_flag = atomic_load_char(&ncp->nc_flag);
5245 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5248 * If they want to create an entry we need to replace this one.
5250 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5252 return (cache_fplookup_modifying(fpl));
5254 neg_promote = cache_neg_hit_prep(ncp);
5255 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5256 cache_neg_hit_abort(ncp);
5257 return (cache_fpl_partial(fpl));
5260 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5262 cache_neg_hit_finish(ncp);
5263 cache_fpl_smr_exit(fpl);
5264 return (cache_fpl_handled_error(fpl, ENOENT));
5268 * Resolve a symlink. Called by filesystem-specific routines.
5271 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5274 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5276 struct nameidata *ndp;
5277 struct componentname *cnp;
5283 if (__predict_false(len == 0)) {
5287 if (__predict_false(len > MAXPATHLEN - 2)) {
5288 if (cache_fpl_istrailingslash(fpl)) {
5293 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5295 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5296 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5297 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5298 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5302 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5303 return (ENAMETOOLONG);
5306 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5311 if (ndp->ni_pathlen > 1) {
5312 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5314 if (cache_fpl_istrailingslash(fpl)) {
5316 cnp->cn_pnbuf[len] = '/';
5317 cnp->cn_pnbuf[len + 1] = '\0';
5319 cnp->cn_pnbuf[len] = '\0';
5322 bcopy(string, cnp->cn_pnbuf, len);
5324 ndp->ni_pathlen += adjust;
5325 cache_fpl_pathlen_add(fpl, adjust);
5326 cnp->cn_nameptr = cnp->cn_pnbuf;
5327 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5332 static int __noinline
5333 cache_fplookup_symlink(struct cache_fpl *fpl)
5336 struct nameidata *ndp;
5337 struct componentname *cnp;
5338 struct vnode *dvp, *tvp;
5346 if (cache_fpl_islastcn(ndp)) {
5347 if ((cnp->cn_flags & FOLLOW) == 0) {
5348 return (cache_fplookup_final(fpl));
5352 mp = atomic_load_ptr(&dvp->v_mount);
5353 if (__predict_false(mp == NULL)) {
5354 return (cache_fpl_aborted(fpl));
5358 * Note this check races against setting the flag just like regular
5361 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5362 cache_fpl_smr_exit(fpl);
5363 return (cache_fpl_handled_error(fpl, EACCES));
5366 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5367 if (__predict_false(error != 0)) {
5370 return (cache_fpl_partial(fpl));
5374 cache_fpl_smr_exit(fpl);
5375 return (cache_fpl_handled_error(fpl, error));
5377 return (cache_fpl_aborted(fpl));
5381 if (*(cnp->cn_nameptr) == '/') {
5382 fpl->dvp = cache_fpl_handle_root(fpl);
5383 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5384 if (seqc_in_modify(fpl->dvp_seqc)) {
5385 return (cache_fpl_aborted(fpl));
5388 * The main loop assumes that ->dvp points to a vnode belonging
5389 * to a filesystem which can do lockless lookup, but the absolute
5390 * symlink can be wandering off to one which does not.
5392 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5393 if (__predict_false(mp == NULL)) {
5394 return (cache_fpl_aborted(fpl));
5396 if (!cache_fplookup_mp_supported(mp)) {
5397 cache_fpl_checkpoint(fpl);
5398 return (cache_fpl_partial(fpl));
5405 cache_fplookup_next(struct cache_fpl *fpl)
5407 struct componentname *cnp;
5408 struct namecache *ncp;
5409 struct vnode *dvp, *tvp;
5418 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5419 if (cnp->cn_namelen == 1) {
5420 return (cache_fplookup_dot(fpl));
5422 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5423 return (cache_fplookup_dotdot(fpl));
5427 MPASS(!cache_fpl_isdotdot(cnp));
5429 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5430 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5431 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5435 if (__predict_false(ncp == NULL)) {
5436 return (cache_fplookup_noentry(fpl));
5439 tvp = atomic_load_ptr(&ncp->nc_vp);
5440 nc_flag = atomic_load_char(&ncp->nc_flag);
5441 if ((nc_flag & NCF_NEGATIVE) != 0) {
5442 return (cache_fplookup_neg(fpl, ncp, hash));
5445 if (!cache_ncp_canuse(ncp)) {
5446 return (cache_fpl_partial(fpl));
5450 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5451 if (seqc_in_modify(fpl->tvp_seqc)) {
5452 return (cache_fpl_partial(fpl));
5455 counter_u64_add(numposhits, 1);
5456 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5459 if (cache_fplookup_is_mp(fpl)) {
5460 error = cache_fplookup_cross_mount(fpl);
5466 cache_fplookup_mp_supported(struct mount *mp)
5470 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5476 * Walk up the mount stack (if any).
5478 * Correctness is provided in the following ways:
5479 * - all vnodes are protected from freeing with SMR
5480 * - struct mount objects are type stable making them always safe to access
5481 * - stability of the particular mount is provided by busying it
5482 * - relationship between the vnode which is mounted on and the mount is
5483 * verified with the vnode sequence counter after busying
5484 * - association between root vnode of the mount and the mount is protected
5487 * From that point on we can read the sequence counter of the root vnode
5488 * and get the next mount on the stack (if any) using the same protection.
5490 * By the end of successful walk we are guaranteed the reached state was
5491 * indeed present at least at some point which matches the regular lookup.
5493 static int __noinline
5494 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5496 struct mount *mp, *prev_mp;
5497 struct mount_pcpu *mpcpu, *prev_mpcpu;
5502 vp_seqc = fpl->tvp_seqc;
5504 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5505 mp = atomic_load_ptr(&vp->v_mountedhere);
5506 if (__predict_false(mp == NULL)) {
5512 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5513 if (prev_mp != NULL)
5514 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5515 return (cache_fpl_partial(fpl));
5517 if (prev_mp != NULL)
5518 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5519 if (!vn_seqc_consistent(vp, vp_seqc)) {
5520 vfs_op_thread_exit_crit(mp, mpcpu);
5521 return (cache_fpl_partial(fpl));
5523 if (!cache_fplookup_mp_supported(mp)) {
5524 vfs_op_thread_exit_crit(mp, mpcpu);
5525 return (cache_fpl_partial(fpl));
5527 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5529 vfs_op_thread_exit_crit(mp, mpcpu);
5530 return (cache_fpl_partial(fpl));
5532 vp_seqc = vn_seqc_read_any(vp);
5533 if (seqc_in_modify(vp_seqc)) {
5534 vfs_op_thread_exit_crit(mp, mpcpu);
5535 return (cache_fpl_partial(fpl));
5539 mp = atomic_load_ptr(&vp->v_mountedhere);
5544 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5546 fpl->tvp_seqc = vp_seqc;
5550 static int __noinline
5551 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5554 struct mount_pcpu *mpcpu;
5559 vp_seqc = fpl->tvp_seqc;
5561 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5562 mp = atomic_load_ptr(&vp->v_mountedhere);
5563 if (__predict_false(mp == NULL)) {
5567 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5568 return (cache_fpl_partial(fpl));
5570 if (!vn_seqc_consistent(vp, vp_seqc)) {
5571 vfs_op_thread_exit_crit(mp, mpcpu);
5572 return (cache_fpl_partial(fpl));
5574 if (!cache_fplookup_mp_supported(mp)) {
5575 vfs_op_thread_exit_crit(mp, mpcpu);
5576 return (cache_fpl_partial(fpl));
5578 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5579 if (__predict_false(vp == NULL)) {
5580 vfs_op_thread_exit_crit(mp, mpcpu);
5581 return (cache_fpl_partial(fpl));
5583 vp_seqc = vn_seqc_read_any(vp);
5584 vfs_op_thread_exit_crit(mp, mpcpu);
5585 if (seqc_in_modify(vp_seqc)) {
5586 return (cache_fpl_partial(fpl));
5588 mp = atomic_load_ptr(&vp->v_mountedhere);
5589 if (__predict_false(mp != NULL)) {
5591 * There are possibly more mount points on top.
5592 * Normally this does not happen so for simplicity just start
5595 return (cache_fplookup_climb_mount(fpl));
5599 fpl->tvp_seqc = vp_seqc;
5604 * Check if a vnode is mounted on.
5607 cache_fplookup_is_mp(struct cache_fpl *fpl)
5612 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5618 * The code was originally copy-pasted from regular lookup and despite
5619 * clean ups leaves performance on the table. Any modifications here
5620 * must take into account that in case off fallback the resulting
5621 * nameidata state has to be compatible with the original.
5625 * Debug ni_pathlen tracking.
5629 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5632 fpl->debug.ni_pathlen += n;
5633 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5634 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5638 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5641 fpl->debug.ni_pathlen -= n;
5642 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5643 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5647 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5650 cache_fpl_pathlen_add(fpl, 1);
5654 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5657 cache_fpl_pathlen_sub(fpl, 1);
5661 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5666 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5671 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5676 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5682 cache_fplookup_parse(struct cache_fpl *fpl)
5684 struct nameidata *ndp;
5685 struct componentname *cnp;
5695 * Find the end of this path component, it is either / or nul.
5697 * Store / as a temporary sentinel so that we only have one character
5698 * to test for. Pathnames tend to be short so this should not be
5699 * resulting in cache misses.
5701 * TODO: fix this to be word-sized.
5703 MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5704 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5705 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5706 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5707 fpl->nulchar, cnp->cn_pnbuf));
5708 KASSERT(*fpl->nulchar == '\0',
5709 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5711 hash = cache_get_hash_iter_start(dvp);
5712 *fpl->nulchar = '/';
5713 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5714 KASSERT(*cp != '\0',
5715 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5717 hash = cache_get_hash_iter(*cp, hash);
5720 *fpl->nulchar = '\0';
5721 fpl->hash = cache_get_hash_iter_finish(hash);
5723 cnp->cn_namelen = cp - cnp->cn_nameptr;
5724 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5728 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5729 * we are going to fail this lookup with ENAMETOOLONG (see below).
5731 if (cnp->cn_namelen <= NAME_MAX) {
5732 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5733 panic("%s: mismatched hash for [%s] len %ld", __func__,
5734 cnp->cn_nameptr, cnp->cn_namelen);
5740 * Hack: we have to check if the found path component's length exceeds
5741 * NAME_MAX. However, the condition is very rarely true and check can
5742 * be elided in the common case -- if an entry was found in the cache,
5743 * then it could not have been too long to begin with.
5749 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5751 struct nameidata *ndp;
5752 struct componentname *cnp;
5757 cnp->cn_nameptr = ndp->ni_next;
5758 KASSERT(*(cnp->cn_nameptr) == '/',
5759 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5760 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5762 cache_fpl_pathlen_dec(fpl);
5766 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5768 * Lockless lookup tries to elide checking for spurious slashes and should they
5769 * be present is guaranteed to fail to find an entry. In this case the caller
5770 * must check if the name starts with a slash and call this routine. It is
5771 * going to fast forward across the spurious slashes and set the state up for
5774 static int __noinline
5775 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5777 struct nameidata *ndp;
5778 struct componentname *cnp;
5783 MPASS(*(cnp->cn_nameptr) == '/');
5786 cache_fpl_pathlen_dec(fpl);
5787 } while (*(cnp->cn_nameptr) == '/');
5790 * Go back to one slash so that cache_fplookup_parse_advance has
5791 * something to skip.
5794 cache_fpl_pathlen_inc(fpl);
5797 * cache_fplookup_parse_advance starts from ndp->ni_next
5799 ndp->ni_next = cnp->cn_nameptr;
5802 * See cache_fplookup_dot.
5804 fpl->tvp = fpl->dvp;
5805 fpl->tvp_seqc = fpl->dvp_seqc;
5811 * Handle trailing slashes (e.g., "foo/").
5813 * If a trailing slash is found the terminal vnode must be a directory.
5814 * Regular lookup shortens the path by nulifying the first trailing slash and
5815 * sets the TRAILINGSLASH flag to denote this took place. There are several
5816 * checks on it performed later.
5818 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5819 * manner relying on an invariant that a non-directory vnode will get a miss.
5820 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5822 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5823 * and denotes this is the last path component, which avoids looping back.
5825 * Only plain lookups are supported for now to restrict corner cases to handle.
5827 static int __noinline
5828 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5833 struct nameidata *ndp;
5834 struct componentname *cnp;
5835 struct namecache *ncp;
5837 char *cn_nameptr_orig, *cn_nameptr_slash;
5844 tvp_seqc = fpl->tvp_seqc;
5846 MPASS(fpl->dvp == fpl->tvp);
5847 KASSERT(cache_fpl_istrailingslash(fpl),
5848 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5850 KASSERT(cnp->cn_nameptr[0] == '\0',
5851 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5853 KASSERT(cnp->cn_namelen == 0,
5854 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5856 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5858 if (cnp->cn_nameiop != LOOKUP) {
5859 return (cache_fpl_aborted(fpl));
5862 if (__predict_false(tvp->v_type != VDIR)) {
5863 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5864 return (cache_fpl_aborted(fpl));
5866 cache_fpl_smr_exit(fpl);
5867 return (cache_fpl_handled_error(fpl, ENOTDIR));
5871 * Denote the last component.
5873 ndp->ni_next = &cnp->cn_nameptr[0];
5874 MPASS(cache_fpl_islastcn(ndp));
5877 * Unwind trailing slashes.
5879 cn_nameptr_orig = cnp->cn_nameptr;
5880 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5882 if (cnp->cn_nameptr[0] != '/') {
5888 * Unwind to the beginning of the path component.
5890 * Note the path may or may not have started with a slash.
5892 cn_nameptr_slash = cnp->cn_nameptr;
5893 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5895 if (cnp->cn_nameptr[0] == '/') {
5899 if (cnp->cn_nameptr[0] == '/') {
5903 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5904 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5905 cache_fpl_checkpoint(fpl);
5908 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5909 if (ni_pathlen != fpl->debug.ni_pathlen) {
5910 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5911 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5912 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5917 * If this was a "./" lookup the parent directory is already correct.
5919 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5924 * Otherwise we need to look it up.
5927 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5928 if (__predict_false(ncp == NULL)) {
5929 return (cache_fpl_aborted(fpl));
5931 nc_flag = atomic_load_char(&ncp->nc_flag);
5932 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5933 return (cache_fpl_aborted(fpl));
5935 fpl->dvp = ncp->nc_dvp;
5936 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5937 if (seqc_in_modify(fpl->dvp_seqc)) {
5938 return (cache_fpl_aborted(fpl));
5944 * See the API contract for VOP_FPLOOKUP_VEXEC.
5946 static int __noinline
5947 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5949 struct componentname *cnp;
5955 dvp_seqc = fpl->dvp_seqc;
5958 * Hack: delayed empty path checking.
5960 if (cnp->cn_pnbuf[0] == '\0') {
5961 return (cache_fplookup_emptypath(fpl));
5965 * TODO: Due to ignoring trailing slashes lookup will perform a
5966 * permission check on the last dir when it should not be doing it. It
5967 * may fail, but said failure should be ignored. It is possible to fix
5968 * it up fully without resorting to regular lookup, but for now just
5971 if (cache_fpl_istrailingslash(fpl)) {
5972 return (cache_fpl_aborted(fpl));
5976 * Hack: delayed degenerate path checking.
5978 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5979 return (cache_fplookup_degenerate(fpl));
5983 * Hack: delayed name len checking.
5985 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5986 cache_fpl_smr_exit(fpl);
5987 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5991 * Hack: they may be looking up foo/bar, where foo is not a directory.
5992 * In such a case we need to return ENOTDIR, but we may happen to get
5993 * here with a different error.
5995 if (dvp->v_type != VDIR) {
6000 * Hack: handle O_SEARCH.
6002 * Open Group Base Specifications Issue 7, 2018 edition states:
6004 * If the access mode of the open file description associated with the
6005 * file descriptor is not O_SEARCH, the function shall check whether
6006 * directory searches are permitted using the current permissions of
6007 * the directory underlying the file descriptor. If the access mode is
6008 * O_SEARCH, the function shall not perform the check.
6011 * Regular lookup tests for the NOEXECCHECK flag for every path
6012 * component to decide whether to do the permission check. However,
6013 * since most lookups never have the flag (and when they do it is only
6014 * present for the first path component), lockless lookup only acts on
6015 * it if there is a permission problem. Here the flag is represented
6016 * with a boolean so that we don't have to clear it on the way out.
6018 * For simplicity this always aborts.
6019 * TODO: check if this is the first lookup and ignore the permission
6020 * problem. Note the flag has to survive fallback (if it happens to be
6024 return (cache_fpl_aborted(fpl));
6029 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6030 error = cache_fpl_aborted(fpl);
6032 cache_fpl_partial(fpl);
6036 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6037 error = cache_fpl_aborted(fpl);
6039 cache_fpl_smr_exit(fpl);
6040 cache_fpl_handled_error(fpl, error);
6048 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
6050 struct nameidata *ndp;
6051 struct componentname *cnp;
6058 cache_fpl_checkpoint(fpl);
6061 * The vnode at hand is almost always stable, skip checking for it.
6062 * Worst case this postpones the check towards the end of the iteration
6066 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
6068 mp = atomic_load_ptr(&dvp->v_mount);
6069 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
6070 return (cache_fpl_aborted(fpl));
6073 MPASS(fpl->tvp == NULL);
6076 cache_fplookup_parse(fpl);
6078 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
6079 if (__predict_false(error != 0)) {
6080 error = cache_fplookup_failed_vexec(fpl, error);
6084 error = cache_fplookup_next(fpl);
6085 if (__predict_false(cache_fpl_terminated(fpl))) {
6089 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
6091 if (fpl->tvp->v_type == VLNK) {
6092 error = cache_fplookup_symlink(fpl);
6093 if (cache_fpl_terminated(fpl)) {
6097 if (cache_fpl_islastcn(ndp)) {
6098 error = cache_fplookup_final(fpl);
6102 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
6103 error = cache_fpl_aborted(fpl);
6107 fpl->dvp = fpl->tvp;
6108 fpl->dvp_seqc = fpl->tvp_seqc;
6109 cache_fplookup_parse_advance(fpl);
6112 cache_fpl_checkpoint(fpl);
6119 * Fast path lookup protected with SMR and sequence counters.
6121 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
6123 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
6126 * Traditional vnode lookup conceptually looks like this:
6132 * vn_unlock(current);
6139 * Each jump to the next vnode is safe memory-wise and atomic with respect to
6140 * any modifications thanks to holding respective locks.
6142 * The same guarantee can be provided with a combination of safe memory
6143 * reclamation and sequence counters instead. If all operations which affect
6144 * the relationship between the current vnode and the one we are looking for
6145 * also modify the counter, we can verify whether all the conditions held as
6146 * we made the jump. This includes things like permissions, mount points etc.
6147 * Counter modification is provided by enclosing relevant places in
6148 * vn_seqc_write_begin()/end() calls.
6150 * Thus this translates to:
6153 * dvp_seqc = seqc_read_any(dvp);
6154 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
6158 * tvp_seqc = seqc_read_any(tvp);
6159 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6161 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6163 * dvp = tvp; // we know nothing of importance has changed
6164 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6168 * vget(); // secure the vnode
6169 * if (!seqc_consistent(tvp, tvp_seqc) // final check
6171 * // at this point we know nothing has changed for any parent<->child pair
6172 * // as they were crossed during the lookup, meaning we matched the guarantee
6173 * // of the locked variant
6176 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6177 * - they are called while within vfs_smr protection which they must never exit
6178 * - EAGAIN can be returned to denote checking could not be performed, it is
6179 * always valid to return it
6180 * - if the sequence counter has not changed the result must be valid
6181 * - if the sequence counter has changed both false positives and false negatives
6182 * are permitted (since the result will be rejected later)
6183 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6185 * Caveats to watch out for:
6186 * - vnodes are passed unlocked and unreferenced with nothing stopping
6187 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6188 * to use atomic_load_ptr to fetch it.
6189 * - the aforementioned object can also get freed, meaning absent other means it
6190 * should be protected with vfs_smr
6191 * - either safely checking permissions as they are modified or guaranteeing
6192 * their stability is left to the routine
6195 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6198 struct cache_fpl fpl;
6201 struct componentname *cnp;
6204 fpl.status = CACHE_FPL_STATUS_UNSET;
6207 fpl.cnp = cnp = &ndp->ni_cnd;
6208 MPASS(ndp->ni_lcf == 0);
6209 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6210 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6212 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6213 MPASS(ndp->ni_resflags == 0);
6215 if (__predict_false(!cache_can_fplookup(&fpl))) {
6216 *status = fpl.status;
6217 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6218 return (EOPNOTSUPP);
6221 cache_fpl_checkpoint_outer(&fpl);
6223 cache_fpl_smr_enter_initial(&fpl);
6225 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6227 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6228 fpl.fsearch = false;
6229 fpl.tvp = NULL; /* for degenerate path handling */
6231 pwd = pwd_get_smr();
6233 namei_setup_rootdir(ndp, cnp, pwd);
6234 ndp->ni_topdir = pwd->pwd_jdir;
6236 if (cnp->cn_pnbuf[0] == '/') {
6237 dvp = cache_fpl_handle_root(&fpl);
6238 ndp->ni_resflags = NIRES_ABS;
6240 if (ndp->ni_dirfd == AT_FDCWD) {
6241 dvp = pwd->pwd_cdir;
6243 error = cache_fplookup_dirfd(&fpl, &dvp);
6244 if (__predict_false(error != 0)) {
6250 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6251 error = cache_fplookup_impl(dvp, &fpl);
6253 cache_fpl_smr_assert_not_entered(&fpl);
6254 cache_fpl_assert_status(&fpl);
6255 *status = fpl.status;
6256 if (SDT_PROBES_ENABLED()) {
6257 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6258 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6259 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6263 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6264 MPASS(error != CACHE_FPL_FAILED);
6266 cache_fpl_cleanup_cnp(fpl.cnp);
6267 MPASS(fpl.dvp == NULL);
6268 MPASS(fpl.tvp == NULL);
6270 ndp->ni_dvp = fpl.dvp;
6271 ndp->ni_vp = fpl.tvp;