2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993, 1995
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Poul-Henning Kamp of the FreeBSD Project.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
41 #include "opt_ktrace.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/capsicum.h>
46 #include <sys/counter.h>
47 #include <sys/filedesc.h>
48 #include <sys/fnv_hash.h>
49 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/fcntl.h>
55 #include <sys/mount.h>
56 #include <sys/namei.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysproto.h>
65 #include <sys/vnode.h>
68 #include <sys/ktrace.h>
71 #include <machine/_inttypes.h>
74 #include <sys/capsicum.h>
76 #include <security/audit/audit.h>
77 #include <security/mac/mac_framework.h>
85 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
88 SDT_PROVIDER_DECLARE(vfs);
89 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
91 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
93 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
95 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
97 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
98 "struct namecache *", "int", "int");
99 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
100 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
101 "char *", "struct vnode *");
102 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
103 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
104 "struct vnode *", "char *");
105 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
107 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
108 "struct vnode *", "char *");
109 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
111 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
112 "struct componentname *");
113 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
114 "struct componentname *");
115 SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
116 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
117 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
118 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
119 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
121 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
123 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
126 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
127 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
128 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
131 * This structure describes the elements in the cache of recent
132 * names looked up by namei.
138 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
139 "the state must fit in a union with a pointer without growing it");
142 LIST_ENTRY(namecache) nc_src; /* source vnode list */
143 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
144 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
145 struct vnode *nc_dvp; /* vnode of parent of name */
147 struct vnode *nu_vp; /* vnode the name refers to */
148 struct negstate nu_neg;/* negative entry state */
150 u_char nc_flag; /* flag bits */
151 u_char nc_nlen; /* length of name */
152 char nc_name[0]; /* segment name + nul */
156 * struct namecache_ts repeats struct namecache layout up to the
158 * struct namecache_ts is used in place of struct namecache when time(s) need
159 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
160 * both a non-dotdot directory name plus dotdot for the directory's
163 * See below for alignment requirement.
165 struct namecache_ts {
166 struct timespec nc_time; /* timespec provided by fs */
167 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
168 int nc_ticks; /* ticks value when entry was added */
170 struct namecache nc_nc;
173 TAILQ_HEAD(cache_freebatch, namecache);
176 * At least mips n32 performs 64-bit accesses to timespec as found
177 * in namecache_ts and requires them to be aligned. Since others
178 * may be in the same spot suffer a little bit and enforce the
179 * alignment for everyone. Note this is a nop for 64-bit platforms.
181 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
184 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
185 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
186 * smaller and the value was bumped to retain the total size, but it
187 * was never re-evaluated for suitability. A simple test counting
188 * lengths during package building shows that the value of 45 covers
189 * about 86% of all added entries, reaching 99% at 65.
191 * Regardless of the above, use of dedicated zones instead of malloc may be
192 * inducing additional waste. This may be hard to address as said zones are
193 * tied to VFS SMR. Even if retaining them, the current split should be
197 #define CACHE_PATH_CUTOFF 45
198 #define CACHE_LARGE_PAD 6
200 #define CACHE_PATH_CUTOFF 41
201 #define CACHE_LARGE_PAD 2
204 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
205 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
206 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
207 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
209 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
210 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
211 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
212 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
214 #define nc_vp n_un.nu_vp
215 #define nc_neg n_un.nu_neg
218 * Flags in namecache.nc_flag
220 #define NCF_WHITE 0x01
221 #define NCF_ISDOTDOT 0x02
224 #define NCF_DVDROP 0x10
225 #define NCF_NEGATIVE 0x20
226 #define NCF_INVALID 0x40
230 * Flags in negstate.neg_flag
234 static bool cache_neg_evict_cond(u_long lnumcache);
237 * Mark an entry as invalid.
239 * This is called before it starts getting deconstructed.
242 cache_ncp_invalidate(struct namecache *ncp)
245 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
246 ("%s: entry %p already invalid", __func__, ncp));
247 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
248 atomic_thread_fence_rel();
252 * Check whether the entry can be safely used.
254 * All places which elide locks are supposed to call this after they are
255 * done with reading from an entry.
257 #define cache_ncp_canuse(ncp) ({ \
258 struct namecache *_ncp = (ncp); \
261 atomic_thread_fence_acq(); \
262 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
263 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0); \
267 * Like the above but also checks NCF_WHITE.
269 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
270 struct namecache *_ncp = (ncp); \
273 atomic_thread_fence_acq(); \
274 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
275 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
279 * Name caching works as follows:
281 * Names found by directory scans are retained in a cache
282 * for future reference. It is managed LRU, so frequently
283 * used names will hang around. Cache is indexed by hash value
284 * obtained from (dvp, name) where dvp refers to the directory
287 * If it is a "negative" entry, (i.e. for a name that is known NOT to
288 * exist) the vnode pointer will be NULL.
290 * Upon reaching the last segment of a path, if the reference
291 * is for DELETE, or NOCACHE is set (rewrite), and the
292 * name is located in the cache, it will be dropped.
294 * These locks are used (in the order in which they can be taken):
296 * vnodelock mtx vnode lists and v_cache_dd field protection
297 * bucketlock mtx for access to given set of hash buckets
298 * neglist mtx negative entry LRU management
300 * It is legal to take multiple vnodelock and bucketlock locks. The locking
301 * order is lower address first. Both are recursive.
303 * "." lookups are lockless.
305 * ".." and vnode -> name lookups require vnodelock.
307 * name -> vnode lookup requires the relevant bucketlock to be held for reading.
309 * Insertions and removals of entries require involved vnodes and bucketlocks
310 * to be locked to provide safe operation against other threads modifying the
313 * Some lookups result in removal of the found entry (e.g. getting rid of a
314 * negative entry with the intent to create a positive one), which poses a
315 * problem when multiple threads reach the state. Similarly, two different
316 * threads can purge two different vnodes and try to remove the same name.
318 * If the already held vnode lock is lower than the second required lock, we
319 * can just take the other lock. However, in the opposite case, this could
320 * deadlock. As such, this is resolved by trylocking and if that fails unlocking
321 * the first node, locking everything in order and revalidating the state.
326 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
327 "Name cache parameters");
329 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
330 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
331 "Total namecache capacity");
333 u_int ncsizefactor = 2;
334 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
335 "Size factor for namecache");
337 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
338 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
339 "Ratio of negative namecache entries");
342 * Negative entry % of namecache capacity above which automatic eviction is allowed.
344 * Check cache_neg_evict_cond for details.
346 static u_int ncnegminpct = 3;
348 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
349 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
350 "Negative entry count above which automatic eviction is allowed");
353 * Structures associated with name caching.
355 #define NCHHASH(hash) \
356 (&nchashtbl[(hash) & nchash])
357 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
358 static u_long __read_mostly nchash; /* size of hash table */
359 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
360 "Size of namecache hash table");
361 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
362 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
364 struct nchstats nchstats; /* cache effectiveness statistics */
366 static bool __read_frequently cache_fast_revlookup = true;
367 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
368 &cache_fast_revlookup, 0, "");
370 static bool __read_mostly cache_rename_add = true;
371 SYSCTL_BOOL(_vfs, OID_AUTO, cache_rename_add, CTLFLAG_RW,
372 &cache_rename_add, 0, "");
374 static u_int __exclusive_cache_line neg_cycle;
377 #define numneglists (ncneghash + 1)
380 struct mtx nl_evict_lock;
381 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
382 TAILQ_HEAD(, namecache) nl_list;
383 TAILQ_HEAD(, namecache) nl_hotlist;
385 } __aligned(CACHE_LINE_SIZE);
387 static struct neglist neglists[numneglists];
389 static inline struct neglist *
390 NCP2NEGLIST(struct namecache *ncp)
393 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
396 static inline struct negstate *
397 NCP2NEGSTATE(struct namecache *ncp)
400 MPASS(ncp->nc_flag & NCF_NEGATIVE);
401 return (&ncp->nc_neg);
404 #define numbucketlocks (ncbuckethash + 1)
405 static u_int __read_mostly ncbuckethash;
406 static struct mtx_padalign __read_mostly *bucketlocks;
407 #define HASH2BUCKETLOCK(hash) \
408 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
410 #define numvnodelocks (ncvnodehash + 1)
411 static u_int __read_mostly ncvnodehash;
412 static struct mtx __read_mostly *vnodelocks;
413 static inline struct mtx *
414 VP2VNODELOCK(struct vnode *vp)
417 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
421 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
423 struct namecache_ts *ncp_ts;
425 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
426 (tsp == NULL && ticksp == NULL),
432 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
433 *tsp = ncp_ts->nc_time;
434 *ticksp = ncp_ts->nc_ticks;
438 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
439 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
440 "VFS namecache enabled");
443 /* Export size information to userland */
444 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
445 sizeof(struct namecache), "sizeof(struct namecache)");
448 * The new name cache statistics
450 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
451 "Name cache statistics");
453 #define STATNODE_ULONG(name, varname, descr) \
454 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
455 #define STATNODE_COUNTER(name, varname, descr) \
456 static COUNTER_U64_DEFINE_EARLY(varname); \
457 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
459 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
460 STATNODE_ULONG(count, numcache, "Number of cache entries");
461 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
462 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
463 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
464 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
465 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
466 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
467 STATNODE_COUNTER(posszaps, numposzaps,
468 "Number of cache hits (positive) we do not want to cache");
469 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
470 STATNODE_COUNTER(negzaps, numnegzaps,
471 "Number of cache hits (negative) we do not want to cache");
472 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
473 /* These count for vn_getcwd(), too. */
474 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
475 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
476 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
477 "Number of fullpath search errors (VOP_VPTOCNP failures)");
478 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
479 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
482 * Debug or developer statistics.
484 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
485 "Name cache debugging");
486 #define DEBUGNODE_ULONG(name, varname, descr) \
487 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
488 #define DEBUGNODE_COUNTER(name, varname, descr) \
489 static COUNTER_U64_DEFINE_EARLY(varname); \
490 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
492 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
493 "Number of successful removals after relocking");
494 static long zap_bucket_fail;
495 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
496 static long zap_bucket_fail2;
497 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
498 static long cache_lock_vnodes_cel_3_failures;
499 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
500 "Number of times 3-way vnode locking failed");
502 static void cache_zap_locked(struct namecache *ncp);
503 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
504 char **freebuf, size_t *buflen);
505 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
506 char **retbuf, size_t *buflen, size_t addend);
507 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
508 char **retbuf, size_t *buflen);
509 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
510 char **retbuf, size_t *len, size_t addend);
512 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
515 cache_assert_vlp_locked(struct mtx *vlp)
519 mtx_assert(vlp, MA_OWNED);
523 cache_assert_vnode_locked(struct vnode *vp)
527 vlp = VP2VNODELOCK(vp);
528 cache_assert_vlp_locked(vlp);
532 * Directory vnodes with entries are held for two reasons:
533 * 1. make them less of a target for reclamation in vnlru
534 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
536 * It will be feasible to stop doing it altogether if all filesystems start
537 * supporting lockless lookup.
540 cache_hold_vnode(struct vnode *vp)
543 cache_assert_vnode_locked(vp);
544 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
546 counter_u64_add(numcachehv, 1);
550 cache_drop_vnode(struct vnode *vp)
554 * Called after all locks are dropped, meaning we can't assert
555 * on the state of v_cache_src.
558 counter_u64_add(numcachehv, -1);
564 static uma_zone_t __read_mostly cache_zone_small;
565 static uma_zone_t __read_mostly cache_zone_small_ts;
566 static uma_zone_t __read_mostly cache_zone_large;
567 static uma_zone_t __read_mostly cache_zone_large_ts;
570 cache_symlink_alloc(size_t size, int flags)
573 if (size < CACHE_ZONE_SMALL_SIZE) {
574 return (uma_zalloc_smr(cache_zone_small, flags));
576 if (size < CACHE_ZONE_LARGE_SIZE) {
577 return (uma_zalloc_smr(cache_zone_large, flags));
583 cache_symlink_free(char *string, size_t size)
586 MPASS(string != NULL);
588 if (size < CACHE_ZONE_SMALL_SIZE) {
589 uma_zfree_smr(cache_zone_small, string);
592 if (size < CACHE_ZONE_LARGE_SIZE) {
593 uma_zfree_smr(cache_zone_large, string);
596 __assert_unreachable();
599 static struct namecache *
600 cache_alloc_uma(int len, bool ts)
602 struct namecache_ts *ncp_ts;
603 struct namecache *ncp;
605 if (__predict_false(ts)) {
606 if (len <= CACHE_PATH_CUTOFF)
607 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
609 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
610 ncp = &ncp_ts->nc_nc;
612 if (len <= CACHE_PATH_CUTOFF)
613 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
615 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
621 cache_free_uma(struct namecache *ncp)
623 struct namecache_ts *ncp_ts;
625 if (__predict_false(ncp->nc_flag & NCF_TS)) {
626 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
627 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
628 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
630 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
632 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
633 uma_zfree_smr(cache_zone_small, ncp);
635 uma_zfree_smr(cache_zone_large, ncp);
639 static struct namecache *
640 cache_alloc(int len, bool ts)
645 * Avoid blowout in namecache entries.
648 * 1. filesystems may end up trying to add an already existing entry
649 * (for example this can happen after a cache miss during concurrent
650 * lookup), in which case we will call cache_neg_evict despite not
652 * 2. the routine may fail to free anything and no provisions are made
653 * to make it try harder (see the inside for failure modes)
654 * 3. it only ever looks at negative entries.
656 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
657 if (cache_neg_evict_cond(lnumcache)) {
658 lnumcache = atomic_load_long(&numcache);
660 if (__predict_false(lnumcache >= ncsize)) {
661 atomic_subtract_long(&numcache, 1);
662 counter_u64_add(numdrops, 1);
665 return (cache_alloc_uma(len, ts));
669 cache_free(struct namecache *ncp)
673 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
674 cache_drop_vnode(ncp->nc_dvp);
677 atomic_subtract_long(&numcache, 1);
681 cache_free_batch(struct cache_freebatch *batch)
683 struct namecache *ncp, *nnp;
687 if (TAILQ_EMPTY(batch))
689 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
690 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
691 cache_drop_vnode(ncp->nc_dvp);
696 atomic_subtract_long(&numcache, i);
698 SDT_PROBE1(vfs, namecache, purge, batch, i);
702 * TODO: With the value stored we can do better than computing the hash based
703 * on the address. The choice of FNV should also be revisited.
706 cache_prehash(struct vnode *vp)
709 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
713 cache_get_hash(char *name, u_char len, struct vnode *dvp)
716 return (fnv_32_buf(name, len, dvp->v_nchash));
719 static inline struct nchashhead *
720 NCP2BUCKET(struct namecache *ncp)
724 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
725 return (NCHHASH(hash));
728 static inline struct mtx *
729 NCP2BUCKETLOCK(struct namecache *ncp)
733 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
734 return (HASH2BUCKETLOCK(hash));
739 cache_assert_bucket_locked(struct namecache *ncp)
743 blp = NCP2BUCKETLOCK(ncp);
744 mtx_assert(blp, MA_OWNED);
748 cache_assert_bucket_unlocked(struct namecache *ncp)
752 blp = NCP2BUCKETLOCK(ncp);
753 mtx_assert(blp, MA_NOTOWNED);
756 #define cache_assert_bucket_locked(x) do { } while (0)
757 #define cache_assert_bucket_unlocked(x) do { } while (0)
760 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
762 _cache_sort_vnodes(void **p1, void **p2)
766 MPASS(*p1 != NULL || *p2 != NULL);
776 cache_lock_all_buckets(void)
780 for (i = 0; i < numbucketlocks; i++)
781 mtx_lock(&bucketlocks[i]);
785 cache_unlock_all_buckets(void)
789 for (i = 0; i < numbucketlocks; i++)
790 mtx_unlock(&bucketlocks[i]);
794 cache_lock_all_vnodes(void)
798 for (i = 0; i < numvnodelocks; i++)
799 mtx_lock(&vnodelocks[i]);
803 cache_unlock_all_vnodes(void)
807 for (i = 0; i < numvnodelocks; i++)
808 mtx_unlock(&vnodelocks[i]);
812 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
815 cache_sort_vnodes(&vlp1, &vlp2);
818 if (!mtx_trylock(vlp1))
821 if (!mtx_trylock(vlp2)) {
831 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
834 MPASS(vlp1 != NULL || vlp2 != NULL);
844 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
847 MPASS(vlp1 != NULL || vlp2 != NULL);
856 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
858 struct nchstats snap;
860 if (req->oldptr == NULL)
861 return (SYSCTL_OUT(req, 0, sizeof(snap)));
864 snap.ncs_goodhits = counter_u64_fetch(numposhits);
865 snap.ncs_neghits = counter_u64_fetch(numneghits);
866 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
867 counter_u64_fetch(numnegzaps);
868 snap.ncs_miss = counter_u64_fetch(nummisszap) +
869 counter_u64_fetch(nummiss);
871 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
873 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
874 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
875 "VFS cache effectiveness statistics");
878 cache_recalc_neg_min(u_int val)
881 neg_min = (ncsize * val) / 100;
885 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
891 error = sysctl_handle_int(oidp, &val, 0, req);
892 if (error != 0 || req->newptr == NULL)
895 if (val == ncnegminpct)
897 if (val < 0 || val > 99)
900 cache_recalc_neg_min(val);
904 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
905 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
906 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
910 * Grab an atomic snapshot of the name cache hash chain lengths
912 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
913 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
917 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
919 struct nchashhead *ncpp;
920 struct namecache *ncp;
921 int i, error, n_nchash, *cntbuf;
924 n_nchash = nchash + 1; /* nchash is max index, not count */
925 if (req->oldptr == NULL)
926 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
927 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
928 cache_lock_all_buckets();
929 if (n_nchash != nchash + 1) {
930 cache_unlock_all_buckets();
931 free(cntbuf, M_TEMP);
934 /* Scan hash tables counting entries */
935 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
936 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
938 cache_unlock_all_buckets();
939 for (error = 0, i = 0; i < n_nchash; i++)
940 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
942 free(cntbuf, M_TEMP);
945 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
946 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
947 "nchash chain lengths");
950 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
953 struct nchashhead *ncpp;
954 struct namecache *ncp;
956 int count, maxlength, used, pct;
959 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
961 cache_lock_all_buckets();
962 n_nchash = nchash + 1; /* nchash is max index, not count */
966 /* Scan hash tables for applicable entries */
967 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
969 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
974 if (maxlength < count)
977 n_nchash = nchash + 1;
978 cache_unlock_all_buckets();
979 pct = (used * 100) / (n_nchash / 100);
980 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
983 error = SYSCTL_OUT(req, &used, sizeof(used));
986 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
989 error = SYSCTL_OUT(req, &pct, sizeof(pct));
994 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
995 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
996 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1000 * Negative entries management
1002 * Various workloads create plenty of negative entries and barely use them
1003 * afterwards. Moreover malicious users can keep performing bogus lookups
1004 * adding even more entries. For example "make tinderbox" as of writing this
1005 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1008 * As such, a rather aggressive eviction method is needed. The currently
1009 * employed method is a placeholder.
1011 * Entries are split over numneglists separate lists, each of which is further
1012 * split into hot and cold entries. Entries get promoted after getting a hit.
1013 * Eviction happens on addition of new entry.
1015 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1016 "Name cache negative entry statistics");
1018 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1019 "Number of negative cache entries");
1021 static COUNTER_U64_DEFINE_EARLY(neg_created);
1022 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1023 "Number of created negative entries");
1025 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1026 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1027 "Number of evicted negative entries");
1029 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1030 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1031 &neg_evict_skipped_empty,
1032 "Number of times evicting failed due to lack of entries");
1034 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1035 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1036 &neg_evict_skipped_missed,
1037 "Number of times evicting failed due to target entry disappearing");
1039 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1040 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1041 &neg_evict_skipped_contended,
1042 "Number of times evicting failed due to contention");
1044 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1045 "Number of cache hits (negative)");
1048 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1053 for (i = 0; i < numneglists; i++)
1054 out += neglists[i].nl_hotnum;
1056 return (SYSCTL_OUT(req, &out, sizeof(out)));
1058 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1059 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1060 "Number of hot negative entries");
1063 cache_neg_init(struct namecache *ncp)
1065 struct negstate *ns;
1067 ncp->nc_flag |= NCF_NEGATIVE;
1068 ns = NCP2NEGSTATE(ncp);
1071 counter_u64_add(neg_created, 1);
1074 #define CACHE_NEG_PROMOTION_THRESH 2
1077 cache_neg_hit_prep(struct namecache *ncp)
1079 struct negstate *ns;
1082 ns = NCP2NEGSTATE(ncp);
1083 n = atomic_load_char(&ns->neg_hit);
1085 if (n >= CACHE_NEG_PROMOTION_THRESH)
1087 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1090 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1094 * Nothing to do here but it is provided for completeness as some
1095 * cache_neg_hit_prep callers may end up returning without even
1096 * trying to promote.
1098 #define cache_neg_hit_abort(ncp) do { } while (0)
1101 cache_neg_hit_finish(struct namecache *ncp)
1104 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1105 counter_u64_add(numneghits, 1);
1109 * Move a negative entry to the hot list.
1112 cache_neg_promote_locked(struct namecache *ncp)
1115 struct negstate *ns;
1117 ns = NCP2NEGSTATE(ncp);
1118 nl = NCP2NEGLIST(ncp);
1119 mtx_assert(&nl->nl_lock, MA_OWNED);
1120 if ((ns->neg_flag & NEG_HOT) == 0) {
1121 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1122 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1124 ns->neg_flag |= NEG_HOT;
1129 * Move a hot negative entry to the cold list.
1132 cache_neg_demote_locked(struct namecache *ncp)
1135 struct negstate *ns;
1137 ns = NCP2NEGSTATE(ncp);
1138 nl = NCP2NEGLIST(ncp);
1139 mtx_assert(&nl->nl_lock, MA_OWNED);
1140 MPASS(ns->neg_flag & NEG_HOT);
1141 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1142 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1144 ns->neg_flag &= ~NEG_HOT;
1145 atomic_store_char(&ns->neg_hit, 0);
1149 * Move a negative entry to the hot list if it matches the lookup.
1151 * We have to take locks, but they may be contended and in the worst
1152 * case we may need to go off CPU. We don't want to spin within the
1153 * smr section and we can't block with it. Exiting the section means
1154 * the found entry could have been evicted. We are going to look it
1158 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1159 struct namecache *oncp, uint32_t hash)
1161 struct namecache *ncp;
1165 nl = NCP2NEGLIST(oncp);
1167 mtx_lock(&nl->nl_lock);
1169 * For hash iteration.
1174 * Avoid all surprises by only succeeding if we got the same entry and
1175 * bailing completely otherwise.
1176 * XXX There are no provisions to keep the vnode around, meaning we may
1177 * end up promoting a negative entry for a *new* vnode and returning
1178 * ENOENT on its account. This is the error we want to return anyway
1179 * and promotion is harmless.
1181 * In particular at this point there can be a new ncp which matches the
1182 * search but hashes to a different neglist.
1184 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1190 * No match to begin with.
1192 if (__predict_false(ncp == NULL)) {
1197 * The newly found entry may be something different...
1199 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1200 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1205 * ... and not even negative.
1207 nc_flag = atomic_load_char(&ncp->nc_flag);
1208 if ((nc_flag & NCF_NEGATIVE) == 0) {
1212 if (!cache_ncp_canuse(ncp)) {
1216 cache_neg_promote_locked(ncp);
1217 cache_neg_hit_finish(ncp);
1219 mtx_unlock(&nl->nl_lock);
1223 mtx_unlock(&nl->nl_lock);
1228 cache_neg_promote(struct namecache *ncp)
1232 nl = NCP2NEGLIST(ncp);
1233 mtx_lock(&nl->nl_lock);
1234 cache_neg_promote_locked(ncp);
1235 mtx_unlock(&nl->nl_lock);
1239 cache_neg_insert(struct namecache *ncp)
1243 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1244 cache_assert_bucket_locked(ncp);
1245 nl = NCP2NEGLIST(ncp);
1246 mtx_lock(&nl->nl_lock);
1247 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1248 mtx_unlock(&nl->nl_lock);
1249 atomic_add_long(&numneg, 1);
1253 cache_neg_remove(struct namecache *ncp)
1256 struct negstate *ns;
1258 cache_assert_bucket_locked(ncp);
1259 nl = NCP2NEGLIST(ncp);
1260 ns = NCP2NEGSTATE(ncp);
1261 mtx_lock(&nl->nl_lock);
1262 if ((ns->neg_flag & NEG_HOT) != 0) {
1263 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1266 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1268 mtx_unlock(&nl->nl_lock);
1269 atomic_subtract_long(&numneg, 1);
1272 static struct neglist *
1273 cache_neg_evict_select_list(void)
1278 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1279 nl = &neglists[c % numneglists];
1280 if (!mtx_trylock(&nl->nl_evict_lock)) {
1281 counter_u64_add(neg_evict_skipped_contended, 1);
1287 static struct namecache *
1288 cache_neg_evict_select_entry(struct neglist *nl)
1290 struct namecache *ncp, *lncp;
1291 struct negstate *ns, *lns;
1294 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1295 mtx_assert(&nl->nl_lock, MA_OWNED);
1296 ncp = TAILQ_FIRST(&nl->nl_list);
1300 lns = NCP2NEGSTATE(lncp);
1301 for (i = 1; i < 4; i++) {
1302 ncp = TAILQ_NEXT(ncp, nc_dst);
1305 ns = NCP2NEGSTATE(ncp);
1306 if (ns->neg_hit < lns->neg_hit) {
1315 cache_neg_evict(void)
1317 struct namecache *ncp, *ncp2;
1326 nl = cache_neg_evict_select_list();
1331 mtx_lock(&nl->nl_lock);
1332 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1334 cache_neg_demote_locked(ncp);
1336 ncp = cache_neg_evict_select_entry(nl);
1338 counter_u64_add(neg_evict_skipped_empty, 1);
1339 mtx_unlock(&nl->nl_lock);
1340 mtx_unlock(&nl->nl_evict_lock);
1343 nlen = ncp->nc_nlen;
1345 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1346 dvlp = VP2VNODELOCK(dvp);
1347 blp = HASH2BUCKETLOCK(hash);
1348 mtx_unlock(&nl->nl_lock);
1349 mtx_unlock(&nl->nl_evict_lock);
1353 * Note that since all locks were dropped above, the entry may be
1354 * gone or reallocated to be something else.
1356 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1357 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1358 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1362 counter_u64_add(neg_evict_skipped_missed, 1);
1366 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1367 MPASS(blp == NCP2BUCKETLOCK(ncp));
1368 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1370 cache_zap_locked(ncp);
1371 counter_u64_add(neg_evicted, 1);
1382 * Maybe evict a negative entry to create more room.
1384 * The ncnegfactor parameter limits what fraction of the total count
1385 * can comprise of negative entries. However, if the cache is just
1386 * warming up this leads to excessive evictions. As such, ncnegminpct
1387 * (recomputed to neg_min) dictates whether the above should be
1390 * Try evicting if the cache is close to full capacity regardless of
1391 * other considerations.
1394 cache_neg_evict_cond(u_long lnumcache)
1398 if (ncsize - 1000 < lnumcache)
1400 lnumneg = atomic_load_long(&numneg);
1401 if (lnumneg < neg_min)
1403 if (lnumneg * ncnegfactor < lnumcache)
1406 return (cache_neg_evict());
1410 * cache_zap_locked():
1412 * Removes a namecache entry from cache, whether it contains an actual
1413 * pointer to a vnode or if it is just a negative cache entry.
1416 cache_zap_locked(struct namecache *ncp)
1418 struct nchashhead *ncpp;
1420 if (!(ncp->nc_flag & NCF_NEGATIVE))
1421 cache_assert_vnode_locked(ncp->nc_vp);
1422 cache_assert_vnode_locked(ncp->nc_dvp);
1423 cache_assert_bucket_locked(ncp);
1425 cache_ncp_invalidate(ncp);
1427 ncpp = NCP2BUCKET(ncp);
1428 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1429 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1430 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
1431 ncp->nc_name, ncp->nc_vp);
1432 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
1433 if (ncp == ncp->nc_vp->v_cache_dd) {
1434 vn_seqc_write_begin_unheld(ncp->nc_vp);
1435 ncp->nc_vp->v_cache_dd = NULL;
1436 vn_seqc_write_end(ncp->nc_vp);
1439 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
1441 cache_neg_remove(ncp);
1443 if (ncp->nc_flag & NCF_ISDOTDOT) {
1444 if (ncp == ncp->nc_dvp->v_cache_dd) {
1445 vn_seqc_write_begin_unheld(ncp->nc_dvp);
1446 ncp->nc_dvp->v_cache_dd = NULL;
1447 vn_seqc_write_end(ncp->nc_dvp);
1450 LIST_REMOVE(ncp, nc_src);
1451 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
1452 ncp->nc_flag |= NCF_DVDROP;
1458 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1462 MPASS(ncp->nc_dvp == vp);
1463 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1464 cache_assert_vnode_locked(vp);
1466 blp = NCP2BUCKETLOCK(ncp);
1468 cache_zap_locked(ncp);
1473 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1476 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1479 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1480 cache_assert_vnode_locked(vp);
1482 if (ncp->nc_flag & NCF_NEGATIVE) {
1483 if (*vlpp != NULL) {
1487 cache_zap_negative_locked_vnode_kl(ncp, vp);
1491 pvlp = VP2VNODELOCK(vp);
1492 blp = NCP2BUCKETLOCK(ncp);
1493 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1494 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1496 if (*vlpp == vlp1 || *vlpp == vlp2) {
1500 if (*vlpp != NULL) {
1504 cache_sort_vnodes(&vlp1, &vlp2);
1509 if (!mtx_trylock(vlp1))
1515 cache_zap_locked(ncp);
1517 if (to_unlock != NULL)
1518 mtx_unlock(to_unlock);
1525 MPASS(*vlpp == NULL);
1531 * If trylocking failed we can get here. We know enough to take all needed locks
1532 * in the right order and re-lookup the entry.
1535 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1536 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1539 struct namecache *rncp;
1541 cache_assert_bucket_unlocked(ncp);
1543 cache_sort_vnodes(&dvlp, &vlp);
1544 cache_lock_vnodes(dvlp, vlp);
1546 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1547 if (rncp == ncp && rncp->nc_dvp == dvp &&
1548 rncp->nc_nlen == cnp->cn_namelen &&
1549 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1553 cache_zap_locked(rncp);
1555 cache_unlock_vnodes(dvlp, vlp);
1556 counter_u64_add(zap_bucket_relock_success, 1);
1561 cache_unlock_vnodes(dvlp, vlp);
1565 static int __noinline
1566 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1567 uint32_t hash, struct mtx *blp)
1569 struct mtx *dvlp, *vlp;
1572 cache_assert_bucket_locked(ncp);
1574 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1576 if (!(ncp->nc_flag & NCF_NEGATIVE))
1577 vlp = VP2VNODELOCK(ncp->nc_vp);
1578 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1579 cache_zap_locked(ncp);
1581 cache_unlock_vnodes(dvlp, vlp);
1587 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1590 static __noinline int
1591 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1593 struct namecache *ncp;
1595 struct mtx *dvlp, *dvlp2;
1599 if (cnp->cn_namelen == 2 &&
1600 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1601 dvlp = VP2VNODELOCK(dvp);
1605 ncp = dvp->v_cache_dd;
1610 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1613 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1614 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1616 MPASS(dvp->v_cache_dd == NULL);
1622 vn_seqc_write_begin(dvp);
1623 dvp->v_cache_dd = NULL;
1624 vn_seqc_write_end(dvp);
1629 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1633 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1634 blp = HASH2BUCKETLOCK(hash);
1636 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1641 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1642 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1643 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1652 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1653 if (__predict_false(error != 0)) {
1657 counter_u64_add(numposzaps, 1);
1658 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1662 counter_u64_add(nummisszap, 1);
1663 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1667 static int __noinline
1668 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1669 struct timespec *tsp, int *ticksp)
1674 counter_u64_add(dothits, 1);
1675 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1682 * When we lookup "." we still can be asked to lock it
1685 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1686 if (ltype != VOP_ISLOCKED(*vpp)) {
1687 if (ltype == LK_EXCLUSIVE) {
1688 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1689 if (VN_IS_DOOMED((*vpp))) {
1690 /* forced unmount */
1696 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1701 static int __noinline
1702 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1703 struct timespec *tsp, int *ticksp)
1705 struct namecache_ts *ncp_ts;
1706 struct namecache *ncp;
1712 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1714 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1715 cache_remove_cnp(dvp, cnp);
1719 counter_u64_add(dotdothits, 1);
1721 dvlp = VP2VNODELOCK(dvp);
1723 ncp = dvp->v_cache_dd;
1725 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, "..", NULL);
1729 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1730 if (ncp->nc_flag & NCF_NEGATIVE)
1737 goto negative_success;
1738 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1739 cache_out_ts(ncp, tsp, ticksp);
1740 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1741 NCF_DTS && tsp != NULL) {
1742 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1743 *tsp = ncp_ts->nc_dotdottime;
1747 ltype = VOP_ISLOCKED(dvp);
1749 vs = vget_prep(*vpp);
1751 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1752 vn_lock(dvp, ltype | LK_RETRY);
1753 if (VN_IS_DOOMED(dvp)) {
1765 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1766 if (cnp->cn_flags & ISLASTCN) {
1767 counter_u64_add(numnegzaps, 1);
1768 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1775 whiteout = (ncp->nc_flag & NCF_WHITE);
1776 cache_out_ts(ncp, tsp, ticksp);
1777 if (cache_neg_hit_prep(ncp))
1778 cache_neg_promote(ncp);
1780 cache_neg_hit_finish(ncp);
1783 cnp->cn_flags |= ISWHITEOUT;
1788 * Lookup a name in the name cache
1792 * - dvp: Parent directory in which to search.
1793 * - vpp: Return argument. Will contain desired vnode on cache hit.
1794 * - cnp: Parameters of the name search. The most interesting bits of
1795 * the cn_flags field have the following meanings:
1796 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1798 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1799 * - tsp: Return storage for cache timestamp. On a successful (positive
1800 * or negative) lookup, tsp will be filled with any timespec that
1801 * was stored when this cache entry was created. However, it will
1802 * be clear for "." entries.
1803 * - ticks: Return storage for alternate cache timestamp. On a successful
1804 * (positive or negative) lookup, it will contain the ticks value
1805 * that was current when the cache entry was created, unless cnp
1808 * Either both tsp and ticks have to be provided or neither of them.
1812 * - -1: A positive cache hit. vpp will contain the desired vnode.
1813 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1814 * to a forced unmount. vpp will not be modified. If the entry
1815 * is a whiteout, then the ISWHITEOUT flag will be set in
1817 * - 0: A cache miss. vpp will not be modified.
1821 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1822 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1823 * lock is not recursively acquired.
1825 static int __noinline
1826 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1827 struct timespec *tsp, int *ticksp)
1829 struct namecache *ncp;
1836 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1837 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1840 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1841 blp = HASH2BUCKETLOCK(hash);
1844 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1845 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1846 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1850 if (__predict_false(ncp == NULL)) {
1852 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1854 counter_u64_add(nummiss, 1);
1858 if (ncp->nc_flag & NCF_NEGATIVE)
1859 goto negative_success;
1861 counter_u64_add(numposhits, 1);
1863 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1864 cache_out_ts(ncp, tsp, ticksp);
1866 vs = vget_prep(*vpp);
1868 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1876 * We don't get here with regular lookup apart from corner cases.
1878 if (__predict_true(cnp->cn_nameiop == CREATE)) {
1879 if (cnp->cn_flags & ISLASTCN) {
1880 counter_u64_add(numnegzaps, 1);
1881 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1882 if (__predict_false(error != 0)) {
1891 whiteout = (ncp->nc_flag & NCF_WHITE);
1892 cache_out_ts(ncp, tsp, ticksp);
1893 if (cache_neg_hit_prep(ncp))
1894 cache_neg_promote(ncp);
1896 cache_neg_hit_finish(ncp);
1899 cnp->cn_flags |= ISWHITEOUT;
1904 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1905 struct timespec *tsp, int *ticksp)
1907 struct namecache *ncp;
1911 bool whiteout, neg_promote;
1914 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
1917 if (__predict_false(!doingcache)) {
1918 cnp->cn_flags &= ~MAKEENTRY;
1923 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1924 if (cnp->cn_namelen == 1)
1925 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1926 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
1927 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
1930 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1932 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
1933 cache_remove_cnp(dvp, cnp);
1937 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1940 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1941 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1942 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1946 if (__predict_false(ncp == NULL)) {
1948 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1950 counter_u64_add(nummiss, 1);
1954 nc_flag = atomic_load_char(&ncp->nc_flag);
1955 if (nc_flag & NCF_NEGATIVE)
1956 goto negative_success;
1958 counter_u64_add(numposhits, 1);
1960 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1961 cache_out_ts(ncp, tsp, ticksp);
1963 if (!cache_ncp_canuse(ncp)) {
1968 vs = vget_prep_smr(*vpp);
1970 if (__predict_false(vs == VGET_NONE)) {
1974 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1981 if (cnp->cn_nameiop == CREATE) {
1982 if (cnp->cn_flags & ISLASTCN) {
1988 cache_out_ts(ncp, tsp, ticksp);
1989 whiteout = (ncp->nc_flag & NCF_WHITE);
1990 neg_promote = cache_neg_hit_prep(ncp);
1991 if (!cache_ncp_canuse(ncp)) {
1992 cache_neg_hit_abort(ncp);
1998 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2001 cache_neg_hit_finish(ncp);
2005 cnp->cn_flags |= ISWHITEOUT;
2008 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2011 struct celockstate {
2015 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2016 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2019 cache_celockstate_init(struct celockstate *cel)
2022 bzero(cel, sizeof(*cel));
2026 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2029 struct mtx *vlp1, *vlp2;
2031 MPASS(cel->vlp[0] == NULL);
2032 MPASS(cel->vlp[1] == NULL);
2033 MPASS(cel->vlp[2] == NULL);
2035 MPASS(vp != NULL || dvp != NULL);
2037 vlp1 = VP2VNODELOCK(vp);
2038 vlp2 = VP2VNODELOCK(dvp);
2039 cache_sort_vnodes(&vlp1, &vlp2);
2050 cache_unlock_vnodes_cel(struct celockstate *cel)
2053 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2055 if (cel->vlp[0] != NULL)
2056 mtx_unlock(cel->vlp[0]);
2057 if (cel->vlp[1] != NULL)
2058 mtx_unlock(cel->vlp[1]);
2059 if (cel->vlp[2] != NULL)
2060 mtx_unlock(cel->vlp[2]);
2064 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2069 cache_assert_vlp_locked(cel->vlp[0]);
2070 cache_assert_vlp_locked(cel->vlp[1]);
2071 MPASS(cel->vlp[2] == NULL);
2074 vlp = VP2VNODELOCK(vp);
2077 if (vlp >= cel->vlp[1]) {
2080 if (mtx_trylock(vlp))
2082 cache_lock_vnodes_cel_3_failures++;
2083 cache_unlock_vnodes_cel(cel);
2084 if (vlp < cel->vlp[0]) {
2086 mtx_lock(cel->vlp[0]);
2087 mtx_lock(cel->vlp[1]);
2089 if (cel->vlp[0] != NULL)
2090 mtx_lock(cel->vlp[0]);
2092 mtx_lock(cel->vlp[1]);
2102 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2106 MPASS(cel->blp[0] == NULL);
2107 MPASS(cel->blp[1] == NULL);
2109 cache_sort_vnodes(&blp1, &blp2);
2120 cache_unlock_buckets_cel(struct celockstate *cel)
2123 if (cel->blp[0] != NULL)
2124 mtx_unlock(cel->blp[0]);
2125 mtx_unlock(cel->blp[1]);
2129 * Lock part of the cache affected by the insertion.
2131 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2132 * However, insertion can result in removal of an old entry. In this
2133 * case we have an additional vnode and bucketlock pair to lock.
2135 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2136 * preserving the locking order (smaller address first).
2139 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2142 struct namecache *ncp;
2143 struct mtx *blps[2];
2145 blps[0] = HASH2BUCKETLOCK(hash);
2148 cache_lock_vnodes_cel(cel, dvp, vp);
2149 if (vp == NULL || vp->v_type != VDIR)
2151 ncp = vp->v_cache_dd;
2154 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2156 MPASS(ncp->nc_dvp == vp);
2157 blps[1] = NCP2BUCKETLOCK(ncp);
2158 if (ncp->nc_flag & NCF_NEGATIVE)
2160 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2163 * All vnodes got re-locked. Re-validate the state and if
2164 * nothing changed we are done. Otherwise restart.
2166 if (ncp == vp->v_cache_dd &&
2167 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2168 blps[1] == NCP2BUCKETLOCK(ncp) &&
2169 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2171 cache_unlock_vnodes_cel(cel);
2176 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2180 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2183 struct namecache *ncp;
2184 struct mtx *blps[2];
2186 blps[0] = HASH2BUCKETLOCK(hash);
2189 cache_lock_vnodes_cel(cel, dvp, vp);
2190 ncp = dvp->v_cache_dd;
2193 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2195 MPASS(ncp->nc_dvp == dvp);
2196 blps[1] = NCP2BUCKETLOCK(ncp);
2197 if (ncp->nc_flag & NCF_NEGATIVE)
2199 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2201 if (ncp == dvp->v_cache_dd &&
2202 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2203 blps[1] == NCP2BUCKETLOCK(ncp) &&
2204 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2206 cache_unlock_vnodes_cel(cel);
2211 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2215 cache_enter_unlock(struct celockstate *cel)
2218 cache_unlock_buckets_cel(cel);
2219 cache_unlock_vnodes_cel(cel);
2222 static void __noinline
2223 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2224 struct componentname *cnp)
2226 struct celockstate cel;
2227 struct namecache *ncp;
2231 if (dvp->v_cache_dd == NULL)
2233 len = cnp->cn_namelen;
2234 cache_celockstate_init(&cel);
2235 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2236 cache_enter_lock_dd(&cel, dvp, vp, hash);
2237 vn_seqc_write_begin(dvp);
2238 ncp = dvp->v_cache_dd;
2239 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2240 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2241 cache_zap_locked(ncp);
2245 dvp->v_cache_dd = NULL;
2246 vn_seqc_write_end(dvp);
2247 cache_enter_unlock(&cel);
2253 * Add an entry to the cache.
2256 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2257 struct timespec *tsp, struct timespec *dtsp)
2259 struct celockstate cel;
2260 struct namecache *ncp, *n2, *ndd;
2261 struct namecache_ts *ncp_ts;
2262 struct nchashhead *ncpp;
2267 KASSERT(cnp->cn_namelen <= NAME_MAX,
2268 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2270 VNPASS(dvp != vp, dvp);
2271 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2272 VNPASS(dvp->v_type != VNON, dvp);
2274 VNPASS(!VN_IS_DOOMED(vp), vp);
2275 VNPASS(vp->v_type != VNON, vp);
2279 if (__predict_false(!doingcache))
2284 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2285 if (cnp->cn_namelen == 1)
2287 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2288 cache_enter_dotdot_prep(dvp, vp, cnp);
2289 flag = NCF_ISDOTDOT;
2293 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2297 cache_celockstate_init(&cel);
2302 * Calculate the hash key and setup as much of the new
2303 * namecache entry as possible before acquiring the lock.
2305 ncp->nc_flag = flag | NCF_WIP;
2308 cache_neg_init(ncp);
2311 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2312 ncp_ts->nc_time = *tsp;
2313 ncp_ts->nc_ticks = ticks;
2314 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2316 ncp_ts->nc_dotdottime = *dtsp;
2317 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2320 len = ncp->nc_nlen = cnp->cn_namelen;
2321 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2322 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2323 ncp->nc_name[len] = '\0';
2324 cache_enter_lock(&cel, dvp, vp, hash);
2327 * See if this vnode or negative entry is already in the cache
2328 * with this name. This can happen with concurrent lookups of
2329 * the same path name.
2331 ncpp = NCHHASH(hash);
2332 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2333 if (n2->nc_dvp == dvp &&
2334 n2->nc_nlen == cnp->cn_namelen &&
2335 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2336 MPASS(cache_ncp_canuse(n2));
2337 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2339 ("%s: found entry pointing to a different vnode (%p != %p)",
2340 __func__, NULL, vp));
2342 KASSERT(n2->nc_vp == vp,
2343 ("%s: found entry pointing to a different vnode (%p != %p)",
2344 __func__, n2->nc_vp, vp));
2346 * Entries are supposed to be immutable unless in the
2347 * process of getting destroyed. Accommodating for
2348 * changing timestamps is possible but not worth it.
2349 * This should be harmless in terms of correctness, in
2350 * the worst case resulting in an earlier expiration.
2351 * Alternatively, the found entry can be replaced
2354 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2357 KASSERT((n2->nc_flag & NCF_TS) != 0,
2359 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2360 n2_ts->nc_time = ncp_ts->nc_time;
2361 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2363 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2364 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2368 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2370 goto out_unlock_free;
2374 if (flag == NCF_ISDOTDOT) {
2376 * See if we are trying to add .. entry, but some other lookup
2377 * has populated v_cache_dd pointer already.
2379 if (dvp->v_cache_dd != NULL)
2380 goto out_unlock_free;
2381 KASSERT(vp == NULL || vp->v_type == VDIR,
2382 ("wrong vnode type %p", vp));
2383 vn_seqc_write_begin(dvp);
2384 dvp->v_cache_dd = ncp;
2385 vn_seqc_write_end(dvp);
2389 if (flag != NCF_ISDOTDOT) {
2391 * For this case, the cache entry maps both the
2392 * directory name in it and the name ".." for the
2393 * directory's parent.
2395 vn_seqc_write_begin(vp);
2396 if ((ndd = vp->v_cache_dd) != NULL) {
2397 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2398 cache_zap_locked(ndd);
2402 vp->v_cache_dd = ncp;
2403 vn_seqc_write_end(vp);
2404 } else if (vp->v_type != VDIR) {
2405 if (vp->v_cache_dd != NULL) {
2406 vn_seqc_write_begin(vp);
2407 vp->v_cache_dd = NULL;
2408 vn_seqc_write_end(vp);
2413 if (flag != NCF_ISDOTDOT) {
2414 if (LIST_EMPTY(&dvp->v_cache_src)) {
2415 cache_hold_vnode(dvp);
2417 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2421 * If the entry is "negative", we place it into the
2422 * "negative" cache queue, otherwise, we place it into the
2423 * destination vnode's cache entries queue.
2426 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2427 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2430 if (cnp->cn_flags & ISWHITEOUT)
2431 ncp->nc_flag |= NCF_WHITE;
2432 cache_neg_insert(ncp);
2433 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2438 * Insert the new namecache entry into the appropriate chain
2439 * within the cache entries table.
2441 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2443 atomic_thread_fence_rel();
2445 * Mark the entry as fully constructed.
2446 * It is immutable past this point until its removal.
2448 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2450 cache_enter_unlock(&cel);
2455 cache_enter_unlock(&cel);
2461 cache_roundup_2(u_int val)
2465 for (res = 1; res <= val; res <<= 1)
2471 static struct nchashhead *
2472 nchinittbl(u_long elements, u_long *hashmask)
2474 struct nchashhead *hashtbl;
2477 hashsize = cache_roundup_2(elements) / 2;
2479 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2480 for (i = 0; i < hashsize; i++)
2481 CK_SLIST_INIT(&hashtbl[i]);
2482 *hashmask = hashsize - 1;
2487 ncfreetbl(struct nchashhead *hashtbl)
2490 free(hashtbl, M_VFSCACHE);
2494 * Name cache initialization, from vfs_init() when we are booting
2497 nchinit(void *dummy __unused)
2501 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2502 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2503 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2504 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2505 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2506 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2507 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2508 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2510 VFS_SMR_ZONE_SET(cache_zone_small);
2511 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2512 VFS_SMR_ZONE_SET(cache_zone_large);
2513 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2515 ncsize = desiredvnodes * ncsizefactor;
2516 cache_recalc_neg_min(ncnegminpct);
2517 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2518 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2519 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2521 if (ncbuckethash > nchash)
2522 ncbuckethash = nchash;
2523 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2525 for (i = 0; i < numbucketlocks; i++)
2526 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2527 ncvnodehash = ncbuckethash;
2528 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2530 for (i = 0; i < numvnodelocks; i++)
2531 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2533 for (i = 0; i < numneglists; i++) {
2534 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2535 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2536 TAILQ_INIT(&neglists[i].nl_list);
2537 TAILQ_INIT(&neglists[i].nl_hotlist);
2540 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2543 cache_vnode_init(struct vnode *vp)
2546 LIST_INIT(&vp->v_cache_src);
2547 TAILQ_INIT(&vp->v_cache_dst);
2548 vp->v_cache_dd = NULL;
2553 cache_changesize(u_long newmaxvnodes)
2555 struct nchashhead *new_nchashtbl, *old_nchashtbl;
2556 u_long new_nchash, old_nchash;
2557 struct namecache *ncp;
2562 newncsize = newmaxvnodes * ncsizefactor;
2563 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2564 if (newmaxvnodes < numbucketlocks)
2565 newmaxvnodes = numbucketlocks;
2567 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2568 /* If same hash table size, nothing to do */
2569 if (nchash == new_nchash) {
2570 ncfreetbl(new_nchashtbl);
2574 * Move everything from the old hash table to the new table.
2575 * None of the namecache entries in the table can be removed
2576 * because to do so, they have to be removed from the hash table.
2578 cache_lock_all_vnodes();
2579 cache_lock_all_buckets();
2580 old_nchashtbl = nchashtbl;
2581 old_nchash = nchash;
2582 nchashtbl = new_nchashtbl;
2583 nchash = new_nchash;
2584 for (i = 0; i <= old_nchash; i++) {
2585 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2586 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2588 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2589 CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2593 cache_recalc_neg_min(ncnegminpct);
2594 cache_unlock_all_buckets();
2595 cache_unlock_all_vnodes();
2596 ncfreetbl(old_nchashtbl);
2600 * Invalidate all entries from and to a particular vnode.
2603 cache_purge_impl(struct vnode *vp)
2605 struct cache_freebatch batch;
2606 struct namecache *ncp;
2607 struct mtx *vlp, *vlp2;
2610 vlp = VP2VNODELOCK(vp);
2614 while (!LIST_EMPTY(&vp->v_cache_src)) {
2615 ncp = LIST_FIRST(&vp->v_cache_src);
2616 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2618 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2620 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2621 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2622 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2624 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2626 ncp = vp->v_cache_dd;
2628 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2629 ("lost dotdot link"));
2630 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2632 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2634 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2638 cache_free_batch(&batch);
2642 * Opportunistic check to see if there is anything to do.
2645 cache_has_entries(struct vnode *vp)
2648 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2649 vp->v_cache_dd == NULL)
2655 cache_purge(struct vnode *vp)
2658 SDT_PROBE1(vfs, namecache, purge, done, vp);
2659 if (!cache_has_entries(vp))
2661 cache_purge_impl(vp);
2665 * Only to be used by vgone.
2668 cache_purge_vgone(struct vnode *vp)
2672 VNPASS(VN_IS_DOOMED(vp), vp);
2673 if (cache_has_entries(vp)) {
2674 cache_purge_impl(vp);
2679 * Serialize against a potential thread doing cache_purge.
2681 vlp = VP2VNODELOCK(vp);
2682 mtx_wait_unlocked(vlp);
2683 if (cache_has_entries(vp)) {
2684 cache_purge_impl(vp);
2691 * Invalidate all negative entries for a particular directory vnode.
2694 cache_purge_negative(struct vnode *vp)
2696 struct cache_freebatch batch;
2697 struct namecache *ncp, *nnp;
2700 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2701 if (LIST_EMPTY(&vp->v_cache_src))
2704 vlp = VP2VNODELOCK(vp);
2706 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2707 if (!(ncp->nc_flag & NCF_NEGATIVE))
2709 cache_zap_negative_locked_vnode_kl(ncp, vp);
2710 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2713 cache_free_batch(&batch);
2717 * Entry points for modifying VOP operations.
2720 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2721 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2724 ASSERT_VOP_IN_SEQC(fdvp);
2725 ASSERT_VOP_IN_SEQC(fvp);
2726 ASSERT_VOP_IN_SEQC(tdvp);
2728 ASSERT_VOP_IN_SEQC(tvp);
2733 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2734 ("%s: lingering negative entry", __func__));
2736 cache_remove_cnp(tdvp, tcnp);
2742 * Historically renaming was always purging all revelang entries,
2743 * but that's quite wasteful. In particular turns out that in many cases
2744 * the target file is immediately accessed after rename, inducing a cache
2747 * Recode this to reduce relocking and reuse the existing entry (if any)
2748 * instead of just removing it above and allocating a new one here.
2750 if (cache_rename_add) {
2751 cache_enter(tdvp, fvp, tcnp);
2756 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2759 ASSERT_VOP_IN_SEQC(dvp);
2760 ASSERT_VOP_IN_SEQC(vp);
2766 * Validate that if an entry exists it matches.
2769 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2771 struct namecache *ncp;
2775 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2776 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2778 blp = HASH2BUCKETLOCK(hash);
2780 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2781 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2782 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2783 if (ncp->nc_vp != vp)
2784 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p vp %p\n",
2785 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp,
2794 * Flush all entries referencing a particular filesystem.
2797 cache_purgevfs(struct mount *mp)
2799 struct vnode *vp, *mvp;
2801 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2803 * Somewhat wasteful iteration over all vnodes. Would be better to
2804 * support filtering and avoid the interlock to begin with.
2806 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2807 if (!cache_has_entries(vp)) {
2819 * Perform canonical checks and cache lookup and pass on to filesystem
2820 * through the vop_cachedlookup only if needed.
2824 vfs_cache_lookup(struct vop_lookup_args *ap)
2828 struct vnode **vpp = ap->a_vpp;
2829 struct componentname *cnp = ap->a_cnp;
2830 int flags = cnp->cn_flags;
2835 if (dvp->v_type != VDIR)
2838 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2839 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2842 error = vn_dir_check_exec(dvp, cnp);
2846 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2848 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2854 /* Implementation of the getcwd syscall. */
2856 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2862 buflen = uap->buflen;
2863 if (__predict_false(buflen < 2))
2865 if (buflen > MAXPATHLEN)
2866 buflen = MAXPATHLEN;
2868 buf = uma_zalloc(namei_zone, M_WAITOK);
2869 error = vn_getcwd(buf, &retbuf, &buflen);
2871 error = copyout(retbuf, uap->buf, buflen);
2872 uma_zfree(namei_zone, buf);
2877 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
2883 pwd = pwd_get_smr();
2884 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
2886 VFS_SMR_ASSERT_NOT_ENTERED();
2888 pwd = pwd_hold(curthread);
2889 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
2895 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2902 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2903 size_t size, int flags, enum uio_seg pathseg)
2905 struct nameidata nd;
2906 char *retbuf, *freebuf;
2911 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2912 pathseg, path, fd, &cap_fstat_rights, td);
2913 if ((error = namei(&nd)) != 0)
2915 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
2917 error = copyout(retbuf, buf, size);
2918 free(freebuf, M_TEMP);
2925 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2928 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2929 uap->flags, UIO_USERSPACE));
2933 * Retrieve the full filesystem path that correspond to a vnode from the name
2934 * cache (if available)
2937 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
2944 if (__predict_false(vp == NULL))
2947 buflen = MAXPATHLEN;
2948 buf = malloc(buflen, M_TEMP, M_WAITOK);
2950 pwd = pwd_get_smr();
2951 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
2952 VFS_SMR_ASSERT_NOT_ENTERED();
2954 pwd = pwd_hold(curthread);
2955 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
2966 * This function is similar to vn_fullpath, but it attempts to lookup the
2967 * pathname relative to the global root mount point. This is required for the
2968 * auditing sub-system, as audited pathnames must be absolute, relative to the
2969 * global root mount point.
2972 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
2978 if (__predict_false(vp == NULL))
2980 buflen = MAXPATHLEN;
2981 buf = malloc(buflen, M_TEMP, M_WAITOK);
2983 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
2984 VFS_SMR_ASSERT_NOT_ENTERED();
2986 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
2995 static struct namecache *
2996 vn_dd_from_dst(struct vnode *vp)
2998 struct namecache *ncp;
3000 cache_assert_vnode_locked(vp);
3001 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3002 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3009 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3012 struct namecache *ncp;
3016 vlp = VP2VNODELOCK(*vp);
3018 ncp = (*vp)->v_cache_dd;
3019 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3020 KASSERT(ncp == vn_dd_from_dst(*vp),
3021 ("%s: mismatch for dd entry (%p != %p)", __func__,
3022 ncp, vn_dd_from_dst(*vp)));
3024 ncp = vn_dd_from_dst(*vp);
3027 if (*buflen < ncp->nc_nlen) {
3030 counter_u64_add(numfullpathfail4, 1);
3032 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3036 *buflen -= ncp->nc_nlen;
3037 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3038 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3047 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3050 vn_lock(*vp, LK_SHARED | LK_RETRY);
3051 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3054 counter_u64_add(numfullpathfail2, 1);
3055 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3060 if (VN_IS_DOOMED(dvp)) {
3061 /* forced unmount */
3064 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3068 * *vp has its use count incremented still.
3075 * Resolve a directory to a pathname.
3077 * The name of the directory can always be found in the namecache or fetched
3078 * from the filesystem. There is also guaranteed to be only one parent, meaning
3079 * we can just follow vnodes up until we find the root.
3081 * The vnode must be referenced.
3084 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3085 size_t *len, size_t addend)
3087 #ifdef KDTRACE_HOOKS
3088 struct vnode *startvp = vp;
3093 bool slash_prefixed;
3095 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3096 VNPASS(vp->v_usecount > 0, vp);
3100 slash_prefixed = true;
3105 slash_prefixed = false;
3110 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3111 counter_u64_add(numfullpathcalls, 1);
3112 while (vp != rdir && vp != rootvnode) {
3114 * The vp vnode must be already fully constructed,
3115 * since it is either found in namecache or obtained
3116 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3117 * without obtaining the vnode lock.
3119 if ((vp->v_vflag & VV_ROOT) != 0) {
3120 vn_lock(vp, LK_RETRY | LK_SHARED);
3123 * With the vnode locked, check for races with
3124 * unmount, forced or not. Note that we
3125 * already verified that vp is not equal to
3126 * the root vnode, which means that
3127 * mnt_vnodecovered can be NULL only for the
3130 if (VN_IS_DOOMED(vp) ||
3131 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3132 vp1->v_mountedhere != vp->v_mount) {
3135 SDT_PROBE3(vfs, namecache, fullpath, return,
3145 if (vp->v_type != VDIR) {
3147 counter_u64_add(numfullpathfail1, 1);
3149 SDT_PROBE3(vfs, namecache, fullpath, return,
3153 error = vn_vptocnp(&vp, buf, &buflen);
3159 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3163 buf[--buflen] = '/';
3164 slash_prefixed = true;
3168 if (!slash_prefixed) {
3171 counter_u64_add(numfullpathfail4, 1);
3172 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3176 buf[--buflen] = '/';
3178 counter_u64_add(numfullpathfound, 1);
3181 *retbuf = buf + buflen;
3182 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3189 * Resolve an arbitrary vnode to a pathname.
3192 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3193 * resolve to a different path than the one used to find it
3194 * - namecache is not mandatory, meaning names are not guaranteed to be added
3195 * (in which case resolving fails)
3197 static void __inline
3198 cache_rev_failed_impl(int *reason, int line)
3203 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3206 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3207 char **retbuf, size_t *buflen, size_t addend)
3209 #ifdef KDTRACE_HOOKS
3210 struct vnode *startvp = vp;
3214 struct namecache *ncp;
3218 #ifdef KDTRACE_HOOKS
3221 seqc_t vp_seqc, tvp_seqc;
3224 VFS_SMR_ASSERT_ENTERED();
3226 if (!cache_fast_revlookup) {
3231 orig_buflen = *buflen;
3234 MPASS(*buflen >= 2);
3236 buf[*buflen] = '\0';
3239 if (vp == rdir || vp == rootvnode) {
3247 #ifdef KDTRACE_HOOKS
3251 ncp = NULL; /* for sdt probe down below */
3252 vp_seqc = vn_seqc_read_any(vp);
3253 if (seqc_in_modify(vp_seqc)) {
3254 cache_rev_failed(&reason);
3259 #ifdef KDTRACE_HOOKS
3262 if ((vp->v_vflag & VV_ROOT) != 0) {
3263 mp = atomic_load_ptr(&vp->v_mount);
3265 cache_rev_failed(&reason);
3268 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3269 tvp_seqc = vn_seqc_read_any(tvp);
3270 if (seqc_in_modify(tvp_seqc)) {
3271 cache_rev_failed(&reason);
3274 if (!vn_seqc_consistent(vp, vp_seqc)) {
3275 cache_rev_failed(&reason);
3282 ncp = atomic_load_ptr(&vp->v_cache_dd);
3284 cache_rev_failed(&reason);
3287 nc_flag = atomic_load_char(&ncp->nc_flag);
3288 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3289 cache_rev_failed(&reason);
3292 if (!cache_ncp_canuse(ncp)) {
3293 cache_rev_failed(&reason);
3296 if (ncp->nc_nlen >= *buflen) {
3297 cache_rev_failed(&reason);
3301 *buflen -= ncp->nc_nlen;
3302 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3306 tvp_seqc = vn_seqc_read_any(tvp);
3307 if (seqc_in_modify(tvp_seqc)) {
3308 cache_rev_failed(&reason);
3311 if (!vn_seqc_consistent(vp, vp_seqc)) {
3312 cache_rev_failed(&reason);
3317 if (vp == rdir || vp == rootvnode)
3322 *retbuf = buf + *buflen;
3323 *buflen = orig_buflen - *buflen + addend;
3324 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3328 *buflen = orig_buflen;
3329 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3335 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3338 size_t orig_buflen, addend;
3344 orig_buflen = *buflen;
3348 if (vp->v_type != VDIR) {
3350 buf[*buflen] = '\0';
3351 error = vn_vptocnp(&vp, buf, buflen);
3360 addend = orig_buflen - *buflen;
3363 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3367 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3369 * Since the namecache does not track hardlinks, the caller is expected to first
3370 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3372 * Then we have 2 cases:
3373 * - if the found vnode is a directory, the path can be constructed just by
3374 * following names up the chain
3375 * - otherwise we populate the buffer with the saved name and start resolving
3379 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3384 struct componentname *cnp;
3392 if (*buflen > MAXPATHLEN)
3393 *buflen = MAXPATHLEN;
3395 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3400 * Check for VBAD to work around the vp_crossmp bug in lookup().
3402 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3403 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3404 * If the type is VDIR (like in this very case) we can skip looking
3405 * at ni_dvp in the first place. However, since vnodes get passed here
3406 * unlocked the target may transition to doomed state (type == VBAD)
3407 * before we get to evaluate the condition. If this happens, we will
3408 * populate part of the buffer and descend to vn_fullpath_dir with
3409 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3411 * This should be atomic_load(&vp->v_type) but it is illegal to take
3412 * an address of a bit field, even if said field is sized to char.
3413 * Work around the problem by reading the value into a full-sized enum
3414 * and then re-reading it with atomic_load which will still prevent
3415 * the compiler from re-reading down the road.
3418 type = atomic_load_int(&type);
3425 addend = cnp->cn_namelen + 2;
3426 if (*buflen < addend) {
3431 tmpbuf = buf + *buflen;
3433 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3434 tmpbuf[addend - 1] = '\0';
3439 pwd = pwd_get_smr();
3440 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3442 VFS_SMR_ASSERT_NOT_ENTERED();
3444 pwd = pwd_hold(curthread);
3446 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3462 vn_dir_dd_ino(struct vnode *vp)
3464 struct namecache *ncp;
3469 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3470 vlp = VP2VNODELOCK(vp);
3472 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3473 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3476 vs = vget_prep(ddvp);
3478 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3487 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3489 struct namecache *ncp;
3493 vlp = VP2VNODELOCK(vp);
3495 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3496 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3502 l = min(ncp->nc_nlen, buflen - 1);
3503 memcpy(buf, ncp->nc_name, l);
3510 * This function updates path string to vnode's full global path
3511 * and checks the size of the new path string against the pathlen argument.
3513 * Requires a locked, referenced vnode.
3514 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3516 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3517 * because it falls back to the ".." lookup if the namecache lookup fails.
3520 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3523 struct nameidata nd;
3528 ASSERT_VOP_ELOCKED(vp, __func__);
3530 /* Construct global filesystem path from vp. */
3532 error = vn_fullpath_global(vp, &rpath, &fbuf);
3539 if (strlen(rpath) >= pathlen) {
3541 error = ENAMETOOLONG;
3546 * Re-lookup the vnode by path to detect a possible rename.
3547 * As a side effect, the vnode is relocked.
3548 * If vnode was renamed, return ENOENT.
3550 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3551 UIO_SYSSPACE, path, td);
3557 NDFREE(&nd, NDF_ONLY_PNBUF);
3561 strcpy(path, rpath);
3574 db_print_vpath(struct vnode *vp)
3577 while (vp != NULL) {
3578 db_printf("%p: ", vp);
3579 if (vp == rootvnode) {
3583 if (vp->v_vflag & VV_ROOT) {
3584 db_printf("<mount point>");
3585 vp = vp->v_mount->mnt_vnodecovered;
3587 struct namecache *ncp;
3591 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3594 for (i = 0; i < ncp->nc_nlen; i++)
3595 db_printf("%c", *ncn++);
3608 DB_SHOW_COMMAND(vpath, db_show_vpath)
3613 db_printf("usage: show vpath <struct vnode *>\n");
3617 vp = (struct vnode *)addr;
3623 static int cache_fast_lookup = 1;
3624 static char __read_frequently cache_fast_lookup_enabled = true;
3626 #define CACHE_FPL_FAILED -2020
3629 cache_fast_lookup_enabled_recalc(void)
3635 mac_on = mac_vnode_check_lookup_enabled();
3636 mac_on |= mac_vnode_check_readlink_enabled();
3641 lookup_flag = atomic_load_int(&cache_fast_lookup);
3642 if (lookup_flag && !mac_on) {
3643 atomic_store_char(&cache_fast_lookup_enabled, true);
3645 atomic_store_char(&cache_fast_lookup_enabled, false);
3650 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
3654 old = atomic_load_int(&cache_fast_lookup);
3655 error = sysctl_handle_int(oidp, arg1, arg2, req);
3656 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
3657 cache_fast_lookup_enabled_recalc();
3660 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
3661 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
3664 * Components of nameidata (or objects it can point to) which may
3665 * need restoring in case fast path lookup fails.
3667 struct nameidata_outer {
3672 struct nameidata_saved {
3680 struct cache_fpl_debug {
3686 struct nameidata *ndp;
3687 struct componentname *cnp;
3694 struct nameidata_saved snd;
3695 struct nameidata_outer snd_outer;
3697 enum cache_fpl_status status:8;
3702 struct cache_fpl_debug debug;
3706 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
3707 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
3708 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
3709 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
3710 static int cache_fplookup_preparse(struct cache_fpl *fpl);
3711 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
3712 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
3713 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
3714 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
3717 cache_fpl_cleanup_cnp(struct componentname *cnp)
3720 uma_zfree(namei_zone, cnp->cn_pnbuf);
3722 cnp->cn_pnbuf = NULL;
3723 cnp->cn_nameptr = NULL;
3727 static struct vnode *
3728 cache_fpl_handle_root(struct cache_fpl *fpl)
3730 struct nameidata *ndp;
3731 struct componentname *cnp;
3736 MPASS(*(cnp->cn_nameptr) == '/');
3738 cache_fpl_pathlen_dec(fpl);
3740 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
3743 cache_fpl_pathlen_dec(fpl);
3744 } while (*(cnp->cn_nameptr) == '/');
3747 return (ndp->ni_rootdir);
3751 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
3754 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
3755 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
3759 cache_fpl_checkpoint(struct cache_fpl *fpl)
3763 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3764 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
3769 cache_fpl_restore_partial(struct cache_fpl *fpl)
3772 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
3774 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
3779 cache_fpl_restore_abort(struct cache_fpl *fpl)
3782 cache_fpl_restore_partial(fpl);
3784 * It is 0 on entry by API contract.
3786 fpl->ndp->ni_resflags = 0;
3787 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
3788 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
3792 #define cache_fpl_smr_assert_entered(fpl) ({ \
3793 struct cache_fpl *_fpl = (fpl); \
3794 MPASS(_fpl->in_smr == true); \
3795 VFS_SMR_ASSERT_ENTERED(); \
3797 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
3798 struct cache_fpl *_fpl = (fpl); \
3799 MPASS(_fpl->in_smr == false); \
3800 VFS_SMR_ASSERT_NOT_ENTERED(); \
3803 cache_fpl_assert_status(struct cache_fpl *fpl)
3806 switch (fpl->status) {
3807 case CACHE_FPL_STATUS_UNSET:
3808 __assert_unreachable();
3810 case CACHE_FPL_STATUS_DESTROYED:
3811 case CACHE_FPL_STATUS_ABORTED:
3812 case CACHE_FPL_STATUS_PARTIAL:
3813 case CACHE_FPL_STATUS_HANDLED:
3818 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3819 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3820 #define cache_fpl_assert_status(fpl) do { } while (0)
3823 #define cache_fpl_smr_enter_initial(fpl) ({ \
3824 struct cache_fpl *_fpl = (fpl); \
3826 _fpl->in_smr = true; \
3829 #define cache_fpl_smr_enter(fpl) ({ \
3830 struct cache_fpl *_fpl = (fpl); \
3831 MPASS(_fpl->in_smr == false); \
3833 _fpl->in_smr = true; \
3836 #define cache_fpl_smr_exit(fpl) ({ \
3837 struct cache_fpl *_fpl = (fpl); \
3838 MPASS(_fpl->in_smr == true); \
3840 _fpl->in_smr = false; \
3844 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
3847 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3848 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3849 ("%s: converting to abort from %d at %d, set at %d\n",
3850 __func__, fpl->status, line, fpl->line));
3852 cache_fpl_smr_assert_not_entered(fpl);
3853 fpl->status = CACHE_FPL_STATUS_ABORTED;
3855 return (CACHE_FPL_FAILED);
3858 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
3860 static int __noinline
3861 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3863 struct nameidata *ndp;
3864 struct componentname *cnp;
3869 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3870 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3871 ("%s: converting to abort from %d at %d, set at %d\n",
3872 __func__, fpl->status, line, fpl->line));
3874 fpl->status = CACHE_FPL_STATUS_ABORTED;
3877 cache_fpl_smr_exit(fpl);
3878 cache_fpl_restore_abort(fpl);
3880 * Resolving symlinks overwrites data passed by the caller.
3883 if (ndp->ni_loopcnt > 0) {
3884 fpl->status = CACHE_FPL_STATUS_DESTROYED;
3885 cache_fpl_cleanup_cnp(cnp);
3887 return (CACHE_FPL_FAILED);
3890 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
3892 static int __noinline
3893 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3896 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3897 ("%s: setting to partial at %d, but already set to %d at %d\n",
3898 __func__, line, fpl->status, fpl->line));
3899 cache_fpl_smr_assert_entered(fpl);
3900 fpl->status = CACHE_FPL_STATUS_PARTIAL;
3902 return (cache_fplookup_partial_setup(fpl));
3905 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
3908 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
3911 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3912 ("%s: setting to handled at %d, but already set to %d at %d\n",
3913 __func__, line, fpl->status, fpl->line));
3914 cache_fpl_smr_assert_not_entered(fpl);
3915 fpl->status = CACHE_FPL_STATUS_HANDLED;
3920 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
3923 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
3926 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3927 ("%s: setting to handled at %d, but already set to %d at %d\n",
3928 __func__, line, fpl->status, fpl->line));
3930 MPASS(error != CACHE_FPL_FAILED);
3931 cache_fpl_smr_assert_not_entered(fpl);
3932 fpl->status = CACHE_FPL_STATUS_HANDLED;
3936 fpl->savename = false;
3940 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
3943 cache_fpl_terminated(struct cache_fpl *fpl)
3946 return (fpl->status != CACHE_FPL_STATUS_UNSET);
3949 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3950 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
3951 FAILIFEXISTS | FOLLOW | LOCKSHARED | SAVENAME | SAVESTART | WILLBEDIR | \
3952 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
3954 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3955 (ISDOTDOT | MAKEENTRY | ISLASTCN)
3957 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3958 "supported and internal flags overlap");
3961 cache_fpl_islastcn(struct nameidata *ndp)
3964 return (*ndp->ni_next == 0);
3968 cache_fpl_isdotdot(struct componentname *cnp)
3971 if (cnp->cn_namelen == 2 &&
3972 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3978 cache_can_fplookup(struct cache_fpl *fpl)
3980 struct nameidata *ndp;
3981 struct componentname *cnp;
3986 td = cnp->cn_thread;
3988 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3989 cache_fpl_aborted_early(fpl);
3992 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3993 cache_fpl_aborted_early(fpl);
3996 if (IN_CAPABILITY_MODE(td)) {
3997 cache_fpl_aborted_early(fpl);
4000 if (AUDITING_TD(td)) {
4001 cache_fpl_aborted_early(fpl);
4004 if (ndp->ni_startdir != NULL) {
4005 cache_fpl_aborted_early(fpl);
4012 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4014 struct nameidata *ndp;
4019 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4020 if (__predict_false(error != 0)) {
4021 return (cache_fpl_aborted(fpl));
4023 fpl->fsearch = fsearch;
4027 static int __noinline
4028 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4031 struct componentname *cnp;
4037 cache_fpl_smr_exit(fpl);
4038 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4039 return (cache_fpl_handled_error(fpl, ENOENT));
4041 return (cache_fpl_aborted(fpl));
4045 * The target vnode is not supported, prepare for the slow path to take over.
4047 static int __noinline
4048 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4050 struct nameidata *ndp;
4051 struct componentname *cnp;
4061 dvp_seqc = fpl->dvp_seqc;
4063 if (!pwd_hold_smr(pwd)) {
4064 return (cache_fpl_aborted(fpl));
4068 * Note that seqc is checked before the vnode is locked, so by
4069 * the time regular lookup gets to it it may have moved.
4071 * Ultimately this does not affect correctness, any lookup errors
4072 * are userspace racing with itself. It is guaranteed that any
4073 * path which ultimately gets found could also have been found
4074 * by regular lookup going all the way in absence of concurrent
4077 dvs = vget_prep_smr(dvp);
4078 cache_fpl_smr_exit(fpl);
4079 if (__predict_false(dvs == VGET_NONE)) {
4081 return (cache_fpl_aborted(fpl));
4084 vget_finish_ref(dvp, dvs);
4085 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4088 return (cache_fpl_aborted(fpl));
4091 cache_fpl_restore_partial(fpl);
4093 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4094 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4095 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4099 ndp->ni_startdir = dvp;
4100 cnp->cn_flags |= MAKEENTRY;
4101 if (cache_fpl_islastcn(ndp))
4102 cnp->cn_flags |= ISLASTCN;
4103 if (cache_fpl_isdotdot(cnp))
4104 cnp->cn_flags |= ISDOTDOT;
4107 * Skip potential extra slashes parsing did not take care of.
4108 * cache_fplookup_skip_slashes explains the mechanism.
4110 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4113 cache_fpl_pathlen_dec(fpl);
4114 } while (*(cnp->cn_nameptr) == '/');
4117 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4119 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4120 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4121 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4122 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4129 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4131 struct componentname *cnp;
4138 tvp_seqc = fpl->tvp_seqc;
4140 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4141 lkflags = LK_SHARED;
4142 if ((cnp->cn_flags & LOCKSHARED) == 0)
4143 lkflags = LK_EXCLUSIVE;
4144 error = vget_finish(tvp, lkflags, tvs);
4145 if (__predict_false(error != 0)) {
4146 return (cache_fpl_aborted(fpl));
4149 vget_finish_ref(tvp, tvs);
4152 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4153 if ((cnp->cn_flags & LOCKLEAF) != 0)
4157 return (cache_fpl_aborted(fpl));
4160 return (cache_fpl_handled(fpl));
4164 * They want to possibly modify the state of the namecache.
4166 static int __noinline
4167 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4169 struct nameidata *ndp;
4170 struct componentname *cnp;
4172 struct vnode *dvp, *tvp;
4181 dvp_seqc = fpl->dvp_seqc;
4183 MPASS(*(cnp->cn_nameptr) != '/');
4184 MPASS(cache_fpl_islastcn(ndp));
4185 if ((cnp->cn_flags & LOCKPARENT) == 0)
4186 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4187 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4188 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4189 cnp->cn_nameiop == RENAME);
4190 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4191 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4193 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4194 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4197 mp = atomic_load_ptr(&dvp->v_mount);
4198 if (__predict_false(mp == NULL)) {
4199 return (cache_fpl_aborted(fpl));
4202 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4203 cache_fpl_smr_exit(fpl);
4205 * Original code keeps not checking for CREATE which
4206 * might be a bug. For now let the old lookup decide.
4208 if (cnp->cn_nameiop == CREATE) {
4209 return (cache_fpl_aborted(fpl));
4211 return (cache_fpl_handled_error(fpl, EROFS));
4214 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4215 cache_fpl_smr_exit(fpl);
4216 return (cache_fpl_handled_error(fpl, EEXIST));
4220 * Secure access to dvp; check cache_fplookup_partial_setup for
4223 * XXX At least UFS requires its lookup routine to be called for
4224 * the last path component, which leads to some level of complication
4226 * - the target routine always locks the target vnode, but our caller
4227 * may not need it locked
4228 * - some of the VOP machinery asserts that the parent is locked, which
4229 * once more may be not required
4231 * TODO: add a flag for filesystems which don't need this.
4233 dvs = vget_prep_smr(dvp);
4234 cache_fpl_smr_exit(fpl);
4235 if (__predict_false(dvs == VGET_NONE)) {
4236 return (cache_fpl_aborted(fpl));
4239 vget_finish_ref(dvp, dvs);
4240 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4242 return (cache_fpl_aborted(fpl));
4245 error = vn_lock(dvp, LK_EXCLUSIVE);
4246 if (__predict_false(error != 0)) {
4248 return (cache_fpl_aborted(fpl));
4252 cnp->cn_flags |= ISLASTCN;
4254 cnp->cn_flags |= MAKEENTRY;
4255 if (cache_fpl_isdotdot(cnp))
4256 cnp->cn_flags |= ISDOTDOT;
4257 cnp->cn_lkflags = LK_EXCLUSIVE;
4258 error = VOP_LOOKUP(dvp, &tvp, cnp);
4266 return (cache_fpl_handled_error(fpl, error));
4269 return (cache_fpl_aborted(fpl));
4273 fpl->savename = (cnp->cn_flags & SAVENAME) != 0;
4276 if ((cnp->cn_flags & SAVESTART) != 0) {
4277 ndp->ni_startdir = dvp;
4278 vrefact(ndp->ni_startdir);
4279 cnp->cn_flags |= SAVENAME;
4280 fpl->savename = true;
4282 MPASS(error == EJUSTRETURN);
4283 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4286 return (cache_fpl_handled(fpl));
4290 * There are very hairy corner cases concerning various flag combinations
4291 * and locking state. In particular here we only hold one lock instead of
4294 * Skip the complexity as it is of no significance for normal workloads.
4296 if (__predict_false(tvp == dvp)) {
4299 return (cache_fpl_aborted(fpl));
4303 * Check if the target is either a symlink or a mount point.
4304 * Since we expect this to be the terminal vnode it should
4305 * almost never be true.
4307 if (__predict_false(tvp->v_type == VLNK || cache_fplookup_is_mp(fpl))) {
4310 return (cache_fpl_aborted(fpl));
4313 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4316 return (cache_fpl_handled_error(fpl, EEXIST));
4319 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4323 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4327 if ((cnp->cn_flags & SAVESTART) != 0) {
4328 ndp->ni_startdir = dvp;
4329 vrefact(ndp->ni_startdir);
4330 cnp->cn_flags |= SAVENAME;
4331 fpl->savename = true;
4334 return (cache_fpl_handled(fpl));
4337 static int __noinline
4338 cache_fplookup_modifying(struct cache_fpl *fpl)
4340 struct nameidata *ndp;
4344 if (!cache_fpl_islastcn(ndp)) {
4345 return (cache_fpl_partial(fpl));
4347 return (cache_fplookup_final_modifying(fpl));
4350 static int __noinline
4351 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4353 struct componentname *cnp;
4354 enum vgetstate dvs, tvs;
4355 struct vnode *dvp, *tvp;
4361 dvp_seqc = fpl->dvp_seqc;
4364 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4367 * This is less efficient than it can be for simplicity.
4369 dvs = vget_prep_smr(dvp);
4370 if (__predict_false(dvs == VGET_NONE)) {
4371 return (cache_fpl_aborted(fpl));
4373 tvs = vget_prep_smr(tvp);
4374 if (__predict_false(tvs == VGET_NONE)) {
4375 cache_fpl_smr_exit(fpl);
4376 vget_abort(dvp, dvs);
4377 return (cache_fpl_aborted(fpl));
4380 cache_fpl_smr_exit(fpl);
4382 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4383 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4384 if (__predict_false(error != 0)) {
4385 vget_abort(tvp, tvs);
4386 return (cache_fpl_aborted(fpl));
4389 vget_finish_ref(dvp, dvs);
4392 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4393 vget_abort(tvp, tvs);
4394 if ((cnp->cn_flags & LOCKPARENT) != 0)
4398 return (cache_fpl_aborted(fpl));
4401 error = cache_fplookup_final_child(fpl, tvs);
4402 if (__predict_false(error != 0)) {
4403 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
4404 if ((cnp->cn_flags & LOCKPARENT) != 0)
4411 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4416 cache_fplookup_final(struct cache_fpl *fpl)
4418 struct componentname *cnp;
4420 struct vnode *dvp, *tvp;
4425 dvp_seqc = fpl->dvp_seqc;
4428 MPASS(*(cnp->cn_nameptr) != '/');
4430 if (cnp->cn_nameiop != LOOKUP) {
4431 return (cache_fplookup_final_modifying(fpl));
4434 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4435 return (cache_fplookup_final_withparent(fpl));
4437 tvs = vget_prep_smr(tvp);
4438 if (__predict_false(tvs == VGET_NONE)) {
4439 return (cache_fpl_partial(fpl));
4442 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4443 cache_fpl_smr_exit(fpl);
4444 vget_abort(tvp, tvs);
4445 return (cache_fpl_aborted(fpl));
4448 cache_fpl_smr_exit(fpl);
4449 return (cache_fplookup_final_child(fpl, tvs));
4453 * Comment from locked lookup:
4454 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4455 * directory, e.g. like "/." or ".".
4457 static int __noinline
4458 cache_fplookup_degenerate(struct cache_fpl *fpl)
4460 struct componentname *cnp;
4465 fpl->tvp = fpl->dvp;
4466 fpl->tvp_seqc = fpl->dvp_seqc;
4471 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4472 cache_fpl_smr_exit(fpl);
4473 return (cache_fpl_handled_error(fpl, EISDIR));
4476 MPASS((cnp->cn_flags & SAVESTART) == 0);
4478 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4479 return (cache_fplookup_final_withparent(fpl));
4482 dvs = vget_prep_smr(dvp);
4483 cache_fpl_smr_exit(fpl);
4484 if (__predict_false(dvs == VGET_NONE)) {
4485 return (cache_fpl_aborted(fpl));
4488 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4489 lkflags = LK_SHARED;
4490 if ((cnp->cn_flags & LOCKSHARED) == 0)
4491 lkflags = LK_EXCLUSIVE;
4492 error = vget_finish(dvp, lkflags, dvs);
4493 if (__predict_false(error != 0)) {
4494 return (cache_fpl_aborted(fpl));
4497 vget_finish_ref(dvp, dvs);
4499 return (cache_fpl_handled(fpl));
4502 static int __noinline
4503 cache_fplookup_noentry(struct cache_fpl *fpl)
4505 struct nameidata *ndp;
4506 struct componentname *cnp;
4508 struct vnode *dvp, *tvp;
4516 dvp_seqc = fpl->dvp_seqc;
4518 MPASS(*(cnp->cn_nameptr) != '/');
4519 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4520 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4521 MPASS(!cache_fpl_isdotdot(cnp));
4524 * Hack: delayed name len checking.
4526 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4527 cache_fpl_smr_exit(fpl);
4528 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
4531 if (cnp->cn_nameiop != LOOKUP) {
4533 return (cache_fplookup_modifying(fpl));
4536 MPASS((cnp->cn_flags & SAVESTART) == 0);
4539 * Only try to fill in the component if it is the last one,
4540 * otherwise not only there may be several to handle but the
4541 * walk may be complicated.
4543 if (!cache_fpl_islastcn(ndp)) {
4544 return (cache_fpl_partial(fpl));
4548 * Secure access to dvp; check cache_fplookup_partial_setup for
4551 dvs = vget_prep_smr(dvp);
4552 cache_fpl_smr_exit(fpl);
4553 if (__predict_false(dvs == VGET_NONE)) {
4554 return (cache_fpl_aborted(fpl));
4557 vget_finish_ref(dvp, dvs);
4558 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4560 return (cache_fpl_aborted(fpl));
4563 error = vn_lock(dvp, LK_SHARED);
4564 if (__predict_false(error != 0)) {
4566 return (cache_fpl_aborted(fpl));
4571 * TODO: provide variants which don't require locking either vnode.
4573 cnp->cn_flags |= ISLASTCN;
4574 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4576 cnp->cn_flags |= MAKEENTRY;
4577 cnp->cn_lkflags = LK_SHARED;
4578 if ((cnp->cn_flags & LOCKSHARED) == 0) {
4579 cnp->cn_lkflags = LK_EXCLUSIVE;
4581 error = VOP_LOOKUP(dvp, &tvp, cnp);
4589 return (cache_fpl_handled_error(fpl, error));
4592 return (cache_fpl_aborted(fpl));
4596 if (!fpl->savename) {
4597 MPASS((cnp->cn_flags & SAVENAME) == 0);
4601 MPASS(error == EJUSTRETURN);
4602 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4604 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4607 return (cache_fpl_handled(fpl));
4610 if (__predict_false(tvp->v_type == VLNK || cache_fplookup_is_mp(fpl))) {
4613 return (cache_fpl_aborted(fpl));
4616 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4620 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4622 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4625 return (cache_fpl_handled(fpl));
4628 static int __noinline
4629 cache_fplookup_dot(struct cache_fpl *fpl)
4633 MPASS(!seqc_in_modify(fpl->dvp_seqc));
4635 * Just re-assign the value. seqc will be checked later for the first
4636 * non-dot path component in line and/or before deciding to return the
4639 fpl->tvp = fpl->dvp;
4640 fpl->tvp_seqc = fpl->dvp_seqc;
4642 counter_u64_add(dothits, 1);
4643 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
4646 if (cache_fplookup_is_mp(fpl)) {
4647 error = cache_fplookup_cross_mount(fpl);
4652 static int __noinline
4653 cache_fplookup_dotdot(struct cache_fpl *fpl)
4655 struct nameidata *ndp;
4656 struct componentname *cnp;
4657 struct namecache *ncp;
4666 MPASS(cache_fpl_isdotdot(cnp));
4669 * XXX this is racy the same way regular lookup is
4671 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
4673 if (dvp == pr->pr_root)
4676 if (dvp == ndp->ni_rootdir ||
4677 dvp == ndp->ni_topdir ||
4681 fpl->tvp_seqc = vn_seqc_read_any(dvp);
4682 if (seqc_in_modify(fpl->tvp_seqc)) {
4683 return (cache_fpl_aborted(fpl));
4688 if ((dvp->v_vflag & VV_ROOT) != 0) {
4691 * The opposite of climb mount is needed here.
4693 return (cache_fpl_aborted(fpl));
4696 ncp = atomic_load_ptr(&dvp->v_cache_dd);
4698 return (cache_fpl_aborted(fpl));
4701 nc_flag = atomic_load_char(&ncp->nc_flag);
4702 if ((nc_flag & NCF_ISDOTDOT) != 0) {
4703 if ((nc_flag & NCF_NEGATIVE) != 0)
4704 return (cache_fpl_aborted(fpl));
4705 fpl->tvp = ncp->nc_vp;
4707 fpl->tvp = ncp->nc_dvp;
4710 if (!cache_ncp_canuse(ncp)) {
4711 return (cache_fpl_aborted(fpl));
4714 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
4715 if (seqc_in_modify(fpl->tvp_seqc)) {
4716 return (cache_fpl_partial(fpl));
4719 counter_u64_add(dotdothits, 1);
4723 static int __noinline
4724 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
4729 nc_flag = atomic_load_char(&ncp->nc_flag);
4730 MPASS((nc_flag & NCF_NEGATIVE) != 0);
4732 * If they want to create an entry we need to replace this one.
4734 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
4736 return (cache_fplookup_modifying(fpl));
4738 neg_promote = cache_neg_hit_prep(ncp);
4739 if (!cache_fpl_neg_ncp_canuse(ncp)) {
4740 cache_neg_hit_abort(ncp);
4741 return (cache_fpl_partial(fpl));
4744 return (cache_fplookup_negative_promote(fpl, ncp, hash));
4746 cache_neg_hit_finish(ncp);
4747 cache_fpl_smr_exit(fpl);
4748 return (cache_fpl_handled_error(fpl, ENOENT));
4752 * Resolve a symlink. Called by filesystem-specific routines.
4755 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
4758 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
4760 struct nameidata *ndp;
4761 struct componentname *cnp;
4766 if (__predict_false(len == 0)) {
4770 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
4772 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4773 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4774 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4775 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4779 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
4780 return (ENAMETOOLONG);
4783 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
4787 if (ndp->ni_pathlen > 1) {
4788 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
4790 cnp->cn_pnbuf[len] = '\0';
4792 bcopy(string, cnp->cn_pnbuf, len);
4794 ndp->ni_pathlen += len;
4795 cache_fpl_pathlen_add(fpl, len);
4796 cnp->cn_nameptr = cnp->cn_pnbuf;
4797 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
4802 static int __noinline
4803 cache_fplookup_symlink(struct cache_fpl *fpl)
4805 struct nameidata *ndp;
4806 struct componentname *cnp;
4807 struct vnode *dvp, *tvp;
4815 if (cache_fpl_islastcn(ndp)) {
4816 if ((cnp->cn_flags & FOLLOW) == 0) {
4817 return (cache_fplookup_final(fpl));
4821 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
4822 if (__predict_false(error != 0)) {
4825 return (cache_fpl_partial(fpl));
4829 cache_fpl_smr_exit(fpl);
4830 return (cache_fpl_handled_error(fpl, error));
4832 return (cache_fpl_aborted(fpl));
4836 if (*(cnp->cn_nameptr) == '/') {
4837 fpl->dvp = cache_fpl_handle_root(fpl);
4838 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
4839 if (seqc_in_modify(fpl->dvp_seqc)) {
4840 return (cache_fpl_aborted(fpl));
4844 return (cache_fplookup_preparse(fpl));
4848 cache_fplookup_next(struct cache_fpl *fpl)
4850 struct componentname *cnp;
4851 struct namecache *ncp;
4852 struct vnode *dvp, *tvp;
4860 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
4861 if (cnp->cn_namelen == 1) {
4862 return (cache_fplookup_dot(fpl));
4864 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
4865 return (cache_fplookup_dotdot(fpl));
4869 MPASS(!cache_fpl_isdotdot(cnp));
4871 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
4873 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
4874 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
4875 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
4879 if (__predict_false(ncp == NULL)) {
4880 if (cnp->cn_nameptr[0] == '/') {
4881 return (cache_fplookup_skip_slashes(fpl));
4883 return (cache_fplookup_noentry(fpl));
4886 tvp = atomic_load_ptr(&ncp->nc_vp);
4887 nc_flag = atomic_load_char(&ncp->nc_flag);
4888 if ((nc_flag & NCF_NEGATIVE) != 0) {
4889 return (cache_fplookup_neg(fpl, ncp, hash));
4892 if (!cache_ncp_canuse(ncp)) {
4893 return (cache_fpl_partial(fpl));
4897 fpl->tvp_seqc = vn_seqc_read_any(tvp);
4898 if (seqc_in_modify(fpl->tvp_seqc)) {
4899 return (cache_fpl_partial(fpl));
4902 counter_u64_add(numposhits, 1);
4903 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
4906 if (cache_fplookup_is_mp(fpl)) {
4907 error = cache_fplookup_cross_mount(fpl);
4913 cache_fplookup_mp_supported(struct mount *mp)
4917 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4923 * Walk up the mount stack (if any).
4925 * Correctness is provided in the following ways:
4926 * - all vnodes are protected from freeing with SMR
4927 * - struct mount objects are type stable making them always safe to access
4928 * - stability of the particular mount is provided by busying it
4929 * - relationship between the vnode which is mounted on and the mount is
4930 * verified with the vnode sequence counter after busying
4931 * - association between root vnode of the mount and the mount is protected
4934 * From that point on we can read the sequence counter of the root vnode
4935 * and get the next mount on the stack (if any) using the same protection.
4937 * By the end of successful walk we are guaranteed the reached state was
4938 * indeed present at least at some point which matches the regular lookup.
4940 static int __noinline
4941 cache_fplookup_climb_mount(struct cache_fpl *fpl)
4943 struct mount *mp, *prev_mp;
4944 struct mount_pcpu *mpcpu, *prev_mpcpu;
4949 vp_seqc = fpl->tvp_seqc;
4951 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
4952 mp = atomic_load_ptr(&vp->v_mountedhere);
4953 if (__predict_false(mp == NULL)) {
4959 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
4960 if (prev_mp != NULL)
4961 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
4962 return (cache_fpl_partial(fpl));
4964 if (prev_mp != NULL)
4965 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
4966 if (!vn_seqc_consistent(vp, vp_seqc)) {
4967 vfs_op_thread_exit_crit(mp, mpcpu);
4968 return (cache_fpl_partial(fpl));
4970 if (!cache_fplookup_mp_supported(mp)) {
4971 vfs_op_thread_exit_crit(mp, mpcpu);
4972 return (cache_fpl_partial(fpl));
4974 vp = atomic_load_ptr(&mp->mnt_rootvnode);
4976 vfs_op_thread_exit_crit(mp, mpcpu);
4977 return (cache_fpl_partial(fpl));
4979 vp_seqc = vn_seqc_read_any(vp);
4980 if (seqc_in_modify(vp_seqc)) {
4981 vfs_op_thread_exit_crit(mp, mpcpu);
4982 return (cache_fpl_partial(fpl));
4986 mp = atomic_load_ptr(&vp->v_mountedhere);
4991 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
4993 fpl->tvp_seqc = vp_seqc;
4997 static int __noinline
4998 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5001 struct mount_pcpu *mpcpu;
5006 vp_seqc = fpl->tvp_seqc;
5008 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5009 mp = atomic_load_ptr(&vp->v_mountedhere);
5010 if (__predict_false(mp == NULL)) {
5014 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5015 return (cache_fpl_partial(fpl));
5017 if (!vn_seqc_consistent(vp, vp_seqc)) {
5018 vfs_op_thread_exit_crit(mp, mpcpu);
5019 return (cache_fpl_partial(fpl));
5021 if (!cache_fplookup_mp_supported(mp)) {
5022 vfs_op_thread_exit_crit(mp, mpcpu);
5023 return (cache_fpl_partial(fpl));
5025 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5026 if (__predict_false(vp == NULL)) {
5027 vfs_op_thread_exit_crit(mp, mpcpu);
5028 return (cache_fpl_partial(fpl));
5030 vp_seqc = vn_seqc_read_any(vp);
5031 vfs_op_thread_exit_crit(mp, mpcpu);
5032 if (seqc_in_modify(vp_seqc)) {
5033 return (cache_fpl_partial(fpl));
5035 mp = atomic_load_ptr(&vp->v_mountedhere);
5036 if (__predict_false(mp != NULL)) {
5038 * There are possibly more mount points on top.
5039 * Normally this does not happen so for simplicity just start
5042 return (cache_fplookup_climb_mount(fpl));
5046 fpl->tvp_seqc = vp_seqc;
5051 * Check if a vnode is mounted on.
5054 cache_fplookup_is_mp(struct cache_fpl *fpl)
5059 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5065 * The code was originally copy-pasted from regular lookup and despite
5066 * clean ups leaves performance on the table. Any modifications here
5067 * must take into account that in case off fallback the resulting
5068 * nameidata state has to be compatible with the original.
5072 * Debug ni_pathlen tracking.
5076 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5079 cache_fpl_pathlen_sub(fpl, 1);
5083 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5086 cache_fpl_pathlen_add(fpl, 1);
5090 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5093 fpl->debug.ni_pathlen += n;
5094 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5095 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5099 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5102 fpl->debug.ni_pathlen -= n;
5103 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5104 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5107 static void __always_inline
5108 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5112 static void __always_inline
5113 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5118 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5123 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5128 static int __always_inline
5129 cache_fplookup_preparse(struct cache_fpl *fpl)
5131 struct componentname *cnp;
5135 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
5136 return (cache_fplookup_degenerate(fpl));
5140 * By this point the shortest possible pathname is one character + nul
5141 * terminator, hence 2.
5143 KASSERT(fpl->debug.ni_pathlen >= 2, ("%s: pathlen %zu\n", __func__,
5144 fpl->debug.ni_pathlen));
5145 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 2] == fpl->nulchar - 1,
5146 ("%s: mismatch on string (%p != %p) [%s]\n", __func__,
5147 &cnp->cn_nameptr[fpl->debug.ni_pathlen - 2], fpl->nulchar - 1,
5149 if (__predict_false(*(fpl->nulchar - 1) == '/')) {
5152 * Regular lookup performs the following:
5153 * *ndp->ni_next = '\0';
5154 * cnp->cn_flags |= TRAILINGSLASH;
5156 * Which is problematic since it modifies data read
5157 * from userspace. Then if fast path lookup was to
5158 * abort we would have to either restore it or convey
5159 * the flag. Since this is a corner case just ignore
5160 * it for simplicity.
5162 return (cache_fpl_aborted(fpl));
5168 cache_fplookup_parse(struct cache_fpl *fpl)
5170 struct nameidata *ndp;
5171 struct componentname *cnp;
5178 * Find the end of this path component, it is either / or nul.
5180 * Store / as a temporary sentinel so that we only have one character
5181 * to test for. Pathnames tend to be short so this should not be
5182 * resulting in cache misses.
5184 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5185 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5186 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5187 fpl->nulchar, cnp->cn_pnbuf));
5188 KASSERT(*fpl->nulchar == '\0',
5189 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5191 *fpl->nulchar = '/';
5192 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5193 KASSERT(*cp != '\0',
5194 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5198 *fpl->nulchar = '\0';
5200 cnp->cn_namelen = cp - cnp->cn_nameptr;
5201 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5203 * Hack: we have to check if the found path component's length exceeds
5204 * NAME_MAX. However, the condition is very rarely true and check can
5205 * be elided in the common case -- if an entry was found in the cache,
5206 * then it could not have been too long to begin with.
5212 * Code below is only here to assure compatibility with regular lookup.
5213 * It covers handling of trailing slashes and names like "/", both of
5214 * which of can be taken care of upfront which lockless lookup does
5215 * in cache_fplookup_preparse. Regular lookup performs these for each
5218 while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
5221 panic("%s: ran into TRAILINGSLASH handling from [%s]\n",
5222 __func__, cnp->cn_pnbuf);
5226 if (cnp->cn_nameptr[0] == '\0') {
5227 panic("%s: ran into degenerate name from [%s]\n", __func__, cnp->cn_pnbuf);
5234 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5236 struct nameidata *ndp;
5237 struct componentname *cnp;
5242 cnp->cn_nameptr = ndp->ni_next;
5243 KASSERT(*(cnp->cn_nameptr) == '/',
5244 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5245 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5247 cache_fpl_pathlen_dec(fpl);
5251 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5253 * Lockless lookup tries to elide checking for spurious slashes and should they
5254 * be present is guaranteed to fail to find an entry. In this case the caller
5255 * must check if the name starts with a slash and this call routine. It is
5256 * going to fast forward across the spurious slashes and set the state up for
5259 static int __noinline
5260 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5262 struct nameidata *ndp;
5263 struct componentname *cnp;
5268 MPASS(*(cnp->cn_nameptr) == '/');
5271 cache_fpl_pathlen_dec(fpl);
5272 } while (*(cnp->cn_nameptr) == '/');
5275 * Go back to one slash so that cache_fplookup_parse_advance has
5276 * something to skip.
5279 cache_fpl_pathlen_inc(fpl);
5282 * cache_fplookup_parse_advance starts from ndp->ni_next
5284 ndp->ni_next = cnp->cn_nameptr;
5287 * See cache_fplookup_dot.
5289 fpl->tvp = fpl->dvp;
5290 fpl->tvp_seqc = fpl->dvp_seqc;
5296 * See the API contract for VOP_FPLOOKUP_VEXEC.
5298 static int __noinline
5299 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5301 struct componentname *cnp;
5307 dvp_seqc = fpl->dvp_seqc;
5310 * Hack: delayed name len checking.
5312 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5313 cache_fpl_smr_exit(fpl);
5314 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5318 * Hack: they may be looking up foo/bar, where foo is a
5319 * regular file. In such a case we need to turn ENOTDIR,
5320 * but we may happen to get here with a different error.
5322 if (dvp->v_type != VDIR) {
5324 * The check here is predominantly to catch
5325 * EOPNOTSUPP from dead_vnodeops. If the vnode
5326 * gets doomed past this point it is going to
5327 * fail seqc verification.
5329 if (VN_IS_DOOMED(dvp)) {
5330 return (cache_fpl_aborted(fpl));
5336 * Hack: handle O_SEARCH.
5338 * Open Group Base Specifications Issue 7, 2018 edition states:
5339 * If the access mode of the open file description associated with the
5340 * file descriptor is not O_SEARCH, the function shall check whether
5341 * directory searches are permitted using the current permissions of
5342 * the directory underlying the file descriptor. If the access mode is
5343 * O_SEARCH, the function shall not perform the check.
5345 * Regular lookup tests for the NOEXECCHECK flag for every path
5346 * component to decide whether to do the permission check. However,
5347 * since most lookups never have the flag (and when they do it is only
5348 * present for the first path component), lockless lookup only acts on
5349 * it if there is a permission problem. Here the flag is represented
5350 * with a boolean so that we don't have to clear it on the way out.
5352 * For simplicity this always aborts.
5353 * TODO: check if this is the first lookup and ignore the permission
5354 * problem. Note the flag has to survive fallback (if it happens to be
5358 return (cache_fpl_aborted(fpl));
5363 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5364 error = cache_fpl_aborted(fpl);
5366 cache_fpl_partial(fpl);
5370 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5371 error = cache_fpl_aborted(fpl);
5373 cache_fpl_smr_exit(fpl);
5374 cache_fpl_handled_error(fpl, error);
5382 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
5384 struct nameidata *ndp;
5385 struct componentname *cnp;
5392 cache_fpl_checkpoint(fpl);
5395 * The vnode at hand is almost always stable, skip checking for it.
5396 * Worst case this postpones the check towards the end of the iteration
5400 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
5402 mp = atomic_load_ptr(&dvp->v_mount);
5403 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
5404 return (cache_fpl_aborted(fpl));
5407 error = cache_fplookup_preparse(fpl);
5408 if (__predict_false(cache_fpl_terminated(fpl))) {
5413 error = cache_fplookup_parse(fpl);
5414 if (__predict_false(error != 0)) {
5418 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
5419 if (__predict_false(error != 0)) {
5420 error = cache_fplookup_failed_vexec(fpl, error);
5424 error = cache_fplookup_next(fpl);
5425 if (__predict_false(cache_fpl_terminated(fpl))) {
5429 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
5431 if (fpl->tvp->v_type == VLNK) {
5432 error = cache_fplookup_symlink(fpl);
5433 if (cache_fpl_terminated(fpl)) {
5437 if (cache_fpl_islastcn(ndp)) {
5438 error = cache_fplookup_final(fpl);
5442 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
5443 error = cache_fpl_aborted(fpl);
5447 fpl->dvp = fpl->tvp;
5448 fpl->dvp_seqc = fpl->tvp_seqc;
5449 cache_fplookup_parse_advance(fpl);
5452 cache_fpl_checkpoint(fpl);
5459 * Fast path lookup protected with SMR and sequence counters.
5461 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
5463 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
5466 * Traditional vnode lookup conceptually looks like this:
5472 * vn_unlock(current);
5479 * Each jump to the next vnode is safe memory-wise and atomic with respect to
5480 * any modifications thanks to holding respective locks.
5482 * The same guarantee can be provided with a combination of safe memory
5483 * reclamation and sequence counters instead. If all operations which affect
5484 * the relationship between the current vnode and the one we are looking for
5485 * also modify the counter, we can verify whether all the conditions held as
5486 * we made the jump. This includes things like permissions, mount points etc.
5487 * Counter modification is provided by enclosing relevant places in
5488 * vn_seqc_write_begin()/end() calls.
5490 * Thus this translates to:
5493 * dvp_seqc = seqc_read_any(dvp);
5494 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
5498 * tvp_seqc = seqc_read_any(tvp);
5499 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
5501 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
5503 * dvp = tvp; // we know nothing of importance has changed
5504 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
5508 * vget(); // secure the vnode
5509 * if (!seqc_consistent(tvp, tvp_seqc) // final check
5511 * // at this point we know nothing has changed for any parent<->child pair
5512 * // as they were crossed during the lookup, meaning we matched the guarantee
5513 * // of the locked variant
5516 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
5517 * - they are called while within vfs_smr protection which they must never exit
5518 * - EAGAIN can be returned to denote checking could not be performed, it is
5519 * always valid to return it
5520 * - if the sequence counter has not changed the result must be valid
5521 * - if the sequence counter has changed both false positives and false negatives
5522 * are permitted (since the result will be rejected later)
5523 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
5525 * Caveats to watch out for:
5526 * - vnodes are passed unlocked and unreferenced with nothing stopping
5527 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
5528 * to use atomic_load_ptr to fetch it.
5529 * - the aforementioned object can also get freed, meaning absent other means it
5530 * should be protected with vfs_smr
5531 * - either safely checking permissions as they are modified or guaranteeing
5532 * their stability is left to the routine
5535 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
5538 struct cache_fpl fpl;
5541 struct componentname *cnp;
5544 fpl.status = CACHE_FPL_STATUS_UNSET;
5547 fpl.cnp = cnp = &ndp->ni_cnd;
5548 MPASS(ndp->ni_lcf == 0);
5549 MPASS(curthread == cnp->cn_thread);
5550 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
5551 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
5553 if ((cnp->cn_flags & SAVESTART) != 0) {
5554 MPASS(cnp->cn_nameiop != LOOKUP);
5556 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
5558 if (__predict_false(!cache_can_fplookup(&fpl))) {
5559 *status = fpl.status;
5560 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
5561 return (EOPNOTSUPP);
5564 cache_fpl_checkpoint_outer(&fpl);
5566 cache_fpl_smr_enter_initial(&fpl);
5568 fpl.debug.ni_pathlen = ndp->ni_pathlen;
5570 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5571 fpl.fsearch = false;
5572 fpl.savename = (cnp->cn_flags & SAVENAME) != 0;
5574 pwd = pwd_get_smr();
5576 ndp->ni_rootdir = pwd->pwd_rdir;
5577 ndp->ni_topdir = pwd->pwd_jdir;
5579 if (cnp->cn_pnbuf[0] == '/') {
5580 dvp = cache_fpl_handle_root(&fpl);
5581 MPASS(ndp->ni_resflags == 0);
5582 ndp->ni_resflags = NIRES_ABS;
5584 if (ndp->ni_dirfd == AT_FDCWD) {
5585 dvp = pwd->pwd_cdir;
5587 error = cache_fplookup_dirfd(&fpl, &dvp);
5588 if (__predict_false(error != 0)) {
5594 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
5595 error = cache_fplookup_impl(dvp, &fpl);
5597 cache_fpl_smr_assert_not_entered(&fpl);
5598 cache_fpl_assert_status(&fpl);
5599 *status = fpl.status;
5600 if (SDT_PROBES_ENABLED()) {
5601 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
5602 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
5603 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
5607 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
5608 MPASS(error != CACHE_FPL_FAILED);
5610 MPASS(fpl.dvp == NULL);
5611 MPASS(fpl.tvp == NULL);
5612 MPASS(fpl.savename == false);
5614 ndp->ni_dvp = fpl.dvp;
5615 ndp->ni_vp = fpl.tvp;
5617 cnp->cn_flags |= HASBUF;
5619 cache_fpl_cleanup_cnp(cnp);