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 *",
125 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
127 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
128 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
129 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
132 * This structure describes the elements in the cache of recent
133 * names looked up by namei.
139 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
140 "the state must fit in a union with a pointer without growing it");
143 LIST_ENTRY(namecache) nc_src; /* source vnode list */
144 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
145 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
146 struct vnode *nc_dvp; /* vnode of parent of name */
148 struct vnode *nu_vp; /* vnode the name refers to */
149 struct negstate nu_neg;/* negative entry state */
151 u_char nc_flag; /* flag bits */
152 u_char nc_nlen; /* length of name */
153 char nc_name[0]; /* segment name + nul */
157 * struct namecache_ts repeats struct namecache layout up to the
159 * struct namecache_ts is used in place of struct namecache when time(s) need
160 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
161 * both a non-dotdot directory name plus dotdot for the directory's
164 * See below for alignment requirement.
166 struct namecache_ts {
167 struct timespec nc_time; /* timespec provided by fs */
168 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
169 int nc_ticks; /* ticks value when entry was added */
171 struct namecache nc_nc;
174 TAILQ_HEAD(cache_freebatch, namecache);
177 * At least mips n32 performs 64-bit accesses to timespec as found
178 * in namecache_ts and requires them to be aligned. Since others
179 * may be in the same spot suffer a little bit and enforce the
180 * alignment for everyone. Note this is a nop for 64-bit platforms.
182 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
185 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
186 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
187 * smaller and the value was bumped to retain the total size, but it
188 * was never re-evaluated for suitability. A simple test counting
189 * lengths during package building shows that the value of 45 covers
190 * about 86% of all added entries, reaching 99% at 65.
192 * Regardless of the above, use of dedicated zones instead of malloc may be
193 * inducing additional waste. This may be hard to address as said zones are
194 * tied to VFS SMR. Even if retaining them, the current split should be
198 #define CACHE_PATH_CUTOFF 45
199 #define CACHE_LARGE_PAD 6
201 #define CACHE_PATH_CUTOFF 41
202 #define CACHE_LARGE_PAD 2
205 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
206 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
207 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
208 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
210 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
211 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
212 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
213 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
215 #define nc_vp n_un.nu_vp
216 #define nc_neg n_un.nu_neg
219 * Flags in namecache.nc_flag
221 #define NCF_WHITE 0x01
222 #define NCF_ISDOTDOT 0x02
225 #define NCF_DVDROP 0x10
226 #define NCF_NEGATIVE 0x20
227 #define NCF_INVALID 0x40
231 * Flags in negstate.neg_flag
235 static bool cache_neg_evict_cond(u_long lnumcache);
238 * Mark an entry as invalid.
240 * This is called before it starts getting deconstructed.
243 cache_ncp_invalidate(struct namecache *ncp)
246 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
247 ("%s: entry %p already invalid", __func__, ncp));
248 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
249 atomic_thread_fence_rel();
253 * Check whether the entry can be safely used.
255 * All places which elide locks are supposed to call this after they are
256 * done with reading from an entry.
258 #define cache_ncp_canuse(ncp) ({ \
259 struct namecache *_ncp = (ncp); \
262 atomic_thread_fence_acq(); \
263 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
264 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0); \
268 * Like the above but also checks NCF_WHITE.
270 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
271 struct namecache *_ncp = (ncp); \
274 atomic_thread_fence_acq(); \
275 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
276 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
280 * Name caching works as follows:
282 * Names found by directory scans are retained in a cache
283 * for future reference. It is managed LRU, so frequently
284 * used names will hang around. Cache is indexed by hash value
285 * obtained from (dvp, name) where dvp refers to the directory
288 * If it is a "negative" entry, (i.e. for a name that is known NOT to
289 * exist) the vnode pointer will be NULL.
291 * Upon reaching the last segment of a path, if the reference
292 * is for DELETE, or NOCACHE is set (rewrite), and the
293 * name is located in the cache, it will be dropped.
295 * These locks are used (in the order in which they can be taken):
297 * vnodelock mtx vnode lists and v_cache_dd field protection
298 * bucketlock mtx for access to given set of hash buckets
299 * neglist mtx negative entry LRU management
301 * It is legal to take multiple vnodelock and bucketlock locks. The locking
302 * order is lower address first. Both are recursive.
304 * "." lookups are lockless.
306 * ".." and vnode -> name lookups require vnodelock.
308 * name -> vnode lookup requires the relevant bucketlock to be held for reading.
310 * Insertions and removals of entries require involved vnodes and bucketlocks
311 * to be locked to provide safe operation against other threads modifying the
314 * Some lookups result in removal of the found entry (e.g. getting rid of a
315 * negative entry with the intent to create a positive one), which poses a
316 * problem when multiple threads reach the state. Similarly, two different
317 * threads can purge two different vnodes and try to remove the same name.
319 * If the already held vnode lock is lower than the second required lock, we
320 * can just take the other lock. However, in the opposite case, this could
321 * deadlock. As such, this is resolved by trylocking and if that fails unlocking
322 * the first node, locking everything in order and revalidating the state.
327 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
328 "Name cache parameters");
330 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
331 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
332 "Total namecache capacity");
334 u_int ncsizefactor = 2;
335 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
336 "Size factor for namecache");
338 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
339 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
340 "Ratio of negative namecache entries");
343 * Negative entry % of namecache capacity above which automatic eviction is allowed.
345 * Check cache_neg_evict_cond for details.
347 static u_int ncnegminpct = 3;
349 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
350 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
351 "Negative entry count above which automatic eviction is allowed");
354 * Structures associated with name caching.
356 #define NCHHASH(hash) \
357 (&nchashtbl[(hash) & nchash])
358 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
359 static u_long __read_mostly nchash; /* size of hash table */
360 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
361 "Size of namecache hash table");
362 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
363 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
365 struct nchstats nchstats; /* cache effectiveness statistics */
367 static bool __read_frequently cache_fast_revlookup = true;
368 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
369 &cache_fast_revlookup, 0, "");
371 static bool __read_mostly cache_rename_add = true;
372 SYSCTL_BOOL(_vfs, OID_AUTO, cache_rename_add, CTLFLAG_RW,
373 &cache_rename_add, 0, "");
375 static u_int __exclusive_cache_line neg_cycle;
378 #define numneglists (ncneghash + 1)
381 struct mtx nl_evict_lock;
382 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
383 TAILQ_HEAD(, namecache) nl_list;
384 TAILQ_HEAD(, namecache) nl_hotlist;
386 } __aligned(CACHE_LINE_SIZE);
388 static struct neglist neglists[numneglists];
390 static inline struct neglist *
391 NCP2NEGLIST(struct namecache *ncp)
394 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
397 static inline struct negstate *
398 NCP2NEGSTATE(struct namecache *ncp)
401 MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
402 return (&ncp->nc_neg);
405 #define numbucketlocks (ncbuckethash + 1)
406 static u_int __read_mostly ncbuckethash;
407 static struct mtx_padalign __read_mostly *bucketlocks;
408 #define HASH2BUCKETLOCK(hash) \
409 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
411 #define numvnodelocks (ncvnodehash + 1)
412 static u_int __read_mostly ncvnodehash;
413 static struct mtx __read_mostly *vnodelocks;
414 static inline struct mtx *
415 VP2VNODELOCK(struct vnode *vp)
418 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
422 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
424 struct namecache_ts *ncp_ts;
426 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
427 (tsp == NULL && ticksp == NULL),
433 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
434 *tsp = ncp_ts->nc_time;
435 *ticksp = ncp_ts->nc_ticks;
439 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
440 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
441 "VFS namecache enabled");
444 /* Export size information to userland */
445 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
446 sizeof(struct namecache), "sizeof(struct namecache)");
449 * The new name cache statistics
451 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
452 "Name cache statistics");
454 #define STATNODE_ULONG(name, varname, descr) \
455 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
456 #define STATNODE_COUNTER(name, varname, descr) \
457 static COUNTER_U64_DEFINE_EARLY(varname); \
458 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
460 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
461 STATNODE_ULONG(count, numcache, "Number of cache entries");
462 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
463 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
464 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
465 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
466 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
467 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
468 STATNODE_COUNTER(posszaps, numposzaps,
469 "Number of cache hits (positive) we do not want to cache");
470 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
471 STATNODE_COUNTER(negzaps, numnegzaps,
472 "Number of cache hits (negative) we do not want to cache");
473 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
474 /* These count for vn_getcwd(), too. */
475 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
476 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
477 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
478 "Number of fullpath search errors (VOP_VPTOCNP failures)");
479 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
480 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
481 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
484 * Debug or developer statistics.
486 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
487 "Name cache debugging");
488 #define DEBUGNODE_ULONG(name, varname, descr) \
489 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
490 #define DEBUGNODE_COUNTER(name, varname, descr) \
491 static COUNTER_U64_DEFINE_EARLY(varname); \
492 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
494 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
495 "Number of successful removals after relocking");
496 static long zap_bucket_fail;
497 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
498 static long zap_bucket_fail2;
499 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
500 static long cache_lock_vnodes_cel_3_failures;
501 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
502 "Number of times 3-way vnode locking failed");
504 static void cache_zap_locked(struct namecache *ncp);
505 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
506 char **freebuf, size_t *buflen);
507 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
508 char **retbuf, size_t *buflen, size_t addend);
509 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
510 char **retbuf, size_t *buflen);
511 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
512 char **retbuf, size_t *len, size_t addend);
514 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
517 cache_assert_vlp_locked(struct mtx *vlp)
521 mtx_assert(vlp, MA_OWNED);
525 cache_assert_vnode_locked(struct vnode *vp)
529 vlp = VP2VNODELOCK(vp);
530 cache_assert_vlp_locked(vlp);
534 * Directory vnodes with entries are held for two reasons:
535 * 1. make them less of a target for reclamation in vnlru
536 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
538 * It will be feasible to stop doing it altogether if all filesystems start
539 * supporting lockless lookup.
542 cache_hold_vnode(struct vnode *vp)
545 cache_assert_vnode_locked(vp);
546 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
548 counter_u64_add(numcachehv, 1);
552 cache_drop_vnode(struct vnode *vp)
556 * Called after all locks are dropped, meaning we can't assert
557 * on the state of v_cache_src.
560 counter_u64_add(numcachehv, -1);
566 static uma_zone_t __read_mostly cache_zone_small;
567 static uma_zone_t __read_mostly cache_zone_small_ts;
568 static uma_zone_t __read_mostly cache_zone_large;
569 static uma_zone_t __read_mostly cache_zone_large_ts;
572 cache_symlink_alloc(size_t size, int flags)
575 if (size < CACHE_ZONE_SMALL_SIZE) {
576 return (uma_zalloc_smr(cache_zone_small, flags));
578 if (size < CACHE_ZONE_LARGE_SIZE) {
579 return (uma_zalloc_smr(cache_zone_large, flags));
581 counter_u64_add(symlinktoobig, 1);
582 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
587 cache_symlink_free(char *string, size_t size)
590 MPASS(string != NULL);
591 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
592 ("%s: size %zu too big", __func__, size));
594 if (size < CACHE_ZONE_SMALL_SIZE) {
595 uma_zfree_smr(cache_zone_small, string);
598 if (size < CACHE_ZONE_LARGE_SIZE) {
599 uma_zfree_smr(cache_zone_large, string);
602 __assert_unreachable();
605 static struct namecache *
606 cache_alloc_uma(int len, bool ts)
608 struct namecache_ts *ncp_ts;
609 struct namecache *ncp;
611 if (__predict_false(ts)) {
612 if (len <= CACHE_PATH_CUTOFF)
613 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
615 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
616 ncp = &ncp_ts->nc_nc;
618 if (len <= CACHE_PATH_CUTOFF)
619 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
621 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
627 cache_free_uma(struct namecache *ncp)
629 struct namecache_ts *ncp_ts;
631 if (__predict_false(ncp->nc_flag & NCF_TS)) {
632 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
633 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
634 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
636 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
638 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
639 uma_zfree_smr(cache_zone_small, ncp);
641 uma_zfree_smr(cache_zone_large, ncp);
645 static struct namecache *
646 cache_alloc(int len, bool ts)
651 * Avoid blowout in namecache entries.
654 * 1. filesystems may end up trying to add an already existing entry
655 * (for example this can happen after a cache miss during concurrent
656 * lookup), in which case we will call cache_neg_evict despite not
658 * 2. the routine may fail to free anything and no provisions are made
659 * to make it try harder (see the inside for failure modes)
660 * 3. it only ever looks at negative entries.
662 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
663 if (cache_neg_evict_cond(lnumcache)) {
664 lnumcache = atomic_load_long(&numcache);
666 if (__predict_false(lnumcache >= ncsize)) {
667 atomic_subtract_long(&numcache, 1);
668 counter_u64_add(numdrops, 1);
671 return (cache_alloc_uma(len, ts));
675 cache_free(struct namecache *ncp)
679 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
680 cache_drop_vnode(ncp->nc_dvp);
683 atomic_subtract_long(&numcache, 1);
687 cache_free_batch(struct cache_freebatch *batch)
689 struct namecache *ncp, *nnp;
693 if (TAILQ_EMPTY(batch))
695 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
696 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
697 cache_drop_vnode(ncp->nc_dvp);
702 atomic_subtract_long(&numcache, i);
704 SDT_PROBE1(vfs, namecache, purge, batch, i);
708 * TODO: With the value stored we can do better than computing the hash based
709 * on the address. The choice of FNV should also be revisited.
712 cache_prehash(struct vnode *vp)
715 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
719 cache_get_hash(char *name, u_char len, struct vnode *dvp)
722 return (fnv_32_buf(name, len, dvp->v_nchash));
726 cache_get_hash_iter_start(struct vnode *dvp)
729 return (dvp->v_nchash);
733 cache_get_hash_iter(char c, uint32_t hash)
736 return (fnv_32_buf(&c, 1, hash));
740 cache_get_hash_iter_finish(uint32_t hash)
746 static inline struct nchashhead *
747 NCP2BUCKET(struct namecache *ncp)
751 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
752 return (NCHHASH(hash));
755 static inline struct mtx *
756 NCP2BUCKETLOCK(struct namecache *ncp)
760 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
761 return (HASH2BUCKETLOCK(hash));
766 cache_assert_bucket_locked(struct namecache *ncp)
770 blp = NCP2BUCKETLOCK(ncp);
771 mtx_assert(blp, MA_OWNED);
775 cache_assert_bucket_unlocked(struct namecache *ncp)
779 blp = NCP2BUCKETLOCK(ncp);
780 mtx_assert(blp, MA_NOTOWNED);
783 #define cache_assert_bucket_locked(x) do { } while (0)
784 #define cache_assert_bucket_unlocked(x) do { } while (0)
787 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
789 _cache_sort_vnodes(void **p1, void **p2)
793 MPASS(*p1 != NULL || *p2 != NULL);
803 cache_lock_all_buckets(void)
807 for (i = 0; i < numbucketlocks; i++)
808 mtx_lock(&bucketlocks[i]);
812 cache_unlock_all_buckets(void)
816 for (i = 0; i < numbucketlocks; i++)
817 mtx_unlock(&bucketlocks[i]);
821 cache_lock_all_vnodes(void)
825 for (i = 0; i < numvnodelocks; i++)
826 mtx_lock(&vnodelocks[i]);
830 cache_unlock_all_vnodes(void)
834 for (i = 0; i < numvnodelocks; i++)
835 mtx_unlock(&vnodelocks[i]);
839 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
842 cache_sort_vnodes(&vlp1, &vlp2);
845 if (!mtx_trylock(vlp1))
848 if (!mtx_trylock(vlp2)) {
858 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
861 MPASS(vlp1 != NULL || vlp2 != NULL);
871 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
874 MPASS(vlp1 != NULL || vlp2 != NULL);
883 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
885 struct nchstats snap;
887 if (req->oldptr == NULL)
888 return (SYSCTL_OUT(req, 0, sizeof(snap)));
891 snap.ncs_goodhits = counter_u64_fetch(numposhits);
892 snap.ncs_neghits = counter_u64_fetch(numneghits);
893 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
894 counter_u64_fetch(numnegzaps);
895 snap.ncs_miss = counter_u64_fetch(nummisszap) +
896 counter_u64_fetch(nummiss);
898 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
900 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
901 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
902 "VFS cache effectiveness statistics");
905 cache_recalc_neg_min(u_int val)
908 neg_min = (ncsize * val) / 100;
912 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
918 error = sysctl_handle_int(oidp, &val, 0, req);
919 if (error != 0 || req->newptr == NULL)
922 if (val == ncnegminpct)
924 if (val < 0 || val > 99)
927 cache_recalc_neg_min(val);
931 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
932 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
933 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
937 * Grab an atomic snapshot of the name cache hash chain lengths
939 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
940 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
944 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
946 struct nchashhead *ncpp;
947 struct namecache *ncp;
948 int i, error, n_nchash, *cntbuf;
951 n_nchash = nchash + 1; /* nchash is max index, not count */
952 if (req->oldptr == NULL)
953 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
954 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
955 cache_lock_all_buckets();
956 if (n_nchash != nchash + 1) {
957 cache_unlock_all_buckets();
958 free(cntbuf, M_TEMP);
961 /* Scan hash tables counting entries */
962 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
963 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
965 cache_unlock_all_buckets();
966 for (error = 0, i = 0; i < n_nchash; i++)
967 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
969 free(cntbuf, M_TEMP);
972 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
973 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
974 "nchash chain lengths");
977 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
980 struct nchashhead *ncpp;
981 struct namecache *ncp;
983 int count, maxlength, used, pct;
986 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
988 cache_lock_all_buckets();
989 n_nchash = nchash + 1; /* nchash is max index, not count */
993 /* Scan hash tables for applicable entries */
994 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
996 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1001 if (maxlength < count)
1004 n_nchash = nchash + 1;
1005 cache_unlock_all_buckets();
1006 pct = (used * 100) / (n_nchash / 100);
1007 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1010 error = SYSCTL_OUT(req, &used, sizeof(used));
1013 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1016 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1021 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1022 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1023 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1027 * Negative entries management
1029 * Various workloads create plenty of negative entries and barely use them
1030 * afterwards. Moreover malicious users can keep performing bogus lookups
1031 * adding even more entries. For example "make tinderbox" as of writing this
1032 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1035 * As such, a rather aggressive eviction method is needed. The currently
1036 * employed method is a placeholder.
1038 * Entries are split over numneglists separate lists, each of which is further
1039 * split into hot and cold entries. Entries get promoted after getting a hit.
1040 * Eviction happens on addition of new entry.
1042 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1043 "Name cache negative entry statistics");
1045 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1046 "Number of negative cache entries");
1048 static COUNTER_U64_DEFINE_EARLY(neg_created);
1049 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1050 "Number of created negative entries");
1052 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1053 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1054 "Number of evicted negative entries");
1056 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1057 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1058 &neg_evict_skipped_empty,
1059 "Number of times evicting failed due to lack of entries");
1061 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1062 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1063 &neg_evict_skipped_missed,
1064 "Number of times evicting failed due to target entry disappearing");
1066 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1067 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1068 &neg_evict_skipped_contended,
1069 "Number of times evicting failed due to contention");
1071 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1072 "Number of cache hits (negative)");
1075 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1080 for (i = 0; i < numneglists; i++)
1081 out += neglists[i].nl_hotnum;
1083 return (SYSCTL_OUT(req, &out, sizeof(out)));
1085 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1086 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1087 "Number of hot negative entries");
1090 cache_neg_init(struct namecache *ncp)
1092 struct negstate *ns;
1094 ncp->nc_flag |= NCF_NEGATIVE;
1095 ns = NCP2NEGSTATE(ncp);
1098 counter_u64_add(neg_created, 1);
1101 #define CACHE_NEG_PROMOTION_THRESH 2
1104 cache_neg_hit_prep(struct namecache *ncp)
1106 struct negstate *ns;
1109 ns = NCP2NEGSTATE(ncp);
1110 n = atomic_load_char(&ns->neg_hit);
1112 if (n >= CACHE_NEG_PROMOTION_THRESH)
1114 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1117 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1121 * Nothing to do here but it is provided for completeness as some
1122 * cache_neg_hit_prep callers may end up returning without even
1123 * trying to promote.
1125 #define cache_neg_hit_abort(ncp) do { } while (0)
1128 cache_neg_hit_finish(struct namecache *ncp)
1131 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1132 counter_u64_add(numneghits, 1);
1136 * Move a negative entry to the hot list.
1139 cache_neg_promote_locked(struct namecache *ncp)
1142 struct negstate *ns;
1144 ns = NCP2NEGSTATE(ncp);
1145 nl = NCP2NEGLIST(ncp);
1146 mtx_assert(&nl->nl_lock, MA_OWNED);
1147 if ((ns->neg_flag & NEG_HOT) == 0) {
1148 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1149 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1151 ns->neg_flag |= NEG_HOT;
1156 * Move a hot negative entry to the cold list.
1159 cache_neg_demote_locked(struct namecache *ncp)
1162 struct negstate *ns;
1164 ns = NCP2NEGSTATE(ncp);
1165 nl = NCP2NEGLIST(ncp);
1166 mtx_assert(&nl->nl_lock, MA_OWNED);
1167 MPASS(ns->neg_flag & NEG_HOT);
1168 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1169 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1171 ns->neg_flag &= ~NEG_HOT;
1172 atomic_store_char(&ns->neg_hit, 0);
1176 * Move a negative entry to the hot list if it matches the lookup.
1178 * We have to take locks, but they may be contended and in the worst
1179 * case we may need to go off CPU. We don't want to spin within the
1180 * smr section and we can't block with it. Exiting the section means
1181 * the found entry could have been evicted. We are going to look it
1185 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1186 struct namecache *oncp, uint32_t hash)
1188 struct namecache *ncp;
1192 nl = NCP2NEGLIST(oncp);
1194 mtx_lock(&nl->nl_lock);
1196 * For hash iteration.
1201 * Avoid all surprises by only succeeding if we got the same entry and
1202 * bailing completely otherwise.
1203 * XXX There are no provisions to keep the vnode around, meaning we may
1204 * end up promoting a negative entry for a *new* vnode and returning
1205 * ENOENT on its account. This is the error we want to return anyway
1206 * and promotion is harmless.
1208 * In particular at this point there can be a new ncp which matches the
1209 * search but hashes to a different neglist.
1211 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1217 * No match to begin with.
1219 if (__predict_false(ncp == NULL)) {
1224 * The newly found entry may be something different...
1226 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1227 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1232 * ... and not even negative.
1234 nc_flag = atomic_load_char(&ncp->nc_flag);
1235 if ((nc_flag & NCF_NEGATIVE) == 0) {
1239 if (!cache_ncp_canuse(ncp)) {
1243 cache_neg_promote_locked(ncp);
1244 cache_neg_hit_finish(ncp);
1246 mtx_unlock(&nl->nl_lock);
1250 mtx_unlock(&nl->nl_lock);
1255 cache_neg_promote(struct namecache *ncp)
1259 nl = NCP2NEGLIST(ncp);
1260 mtx_lock(&nl->nl_lock);
1261 cache_neg_promote_locked(ncp);
1262 mtx_unlock(&nl->nl_lock);
1266 cache_neg_insert(struct namecache *ncp)
1270 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1271 cache_assert_bucket_locked(ncp);
1272 nl = NCP2NEGLIST(ncp);
1273 mtx_lock(&nl->nl_lock);
1274 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1275 mtx_unlock(&nl->nl_lock);
1276 atomic_add_long(&numneg, 1);
1280 cache_neg_remove(struct namecache *ncp)
1283 struct negstate *ns;
1285 cache_assert_bucket_locked(ncp);
1286 nl = NCP2NEGLIST(ncp);
1287 ns = NCP2NEGSTATE(ncp);
1288 mtx_lock(&nl->nl_lock);
1289 if ((ns->neg_flag & NEG_HOT) != 0) {
1290 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1293 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1295 mtx_unlock(&nl->nl_lock);
1296 atomic_subtract_long(&numneg, 1);
1299 static struct neglist *
1300 cache_neg_evict_select_list(void)
1305 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1306 nl = &neglists[c % numneglists];
1307 if (!mtx_trylock(&nl->nl_evict_lock)) {
1308 counter_u64_add(neg_evict_skipped_contended, 1);
1314 static struct namecache *
1315 cache_neg_evict_select_entry(struct neglist *nl)
1317 struct namecache *ncp, *lncp;
1318 struct negstate *ns, *lns;
1321 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1322 mtx_assert(&nl->nl_lock, MA_OWNED);
1323 ncp = TAILQ_FIRST(&nl->nl_list);
1327 lns = NCP2NEGSTATE(lncp);
1328 for (i = 1; i < 4; i++) {
1329 ncp = TAILQ_NEXT(ncp, nc_dst);
1332 ns = NCP2NEGSTATE(ncp);
1333 if (ns->neg_hit < lns->neg_hit) {
1342 cache_neg_evict(void)
1344 struct namecache *ncp, *ncp2;
1353 nl = cache_neg_evict_select_list();
1358 mtx_lock(&nl->nl_lock);
1359 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1361 cache_neg_demote_locked(ncp);
1363 ncp = cache_neg_evict_select_entry(nl);
1365 counter_u64_add(neg_evict_skipped_empty, 1);
1366 mtx_unlock(&nl->nl_lock);
1367 mtx_unlock(&nl->nl_evict_lock);
1370 nlen = ncp->nc_nlen;
1372 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1373 dvlp = VP2VNODELOCK(dvp);
1374 blp = HASH2BUCKETLOCK(hash);
1375 mtx_unlock(&nl->nl_lock);
1376 mtx_unlock(&nl->nl_evict_lock);
1380 * Note that since all locks were dropped above, the entry may be
1381 * gone or reallocated to be something else.
1383 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1384 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1385 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1389 counter_u64_add(neg_evict_skipped_missed, 1);
1393 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1394 MPASS(blp == NCP2BUCKETLOCK(ncp));
1395 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1397 cache_zap_locked(ncp);
1398 counter_u64_add(neg_evicted, 1);
1409 * Maybe evict a negative entry to create more room.
1411 * The ncnegfactor parameter limits what fraction of the total count
1412 * can comprise of negative entries. However, if the cache is just
1413 * warming up this leads to excessive evictions. As such, ncnegminpct
1414 * (recomputed to neg_min) dictates whether the above should be
1417 * Try evicting if the cache is close to full capacity regardless of
1418 * other considerations.
1421 cache_neg_evict_cond(u_long lnumcache)
1425 if (ncsize - 1000 < lnumcache)
1427 lnumneg = atomic_load_long(&numneg);
1428 if (lnumneg < neg_min)
1430 if (lnumneg * ncnegfactor < lnumcache)
1433 return (cache_neg_evict());
1437 * cache_zap_locked():
1439 * Removes a namecache entry from cache, whether it contains an actual
1440 * pointer to a vnode or if it is just a negative cache entry.
1443 cache_zap_locked(struct namecache *ncp)
1445 struct nchashhead *ncpp;
1446 struct vnode *dvp, *vp;
1451 if (!(ncp->nc_flag & NCF_NEGATIVE))
1452 cache_assert_vnode_locked(vp);
1453 cache_assert_vnode_locked(dvp);
1454 cache_assert_bucket_locked(ncp);
1456 cache_ncp_invalidate(ncp);
1458 ncpp = NCP2BUCKET(ncp);
1459 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1460 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1461 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1462 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1463 if (ncp == vp->v_cache_dd) {
1464 atomic_store_ptr(&vp->v_cache_dd, NULL);
1467 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1468 cache_neg_remove(ncp);
1470 if (ncp->nc_flag & NCF_ISDOTDOT) {
1471 if (ncp == dvp->v_cache_dd) {
1472 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1475 LIST_REMOVE(ncp, nc_src);
1476 if (LIST_EMPTY(&dvp->v_cache_src)) {
1477 ncp->nc_flag |= NCF_DVDROP;
1483 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1487 MPASS(ncp->nc_dvp == vp);
1488 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1489 cache_assert_vnode_locked(vp);
1491 blp = NCP2BUCKETLOCK(ncp);
1493 cache_zap_locked(ncp);
1498 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1501 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1504 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1505 cache_assert_vnode_locked(vp);
1507 if (ncp->nc_flag & NCF_NEGATIVE) {
1508 if (*vlpp != NULL) {
1512 cache_zap_negative_locked_vnode_kl(ncp, vp);
1516 pvlp = VP2VNODELOCK(vp);
1517 blp = NCP2BUCKETLOCK(ncp);
1518 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1519 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1521 if (*vlpp == vlp1 || *vlpp == vlp2) {
1525 if (*vlpp != NULL) {
1529 cache_sort_vnodes(&vlp1, &vlp2);
1534 if (!mtx_trylock(vlp1))
1540 cache_zap_locked(ncp);
1542 if (to_unlock != NULL)
1543 mtx_unlock(to_unlock);
1550 MPASS(*vlpp == NULL);
1556 * If trylocking failed we can get here. We know enough to take all needed locks
1557 * in the right order and re-lookup the entry.
1560 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1561 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1564 struct namecache *rncp;
1566 cache_assert_bucket_unlocked(ncp);
1568 cache_sort_vnodes(&dvlp, &vlp);
1569 cache_lock_vnodes(dvlp, vlp);
1571 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1572 if (rncp == ncp && rncp->nc_dvp == dvp &&
1573 rncp->nc_nlen == cnp->cn_namelen &&
1574 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1578 cache_zap_locked(rncp);
1580 cache_unlock_vnodes(dvlp, vlp);
1581 counter_u64_add(zap_bucket_relock_success, 1);
1586 cache_unlock_vnodes(dvlp, vlp);
1590 static int __noinline
1591 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1592 uint32_t hash, struct mtx *blp)
1594 struct mtx *dvlp, *vlp;
1597 cache_assert_bucket_locked(ncp);
1599 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1601 if (!(ncp->nc_flag & NCF_NEGATIVE))
1602 vlp = VP2VNODELOCK(ncp->nc_vp);
1603 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1604 cache_zap_locked(ncp);
1606 cache_unlock_vnodes(dvlp, vlp);
1612 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1615 static __noinline int
1616 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1618 struct namecache *ncp;
1620 struct mtx *dvlp, *dvlp2;
1624 if (cnp->cn_namelen == 2 &&
1625 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1626 dvlp = VP2VNODELOCK(dvp);
1630 ncp = dvp->v_cache_dd;
1635 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1638 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1639 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1641 MPASS(dvp->v_cache_dd == NULL);
1647 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1652 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1656 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1657 blp = HASH2BUCKETLOCK(hash);
1659 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1664 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1665 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1666 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1675 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1676 if (__predict_false(error != 0)) {
1680 counter_u64_add(numposzaps, 1);
1681 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1685 counter_u64_add(nummisszap, 1);
1686 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1690 static int __noinline
1691 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1692 struct timespec *tsp, int *ticksp)
1697 counter_u64_add(dothits, 1);
1698 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1705 * When we lookup "." we still can be asked to lock it
1708 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1709 if (ltype != VOP_ISLOCKED(*vpp)) {
1710 if (ltype == LK_EXCLUSIVE) {
1711 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1712 if (VN_IS_DOOMED((*vpp))) {
1713 /* forced unmount */
1719 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1724 static int __noinline
1725 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1726 struct timespec *tsp, int *ticksp)
1728 struct namecache_ts *ncp_ts;
1729 struct namecache *ncp;
1735 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1737 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1738 cache_remove_cnp(dvp, cnp);
1742 counter_u64_add(dotdothits, 1);
1744 dvlp = VP2VNODELOCK(dvp);
1746 ncp = dvp->v_cache_dd;
1748 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, "..", NULL);
1752 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1753 if (ncp->nc_flag & NCF_NEGATIVE)
1760 goto negative_success;
1761 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1762 cache_out_ts(ncp, tsp, ticksp);
1763 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1764 NCF_DTS && tsp != NULL) {
1765 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1766 *tsp = ncp_ts->nc_dotdottime;
1770 ltype = VOP_ISLOCKED(dvp);
1772 vs = vget_prep(*vpp);
1774 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1775 vn_lock(dvp, ltype | LK_RETRY);
1776 if (VN_IS_DOOMED(dvp)) {
1788 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1789 if (cnp->cn_flags & ISLASTCN) {
1790 counter_u64_add(numnegzaps, 1);
1791 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1798 whiteout = (ncp->nc_flag & NCF_WHITE);
1799 cache_out_ts(ncp, tsp, ticksp);
1800 if (cache_neg_hit_prep(ncp))
1801 cache_neg_promote(ncp);
1803 cache_neg_hit_finish(ncp);
1806 cnp->cn_flags |= ISWHITEOUT;
1811 * Lookup a name in the name cache
1815 * - dvp: Parent directory in which to search.
1816 * - vpp: Return argument. Will contain desired vnode on cache hit.
1817 * - cnp: Parameters of the name search. The most interesting bits of
1818 * the cn_flags field have the following meanings:
1819 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1821 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1822 * - tsp: Return storage for cache timestamp. On a successful (positive
1823 * or negative) lookup, tsp will be filled with any timespec that
1824 * was stored when this cache entry was created. However, it will
1825 * be clear for "." entries.
1826 * - ticks: Return storage for alternate cache timestamp. On a successful
1827 * (positive or negative) lookup, it will contain the ticks value
1828 * that was current when the cache entry was created, unless cnp
1831 * Either both tsp and ticks have to be provided or neither of them.
1835 * - -1: A positive cache hit. vpp will contain the desired vnode.
1836 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1837 * to a forced unmount. vpp will not be modified. If the entry
1838 * is a whiteout, then the ISWHITEOUT flag will be set in
1840 * - 0: A cache miss. vpp will not be modified.
1844 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1845 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1846 * lock is not recursively acquired.
1848 static int __noinline
1849 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1850 struct timespec *tsp, int *ticksp)
1852 struct namecache *ncp;
1859 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1860 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1863 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1864 blp = HASH2BUCKETLOCK(hash);
1867 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1868 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1869 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1873 if (__predict_false(ncp == NULL)) {
1875 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1877 counter_u64_add(nummiss, 1);
1881 if (ncp->nc_flag & NCF_NEGATIVE)
1882 goto negative_success;
1884 counter_u64_add(numposhits, 1);
1886 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1887 cache_out_ts(ncp, tsp, ticksp);
1889 vs = vget_prep(*vpp);
1891 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1899 * We don't get here with regular lookup apart from corner cases.
1901 if (__predict_true(cnp->cn_nameiop == CREATE)) {
1902 if (cnp->cn_flags & ISLASTCN) {
1903 counter_u64_add(numnegzaps, 1);
1904 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1905 if (__predict_false(error != 0)) {
1914 whiteout = (ncp->nc_flag & NCF_WHITE);
1915 cache_out_ts(ncp, tsp, ticksp);
1916 if (cache_neg_hit_prep(ncp))
1917 cache_neg_promote(ncp);
1919 cache_neg_hit_finish(ncp);
1922 cnp->cn_flags |= ISWHITEOUT;
1927 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1928 struct timespec *tsp, int *ticksp)
1930 struct namecache *ncp;
1934 bool whiteout, neg_promote;
1937 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
1940 if (__predict_false(!doingcache)) {
1941 cnp->cn_flags &= ~MAKEENTRY;
1946 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1947 if (cnp->cn_namelen == 1)
1948 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1949 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
1950 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
1953 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1955 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
1956 cache_remove_cnp(dvp, cnp);
1960 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1963 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1964 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1965 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1969 if (__predict_false(ncp == NULL)) {
1971 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1973 counter_u64_add(nummiss, 1);
1977 nc_flag = atomic_load_char(&ncp->nc_flag);
1978 if (nc_flag & NCF_NEGATIVE)
1979 goto negative_success;
1981 counter_u64_add(numposhits, 1);
1983 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1984 cache_out_ts(ncp, tsp, ticksp);
1986 if (!cache_ncp_canuse(ncp)) {
1991 vs = vget_prep_smr(*vpp);
1993 if (__predict_false(vs == VGET_NONE)) {
1997 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2004 if (cnp->cn_nameiop == CREATE) {
2005 if (cnp->cn_flags & ISLASTCN) {
2011 cache_out_ts(ncp, tsp, ticksp);
2012 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2013 neg_promote = cache_neg_hit_prep(ncp);
2014 if (!cache_ncp_canuse(ncp)) {
2015 cache_neg_hit_abort(ncp);
2021 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2024 cache_neg_hit_finish(ncp);
2028 cnp->cn_flags |= ISWHITEOUT;
2031 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2034 struct celockstate {
2038 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2039 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2042 cache_celockstate_init(struct celockstate *cel)
2045 bzero(cel, sizeof(*cel));
2049 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2052 struct mtx *vlp1, *vlp2;
2054 MPASS(cel->vlp[0] == NULL);
2055 MPASS(cel->vlp[1] == NULL);
2056 MPASS(cel->vlp[2] == NULL);
2058 MPASS(vp != NULL || dvp != NULL);
2060 vlp1 = VP2VNODELOCK(vp);
2061 vlp2 = VP2VNODELOCK(dvp);
2062 cache_sort_vnodes(&vlp1, &vlp2);
2073 cache_unlock_vnodes_cel(struct celockstate *cel)
2076 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2078 if (cel->vlp[0] != NULL)
2079 mtx_unlock(cel->vlp[0]);
2080 if (cel->vlp[1] != NULL)
2081 mtx_unlock(cel->vlp[1]);
2082 if (cel->vlp[2] != NULL)
2083 mtx_unlock(cel->vlp[2]);
2087 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2092 cache_assert_vlp_locked(cel->vlp[0]);
2093 cache_assert_vlp_locked(cel->vlp[1]);
2094 MPASS(cel->vlp[2] == NULL);
2097 vlp = VP2VNODELOCK(vp);
2100 if (vlp >= cel->vlp[1]) {
2103 if (mtx_trylock(vlp))
2105 cache_lock_vnodes_cel_3_failures++;
2106 cache_unlock_vnodes_cel(cel);
2107 if (vlp < cel->vlp[0]) {
2109 mtx_lock(cel->vlp[0]);
2110 mtx_lock(cel->vlp[1]);
2112 if (cel->vlp[0] != NULL)
2113 mtx_lock(cel->vlp[0]);
2115 mtx_lock(cel->vlp[1]);
2125 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2129 MPASS(cel->blp[0] == NULL);
2130 MPASS(cel->blp[1] == NULL);
2132 cache_sort_vnodes(&blp1, &blp2);
2143 cache_unlock_buckets_cel(struct celockstate *cel)
2146 if (cel->blp[0] != NULL)
2147 mtx_unlock(cel->blp[0]);
2148 mtx_unlock(cel->blp[1]);
2152 * Lock part of the cache affected by the insertion.
2154 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2155 * However, insertion can result in removal of an old entry. In this
2156 * case we have an additional vnode and bucketlock pair to lock.
2158 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2159 * preserving the locking order (smaller address first).
2162 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2165 struct namecache *ncp;
2166 struct mtx *blps[2];
2169 blps[0] = HASH2BUCKETLOCK(hash);
2172 cache_lock_vnodes_cel(cel, dvp, vp);
2173 if (vp == NULL || vp->v_type != VDIR)
2175 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2178 nc_flag = atomic_load_char(&ncp->nc_flag);
2179 if ((nc_flag & NCF_ISDOTDOT) == 0)
2181 MPASS(ncp->nc_dvp == vp);
2182 blps[1] = NCP2BUCKETLOCK(ncp);
2183 if ((nc_flag & NCF_NEGATIVE) != 0)
2185 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2188 * All vnodes got re-locked. Re-validate the state and if
2189 * nothing changed we are done. Otherwise restart.
2191 if (ncp == vp->v_cache_dd &&
2192 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2193 blps[1] == NCP2BUCKETLOCK(ncp) &&
2194 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2196 cache_unlock_vnodes_cel(cel);
2201 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2205 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2208 struct namecache *ncp;
2209 struct mtx *blps[2];
2212 blps[0] = HASH2BUCKETLOCK(hash);
2215 cache_lock_vnodes_cel(cel, dvp, vp);
2216 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2219 nc_flag = atomic_load_char(&ncp->nc_flag);
2220 if ((nc_flag & NCF_ISDOTDOT) == 0)
2222 MPASS(ncp->nc_dvp == dvp);
2223 blps[1] = NCP2BUCKETLOCK(ncp);
2224 if ((nc_flag & NCF_NEGATIVE) != 0)
2226 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2228 if (ncp == dvp->v_cache_dd &&
2229 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2230 blps[1] == NCP2BUCKETLOCK(ncp) &&
2231 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2233 cache_unlock_vnodes_cel(cel);
2238 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2242 cache_enter_unlock(struct celockstate *cel)
2245 cache_unlock_buckets_cel(cel);
2246 cache_unlock_vnodes_cel(cel);
2249 static void __noinline
2250 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2251 struct componentname *cnp)
2253 struct celockstate cel;
2254 struct namecache *ncp;
2258 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2260 len = cnp->cn_namelen;
2261 cache_celockstate_init(&cel);
2262 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2263 cache_enter_lock_dd(&cel, dvp, vp, hash);
2264 ncp = dvp->v_cache_dd;
2265 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2266 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2267 cache_zap_locked(ncp);
2271 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2272 cache_enter_unlock(&cel);
2278 * Add an entry to the cache.
2281 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2282 struct timespec *tsp, struct timespec *dtsp)
2284 struct celockstate cel;
2285 struct namecache *ncp, *n2, *ndd;
2286 struct namecache_ts *ncp_ts;
2287 struct nchashhead *ncpp;
2292 KASSERT(cnp->cn_namelen <= NAME_MAX,
2293 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2295 VNPASS(dvp != vp, dvp);
2296 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2297 VNPASS(dvp->v_type != VNON, dvp);
2299 VNPASS(!VN_IS_DOOMED(vp), vp);
2300 VNPASS(vp->v_type != VNON, vp);
2304 if (__predict_false(!doingcache))
2309 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2310 if (cnp->cn_namelen == 1)
2312 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2313 cache_enter_dotdot_prep(dvp, vp, cnp);
2314 flag = NCF_ISDOTDOT;
2318 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2322 cache_celockstate_init(&cel);
2327 * Calculate the hash key and setup as much of the new
2328 * namecache entry as possible before acquiring the lock.
2330 ncp->nc_flag = flag | NCF_WIP;
2333 cache_neg_init(ncp);
2336 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2337 ncp_ts->nc_time = *tsp;
2338 ncp_ts->nc_ticks = ticks;
2339 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2341 ncp_ts->nc_dotdottime = *dtsp;
2342 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2345 len = ncp->nc_nlen = cnp->cn_namelen;
2346 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2347 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2348 ncp->nc_name[len] = '\0';
2349 cache_enter_lock(&cel, dvp, vp, hash);
2352 * See if this vnode or negative entry is already in the cache
2353 * with this name. This can happen with concurrent lookups of
2354 * the same path name.
2356 ncpp = NCHHASH(hash);
2357 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2358 if (n2->nc_dvp == dvp &&
2359 n2->nc_nlen == cnp->cn_namelen &&
2360 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2361 MPASS(cache_ncp_canuse(n2));
2362 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2364 ("%s: found entry pointing to a different vnode (%p != %p)",
2365 __func__, NULL, vp));
2367 KASSERT(n2->nc_vp == vp,
2368 ("%s: found entry pointing to a different vnode (%p != %p)",
2369 __func__, n2->nc_vp, vp));
2371 * Entries are supposed to be immutable unless in the
2372 * process of getting destroyed. Accommodating for
2373 * changing timestamps is possible but not worth it.
2374 * This should be harmless in terms of correctness, in
2375 * the worst case resulting in an earlier expiration.
2376 * Alternatively, the found entry can be replaced
2379 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2382 KASSERT((n2->nc_flag & NCF_TS) != 0,
2384 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2385 n2_ts->nc_time = ncp_ts->nc_time;
2386 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2388 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2389 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2393 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2395 goto out_unlock_free;
2399 if (flag == NCF_ISDOTDOT) {
2401 * See if we are trying to add .. entry, but some other lookup
2402 * has populated v_cache_dd pointer already.
2404 if (dvp->v_cache_dd != NULL)
2405 goto out_unlock_free;
2406 KASSERT(vp == NULL || vp->v_type == VDIR,
2407 ("wrong vnode type %p", vp));
2408 atomic_thread_fence_rel();
2409 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2413 if (flag != NCF_ISDOTDOT) {
2415 * For this case, the cache entry maps both the
2416 * directory name in it and the name ".." for the
2417 * directory's parent.
2419 if ((ndd = vp->v_cache_dd) != NULL) {
2420 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2421 cache_zap_locked(ndd);
2425 atomic_thread_fence_rel();
2426 atomic_store_ptr(&vp->v_cache_dd, ncp);
2427 } else if (vp->v_type != VDIR) {
2428 if (vp->v_cache_dd != NULL) {
2429 atomic_store_ptr(&vp->v_cache_dd, NULL);
2434 if (flag != NCF_ISDOTDOT) {
2435 if (LIST_EMPTY(&dvp->v_cache_src)) {
2436 cache_hold_vnode(dvp);
2438 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2442 * If the entry is "negative", we place it into the
2443 * "negative" cache queue, otherwise, we place it into the
2444 * destination vnode's cache entries queue.
2447 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2448 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2451 if (cnp->cn_flags & ISWHITEOUT)
2452 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2453 cache_neg_insert(ncp);
2454 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2459 * Insert the new namecache entry into the appropriate chain
2460 * within the cache entries table.
2462 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2464 atomic_thread_fence_rel();
2466 * Mark the entry as fully constructed.
2467 * It is immutable past this point until its removal.
2469 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2471 cache_enter_unlock(&cel);
2476 cache_enter_unlock(&cel);
2482 cache_roundup_2(u_int val)
2486 for (res = 1; res <= val; res <<= 1)
2492 static struct nchashhead *
2493 nchinittbl(u_long elements, u_long *hashmask)
2495 struct nchashhead *hashtbl;
2498 hashsize = cache_roundup_2(elements) / 2;
2500 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2501 for (i = 0; i < hashsize; i++)
2502 CK_SLIST_INIT(&hashtbl[i]);
2503 *hashmask = hashsize - 1;
2508 ncfreetbl(struct nchashhead *hashtbl)
2511 free(hashtbl, M_VFSCACHE);
2515 * Name cache initialization, from vfs_init() when we are booting
2518 nchinit(void *dummy __unused)
2522 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2523 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2524 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2525 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2526 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2527 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2528 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2529 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2531 VFS_SMR_ZONE_SET(cache_zone_small);
2532 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2533 VFS_SMR_ZONE_SET(cache_zone_large);
2534 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2536 ncsize = desiredvnodes * ncsizefactor;
2537 cache_recalc_neg_min(ncnegminpct);
2538 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2539 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2540 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2542 if (ncbuckethash > nchash)
2543 ncbuckethash = nchash;
2544 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2546 for (i = 0; i < numbucketlocks; i++)
2547 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2548 ncvnodehash = ncbuckethash;
2549 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2551 for (i = 0; i < numvnodelocks; i++)
2552 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2554 for (i = 0; i < numneglists; i++) {
2555 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2556 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2557 TAILQ_INIT(&neglists[i].nl_list);
2558 TAILQ_INIT(&neglists[i].nl_hotlist);
2561 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2564 cache_vnode_init(struct vnode *vp)
2567 LIST_INIT(&vp->v_cache_src);
2568 TAILQ_INIT(&vp->v_cache_dst);
2569 vp->v_cache_dd = NULL;
2574 cache_changesize(u_long newmaxvnodes)
2576 struct nchashhead *new_nchashtbl, *old_nchashtbl;
2577 u_long new_nchash, old_nchash;
2578 struct namecache *ncp;
2583 newncsize = newmaxvnodes * ncsizefactor;
2584 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2585 if (newmaxvnodes < numbucketlocks)
2586 newmaxvnodes = numbucketlocks;
2588 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2589 /* If same hash table size, nothing to do */
2590 if (nchash == new_nchash) {
2591 ncfreetbl(new_nchashtbl);
2595 * Move everything from the old hash table to the new table.
2596 * None of the namecache entries in the table can be removed
2597 * because to do so, they have to be removed from the hash table.
2599 cache_lock_all_vnodes();
2600 cache_lock_all_buckets();
2601 old_nchashtbl = nchashtbl;
2602 old_nchash = nchash;
2603 nchashtbl = new_nchashtbl;
2604 nchash = new_nchash;
2605 for (i = 0; i <= old_nchash; i++) {
2606 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2607 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2609 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2610 CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2614 cache_recalc_neg_min(ncnegminpct);
2615 cache_unlock_all_buckets();
2616 cache_unlock_all_vnodes();
2617 ncfreetbl(old_nchashtbl);
2621 * Remove all entries from and to a particular vnode.
2624 cache_purge_impl(struct vnode *vp)
2626 struct cache_freebatch batch;
2627 struct namecache *ncp;
2628 struct mtx *vlp, *vlp2;
2631 vlp = VP2VNODELOCK(vp);
2635 while (!LIST_EMPTY(&vp->v_cache_src)) {
2636 ncp = LIST_FIRST(&vp->v_cache_src);
2637 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2639 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2641 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2642 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2643 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2645 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2647 ncp = vp->v_cache_dd;
2649 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2650 ("lost dotdot link"));
2651 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2653 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2655 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2659 cache_free_batch(&batch);
2663 * Opportunistic check to see if there is anything to do.
2666 cache_has_entries(struct vnode *vp)
2669 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2670 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2676 cache_purge(struct vnode *vp)
2679 SDT_PROBE1(vfs, namecache, purge, done, vp);
2680 if (!cache_has_entries(vp))
2682 cache_purge_impl(vp);
2686 * Only to be used by vgone.
2689 cache_purge_vgone(struct vnode *vp)
2693 VNPASS(VN_IS_DOOMED(vp), vp);
2694 if (cache_has_entries(vp)) {
2695 cache_purge_impl(vp);
2700 * Serialize against a potential thread doing cache_purge.
2702 vlp = VP2VNODELOCK(vp);
2703 mtx_wait_unlocked(vlp);
2704 if (cache_has_entries(vp)) {
2705 cache_purge_impl(vp);
2712 * Remove all negative entries for a particular directory vnode.
2715 cache_purge_negative(struct vnode *vp)
2717 struct cache_freebatch batch;
2718 struct namecache *ncp, *nnp;
2721 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2722 if (LIST_EMPTY(&vp->v_cache_src))
2725 vlp = VP2VNODELOCK(vp);
2727 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2728 if (!(ncp->nc_flag & NCF_NEGATIVE))
2730 cache_zap_negative_locked_vnode_kl(ncp, vp);
2731 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2734 cache_free_batch(&batch);
2738 * Entry points for modifying VOP operations.
2741 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2742 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2745 ASSERT_VOP_IN_SEQC(fdvp);
2746 ASSERT_VOP_IN_SEQC(fvp);
2747 ASSERT_VOP_IN_SEQC(tdvp);
2749 ASSERT_VOP_IN_SEQC(tvp);
2754 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2755 ("%s: lingering negative entry", __func__));
2757 cache_remove_cnp(tdvp, tcnp);
2763 * Historically renaming was always purging all revelang entries,
2764 * but that's quite wasteful. In particular turns out that in many cases
2765 * the target file is immediately accessed after rename, inducing a cache
2768 * Recode this to reduce relocking and reuse the existing entry (if any)
2769 * instead of just removing it above and allocating a new one here.
2771 if (cache_rename_add) {
2772 cache_enter(tdvp, fvp, tcnp);
2777 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2780 ASSERT_VOP_IN_SEQC(dvp);
2781 ASSERT_VOP_IN_SEQC(vp);
2787 * Validate that if an entry exists it matches.
2790 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2792 struct namecache *ncp;
2796 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2797 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2799 blp = HASH2BUCKETLOCK(hash);
2801 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2802 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2803 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2804 if (ncp->nc_vp != vp)
2805 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p vp %p\n",
2806 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp,
2815 * Flush all entries referencing a particular filesystem.
2818 cache_purgevfs(struct mount *mp)
2820 struct vnode *vp, *mvp;
2822 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2824 * Somewhat wasteful iteration over all vnodes. Would be better to
2825 * support filtering and avoid the interlock to begin with.
2827 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2828 if (!cache_has_entries(vp)) {
2840 * Perform canonical checks and cache lookup and pass on to filesystem
2841 * through the vop_cachedlookup only if needed.
2845 vfs_cache_lookup(struct vop_lookup_args *ap)
2849 struct vnode **vpp = ap->a_vpp;
2850 struct componentname *cnp = ap->a_cnp;
2851 int flags = cnp->cn_flags;
2856 if (dvp->v_type != VDIR)
2859 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2860 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2863 error = vn_dir_check_exec(dvp, cnp);
2867 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2869 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2875 /* Implementation of the getcwd syscall. */
2877 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2883 buflen = uap->buflen;
2884 if (__predict_false(buflen < 2))
2886 if (buflen > MAXPATHLEN)
2887 buflen = MAXPATHLEN;
2889 buf = uma_zalloc(namei_zone, M_WAITOK);
2890 error = vn_getcwd(buf, &retbuf, &buflen);
2892 error = copyout(retbuf, uap->buf, buflen);
2893 uma_zfree(namei_zone, buf);
2898 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
2904 pwd = pwd_get_smr();
2905 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
2907 VFS_SMR_ASSERT_NOT_ENTERED();
2909 pwd = pwd_hold(curthread);
2910 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
2916 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2923 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2924 size_t size, int flags, enum uio_seg pathseg)
2926 struct nameidata nd;
2927 char *retbuf, *freebuf;
2932 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2933 pathseg, path, fd, &cap_fstat_rights, td);
2934 if ((error = namei(&nd)) != 0)
2936 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
2938 error = copyout(retbuf, buf, size);
2939 free(freebuf, M_TEMP);
2946 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2949 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2950 uap->flags, UIO_USERSPACE));
2954 * Retrieve the full filesystem path that correspond to a vnode from the name
2955 * cache (if available)
2958 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
2965 if (__predict_false(vp == NULL))
2968 buflen = MAXPATHLEN;
2969 buf = malloc(buflen, M_TEMP, M_WAITOK);
2971 pwd = pwd_get_smr();
2972 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
2973 VFS_SMR_ASSERT_NOT_ENTERED();
2975 pwd = pwd_hold(curthread);
2976 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
2987 * This function is similar to vn_fullpath, but it attempts to lookup the
2988 * pathname relative to the global root mount point. This is required for the
2989 * auditing sub-system, as audited pathnames must be absolute, relative to the
2990 * global root mount point.
2993 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
2999 if (__predict_false(vp == NULL))
3001 buflen = MAXPATHLEN;
3002 buf = malloc(buflen, M_TEMP, M_WAITOK);
3004 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3005 VFS_SMR_ASSERT_NOT_ENTERED();
3007 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3016 static struct namecache *
3017 vn_dd_from_dst(struct vnode *vp)
3019 struct namecache *ncp;
3021 cache_assert_vnode_locked(vp);
3022 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3023 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3030 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3033 struct namecache *ncp;
3037 vlp = VP2VNODELOCK(*vp);
3039 ncp = (*vp)->v_cache_dd;
3040 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3041 KASSERT(ncp == vn_dd_from_dst(*vp),
3042 ("%s: mismatch for dd entry (%p != %p)", __func__,
3043 ncp, vn_dd_from_dst(*vp)));
3045 ncp = vn_dd_from_dst(*vp);
3048 if (*buflen < ncp->nc_nlen) {
3051 counter_u64_add(numfullpathfail4, 1);
3053 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3057 *buflen -= ncp->nc_nlen;
3058 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3059 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3068 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3071 vn_lock(*vp, LK_SHARED | LK_RETRY);
3072 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3075 counter_u64_add(numfullpathfail2, 1);
3076 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3081 if (VN_IS_DOOMED(dvp)) {
3082 /* forced unmount */
3085 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3089 * *vp has its use count incremented still.
3096 * Resolve a directory to a pathname.
3098 * The name of the directory can always be found in the namecache or fetched
3099 * from the filesystem. There is also guaranteed to be only one parent, meaning
3100 * we can just follow vnodes up until we find the root.
3102 * The vnode must be referenced.
3105 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3106 size_t *len, size_t addend)
3108 #ifdef KDTRACE_HOOKS
3109 struct vnode *startvp = vp;
3114 bool slash_prefixed;
3116 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3117 VNPASS(vp->v_usecount > 0, vp);
3121 slash_prefixed = true;
3126 slash_prefixed = false;
3131 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3132 counter_u64_add(numfullpathcalls, 1);
3133 while (vp != rdir && vp != rootvnode) {
3135 * The vp vnode must be already fully constructed,
3136 * since it is either found in namecache or obtained
3137 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3138 * without obtaining the vnode lock.
3140 if ((vp->v_vflag & VV_ROOT) != 0) {
3141 vn_lock(vp, LK_RETRY | LK_SHARED);
3144 * With the vnode locked, check for races with
3145 * unmount, forced or not. Note that we
3146 * already verified that vp is not equal to
3147 * the root vnode, which means that
3148 * mnt_vnodecovered can be NULL only for the
3151 if (VN_IS_DOOMED(vp) ||
3152 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3153 vp1->v_mountedhere != vp->v_mount) {
3156 SDT_PROBE3(vfs, namecache, fullpath, return,
3166 if (vp->v_type != VDIR) {
3168 counter_u64_add(numfullpathfail1, 1);
3170 SDT_PROBE3(vfs, namecache, fullpath, return,
3174 error = vn_vptocnp(&vp, buf, &buflen);
3180 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3184 buf[--buflen] = '/';
3185 slash_prefixed = true;
3189 if (!slash_prefixed) {
3192 counter_u64_add(numfullpathfail4, 1);
3193 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3197 buf[--buflen] = '/';
3199 counter_u64_add(numfullpathfound, 1);
3202 *retbuf = buf + buflen;
3203 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3210 * Resolve an arbitrary vnode to a pathname.
3213 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3214 * resolve to a different path than the one used to find it
3215 * - namecache is not mandatory, meaning names are not guaranteed to be added
3216 * (in which case resolving fails)
3218 static void __inline
3219 cache_rev_failed_impl(int *reason, int line)
3224 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3227 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3228 char **retbuf, size_t *buflen, size_t addend)
3230 #ifdef KDTRACE_HOOKS
3231 struct vnode *startvp = vp;
3235 struct namecache *ncp;
3239 #ifdef KDTRACE_HOOKS
3242 seqc_t vp_seqc, tvp_seqc;
3245 VFS_SMR_ASSERT_ENTERED();
3247 if (!cache_fast_revlookup) {
3252 orig_buflen = *buflen;
3255 MPASS(*buflen >= 2);
3257 buf[*buflen] = '\0';
3260 if (vp == rdir || vp == rootvnode) {
3268 #ifdef KDTRACE_HOOKS
3272 ncp = NULL; /* for sdt probe down below */
3273 vp_seqc = vn_seqc_read_any(vp);
3274 if (seqc_in_modify(vp_seqc)) {
3275 cache_rev_failed(&reason);
3280 #ifdef KDTRACE_HOOKS
3283 if ((vp->v_vflag & VV_ROOT) != 0) {
3284 mp = atomic_load_ptr(&vp->v_mount);
3286 cache_rev_failed(&reason);
3289 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3290 tvp_seqc = vn_seqc_read_any(tvp);
3291 if (seqc_in_modify(tvp_seqc)) {
3292 cache_rev_failed(&reason);
3295 if (!vn_seqc_consistent(vp, vp_seqc)) {
3296 cache_rev_failed(&reason);
3303 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3305 cache_rev_failed(&reason);
3308 nc_flag = atomic_load_char(&ncp->nc_flag);
3309 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3310 cache_rev_failed(&reason);
3313 if (ncp->nc_nlen >= *buflen) {
3314 cache_rev_failed(&reason);
3318 *buflen -= ncp->nc_nlen;
3319 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3323 tvp_seqc = vn_seqc_read_any(tvp);
3324 if (seqc_in_modify(tvp_seqc)) {
3325 cache_rev_failed(&reason);
3328 if (!vn_seqc_consistent(vp, vp_seqc)) {
3329 cache_rev_failed(&reason);
3333 * Acquire fence provided by vn_seqc_read_any above.
3335 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3336 cache_rev_failed(&reason);
3339 if (!cache_ncp_canuse(ncp)) {
3340 cache_rev_failed(&reason);
3345 if (vp == rdir || vp == rootvnode)
3350 *retbuf = buf + *buflen;
3351 *buflen = orig_buflen - *buflen + addend;
3352 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3356 *buflen = orig_buflen;
3357 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3363 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3366 size_t orig_buflen, addend;
3372 orig_buflen = *buflen;
3376 if (vp->v_type != VDIR) {
3378 buf[*buflen] = '\0';
3379 error = vn_vptocnp(&vp, buf, buflen);
3388 addend = orig_buflen - *buflen;
3391 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3395 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3397 * Since the namecache does not track hardlinks, the caller is expected to first
3398 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3400 * Then we have 2 cases:
3401 * - if the found vnode is a directory, the path can be constructed just by
3402 * following names up the chain
3403 * - otherwise we populate the buffer with the saved name and start resolving
3407 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3412 struct componentname *cnp;
3420 if (*buflen > MAXPATHLEN)
3421 *buflen = MAXPATHLEN;
3423 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3428 * Check for VBAD to work around the vp_crossmp bug in lookup().
3430 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3431 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3432 * If the type is VDIR (like in this very case) we can skip looking
3433 * at ni_dvp in the first place. However, since vnodes get passed here
3434 * unlocked the target may transition to doomed state (type == VBAD)
3435 * before we get to evaluate the condition. If this happens, we will
3436 * populate part of the buffer and descend to vn_fullpath_dir with
3437 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3439 * This should be atomic_load(&vp->v_type) but it is illegal to take
3440 * an address of a bit field, even if said field is sized to char.
3441 * Work around the problem by reading the value into a full-sized enum
3442 * and then re-reading it with atomic_load which will still prevent
3443 * the compiler from re-reading down the road.
3446 type = atomic_load_int(&type);
3453 addend = cnp->cn_namelen + 2;
3454 if (*buflen < addend) {
3459 tmpbuf = buf + *buflen;
3461 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3462 tmpbuf[addend - 1] = '\0';
3467 pwd = pwd_get_smr();
3468 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3470 VFS_SMR_ASSERT_NOT_ENTERED();
3472 pwd = pwd_hold(curthread);
3474 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3490 vn_dir_dd_ino(struct vnode *vp)
3492 struct namecache *ncp;
3497 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3498 vlp = VP2VNODELOCK(vp);
3500 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3501 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3504 vs = vget_prep(ddvp);
3506 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3515 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3517 struct namecache *ncp;
3521 vlp = VP2VNODELOCK(vp);
3523 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3524 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3530 l = min(ncp->nc_nlen, buflen - 1);
3531 memcpy(buf, ncp->nc_name, l);
3538 * This function updates path string to vnode's full global path
3539 * and checks the size of the new path string against the pathlen argument.
3541 * Requires a locked, referenced vnode.
3542 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3544 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3545 * because it falls back to the ".." lookup if the namecache lookup fails.
3548 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3551 struct nameidata nd;
3556 ASSERT_VOP_ELOCKED(vp, __func__);
3558 /* Construct global filesystem path from vp. */
3560 error = vn_fullpath_global(vp, &rpath, &fbuf);
3567 if (strlen(rpath) >= pathlen) {
3569 error = ENAMETOOLONG;
3574 * Re-lookup the vnode by path to detect a possible rename.
3575 * As a side effect, the vnode is relocked.
3576 * If vnode was renamed, return ENOENT.
3578 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3579 UIO_SYSSPACE, path, td);
3585 NDFREE(&nd, NDF_ONLY_PNBUF);
3589 strcpy(path, rpath);
3602 db_print_vpath(struct vnode *vp)
3605 while (vp != NULL) {
3606 db_printf("%p: ", vp);
3607 if (vp == rootvnode) {
3611 if (vp->v_vflag & VV_ROOT) {
3612 db_printf("<mount point>");
3613 vp = vp->v_mount->mnt_vnodecovered;
3615 struct namecache *ncp;
3619 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3622 for (i = 0; i < ncp->nc_nlen; i++)
3623 db_printf("%c", *ncn++);
3636 DB_SHOW_COMMAND(vpath, db_show_vpath)
3641 db_printf("usage: show vpath <struct vnode *>\n");
3645 vp = (struct vnode *)addr;
3651 static int cache_fast_lookup = 1;
3652 static char __read_frequently cache_fast_lookup_enabled = true;
3654 #define CACHE_FPL_FAILED -2020
3657 cache_fast_lookup_enabled_recalc(void)
3663 mac_on = mac_vnode_check_lookup_enabled();
3664 mac_on |= mac_vnode_check_readlink_enabled();
3669 lookup_flag = atomic_load_int(&cache_fast_lookup);
3670 if (lookup_flag && !mac_on) {
3671 atomic_store_char(&cache_fast_lookup_enabled, true);
3673 atomic_store_char(&cache_fast_lookup_enabled, false);
3678 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
3682 old = atomic_load_int(&cache_fast_lookup);
3683 error = sysctl_handle_int(oidp, arg1, arg2, req);
3684 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
3685 cache_fast_lookup_enabled_recalc();
3688 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
3689 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
3692 * Components of nameidata (or objects it can point to) which may
3693 * need restoring in case fast path lookup fails.
3695 struct nameidata_outer {
3700 struct nameidata_saved {
3708 struct cache_fpl_debug {
3714 struct nameidata *ndp;
3715 struct componentname *cnp;
3722 struct nameidata_saved snd;
3723 struct nameidata_outer snd_outer;
3725 enum cache_fpl_status status:8;
3731 struct cache_fpl_debug debug;
3735 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
3736 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
3737 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
3738 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
3739 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
3740 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
3741 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
3742 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
3743 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
3746 cache_fpl_cleanup_cnp(struct componentname *cnp)
3749 uma_zfree(namei_zone, cnp->cn_pnbuf);
3751 cnp->cn_pnbuf = NULL;
3752 cnp->cn_nameptr = NULL;
3756 static struct vnode *
3757 cache_fpl_handle_root(struct cache_fpl *fpl)
3759 struct nameidata *ndp;
3760 struct componentname *cnp;
3765 MPASS(*(cnp->cn_nameptr) == '/');
3767 cache_fpl_pathlen_dec(fpl);
3769 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
3772 cache_fpl_pathlen_dec(fpl);
3773 } while (*(cnp->cn_nameptr) == '/');
3776 return (ndp->ni_rootdir);
3780 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
3783 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
3784 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
3788 cache_fpl_checkpoint(struct cache_fpl *fpl)
3792 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3793 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
3798 cache_fpl_restore_partial(struct cache_fpl *fpl)
3801 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
3803 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
3808 cache_fpl_restore_abort(struct cache_fpl *fpl)
3811 cache_fpl_restore_partial(fpl);
3813 * It is 0 on entry by API contract.
3815 fpl->ndp->ni_resflags = 0;
3816 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
3817 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
3821 #define cache_fpl_smr_assert_entered(fpl) ({ \
3822 struct cache_fpl *_fpl = (fpl); \
3823 MPASS(_fpl->in_smr == true); \
3824 VFS_SMR_ASSERT_ENTERED(); \
3826 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
3827 struct cache_fpl *_fpl = (fpl); \
3828 MPASS(_fpl->in_smr == false); \
3829 VFS_SMR_ASSERT_NOT_ENTERED(); \
3832 cache_fpl_assert_status(struct cache_fpl *fpl)
3835 switch (fpl->status) {
3836 case CACHE_FPL_STATUS_UNSET:
3837 __assert_unreachable();
3839 case CACHE_FPL_STATUS_DESTROYED:
3840 case CACHE_FPL_STATUS_ABORTED:
3841 case CACHE_FPL_STATUS_PARTIAL:
3842 case CACHE_FPL_STATUS_HANDLED:
3847 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3848 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3849 #define cache_fpl_assert_status(fpl) do { } while (0)
3852 #define cache_fpl_smr_enter_initial(fpl) ({ \
3853 struct cache_fpl *_fpl = (fpl); \
3855 _fpl->in_smr = true; \
3858 #define cache_fpl_smr_enter(fpl) ({ \
3859 struct cache_fpl *_fpl = (fpl); \
3860 MPASS(_fpl->in_smr == false); \
3862 _fpl->in_smr = true; \
3865 #define cache_fpl_smr_exit(fpl) ({ \
3866 struct cache_fpl *_fpl = (fpl); \
3867 MPASS(_fpl->in_smr == true); \
3869 _fpl->in_smr = false; \
3873 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
3876 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3877 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3878 ("%s: converting to abort from %d at %d, set at %d\n",
3879 __func__, fpl->status, line, fpl->line));
3881 cache_fpl_smr_assert_not_entered(fpl);
3882 fpl->status = CACHE_FPL_STATUS_ABORTED;
3884 return (CACHE_FPL_FAILED);
3887 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
3889 static int __noinline
3890 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3892 struct nameidata *ndp;
3893 struct componentname *cnp;
3898 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3899 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3900 ("%s: converting to abort from %d at %d, set at %d\n",
3901 __func__, fpl->status, line, fpl->line));
3903 fpl->status = CACHE_FPL_STATUS_ABORTED;
3906 cache_fpl_smr_exit(fpl);
3907 cache_fpl_restore_abort(fpl);
3909 * Resolving symlinks overwrites data passed by the caller.
3912 if (ndp->ni_loopcnt > 0) {
3913 fpl->status = CACHE_FPL_STATUS_DESTROYED;
3914 cache_fpl_cleanup_cnp(cnp);
3916 return (CACHE_FPL_FAILED);
3919 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
3921 static int __noinline
3922 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3925 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3926 ("%s: setting to partial at %d, but already set to %d at %d\n",
3927 __func__, line, fpl->status, fpl->line));
3928 cache_fpl_smr_assert_entered(fpl);
3929 fpl->status = CACHE_FPL_STATUS_PARTIAL;
3931 return (cache_fplookup_partial_setup(fpl));
3934 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
3937 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
3940 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3941 ("%s: setting to handled at %d, but already set to %d at %d\n",
3942 __func__, line, fpl->status, fpl->line));
3943 cache_fpl_smr_assert_not_entered(fpl);
3944 fpl->status = CACHE_FPL_STATUS_HANDLED;
3949 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
3952 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
3955 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3956 ("%s: setting to handled at %d, but already set to %d at %d\n",
3957 __func__, line, fpl->status, fpl->line));
3959 MPASS(error != CACHE_FPL_FAILED);
3960 cache_fpl_smr_assert_not_entered(fpl);
3961 fpl->status = CACHE_FPL_STATUS_HANDLED;
3965 fpl->savename = false;
3969 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
3972 cache_fpl_terminated(struct cache_fpl *fpl)
3975 return (fpl->status != CACHE_FPL_STATUS_UNSET);
3978 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3979 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
3980 FAILIFEXISTS | FOLLOW | LOCKSHARED | SAVENAME | SAVESTART | WILLBEDIR | \
3981 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
3983 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3984 (ISDOTDOT | MAKEENTRY | ISLASTCN)
3986 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3987 "supported and internal flags overlap");
3990 cache_fpl_islastcn(struct nameidata *ndp)
3993 return (*ndp->ni_next == 0);
3997 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4000 return (*(fpl->nulchar - 1) == '/');
4004 cache_fpl_isdotdot(struct componentname *cnp)
4007 if (cnp->cn_namelen == 2 &&
4008 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4014 cache_can_fplookup(struct cache_fpl *fpl)
4016 struct nameidata *ndp;
4017 struct componentname *cnp;
4022 td = cnp->cn_thread;
4024 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4025 cache_fpl_aborted_early(fpl);
4028 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4029 cache_fpl_aborted_early(fpl);
4032 if (IN_CAPABILITY_MODE(td)) {
4033 cache_fpl_aborted_early(fpl);
4036 if (AUDITING_TD(td)) {
4037 cache_fpl_aborted_early(fpl);
4040 if (ndp->ni_startdir != NULL) {
4041 cache_fpl_aborted_early(fpl);
4048 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4050 struct nameidata *ndp;
4055 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4056 if (__predict_false(error != 0)) {
4057 return (cache_fpl_aborted(fpl));
4059 fpl->fsearch = fsearch;
4063 static int __noinline
4064 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4067 struct componentname *cnp;
4073 cache_fpl_smr_exit(fpl);
4074 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4075 return (cache_fpl_handled_error(fpl, ENOENT));
4077 return (cache_fpl_aborted(fpl));
4081 * The target vnode is not supported, prepare for the slow path to take over.
4083 static int __noinline
4084 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4086 struct nameidata *ndp;
4087 struct componentname *cnp;
4097 dvp_seqc = fpl->dvp_seqc;
4099 if (!pwd_hold_smr(pwd)) {
4100 return (cache_fpl_aborted(fpl));
4104 * Note that seqc is checked before the vnode is locked, so by
4105 * the time regular lookup gets to it it may have moved.
4107 * Ultimately this does not affect correctness, any lookup errors
4108 * are userspace racing with itself. It is guaranteed that any
4109 * path which ultimately gets found could also have been found
4110 * by regular lookup going all the way in absence of concurrent
4113 dvs = vget_prep_smr(dvp);
4114 cache_fpl_smr_exit(fpl);
4115 if (__predict_false(dvs == VGET_NONE)) {
4117 return (cache_fpl_aborted(fpl));
4120 vget_finish_ref(dvp, dvs);
4121 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4124 return (cache_fpl_aborted(fpl));
4127 cache_fpl_restore_partial(fpl);
4129 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4130 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4131 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4135 ndp->ni_startdir = dvp;
4136 cnp->cn_flags |= MAKEENTRY;
4137 if (cache_fpl_islastcn(ndp))
4138 cnp->cn_flags |= ISLASTCN;
4139 if (cache_fpl_isdotdot(cnp))
4140 cnp->cn_flags |= ISDOTDOT;
4143 * Skip potential extra slashes parsing did not take care of.
4144 * cache_fplookup_skip_slashes explains the mechanism.
4146 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4149 cache_fpl_pathlen_dec(fpl);
4150 } while (*(cnp->cn_nameptr) == '/');
4153 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4155 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4156 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4157 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4158 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4165 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4167 struct componentname *cnp;
4174 tvp_seqc = fpl->tvp_seqc;
4176 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4177 lkflags = LK_SHARED;
4178 if ((cnp->cn_flags & LOCKSHARED) == 0)
4179 lkflags = LK_EXCLUSIVE;
4180 error = vget_finish(tvp, lkflags, tvs);
4181 if (__predict_false(error != 0)) {
4182 return (cache_fpl_aborted(fpl));
4185 vget_finish_ref(tvp, tvs);
4188 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4189 if ((cnp->cn_flags & LOCKLEAF) != 0)
4193 return (cache_fpl_aborted(fpl));
4196 return (cache_fpl_handled(fpl));
4200 * They want to possibly modify the state of the namecache.
4202 static int __noinline
4203 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4205 struct nameidata *ndp;
4206 struct componentname *cnp;
4208 struct vnode *dvp, *tvp;
4217 dvp_seqc = fpl->dvp_seqc;
4219 MPASS(*(cnp->cn_nameptr) != '/');
4220 MPASS(cache_fpl_islastcn(ndp));
4221 if ((cnp->cn_flags & LOCKPARENT) == 0)
4222 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4223 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4224 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4225 cnp->cn_nameiop == RENAME);
4226 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4227 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4229 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4230 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4234 * Regular lookup nulifies the slash, which we don't do here.
4235 * Don't take chances with filesystem routines seeing it for
4238 if (cache_fpl_istrailingslash(fpl)) {
4239 return (cache_fpl_partial(fpl));
4242 mp = atomic_load_ptr(&dvp->v_mount);
4243 if (__predict_false(mp == NULL)) {
4244 return (cache_fpl_aborted(fpl));
4247 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4248 cache_fpl_smr_exit(fpl);
4250 * Original code keeps not checking for CREATE which
4251 * might be a bug. For now let the old lookup decide.
4253 if (cnp->cn_nameiop == CREATE) {
4254 return (cache_fpl_aborted(fpl));
4256 return (cache_fpl_handled_error(fpl, EROFS));
4259 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4260 cache_fpl_smr_exit(fpl);
4261 return (cache_fpl_handled_error(fpl, EEXIST));
4265 * Secure access to dvp; check cache_fplookup_partial_setup for
4268 * XXX At least UFS requires its lookup routine to be called for
4269 * the last path component, which leads to some level of complication
4271 * - the target routine always locks the target vnode, but our caller
4272 * may not need it locked
4273 * - some of the VOP machinery asserts that the parent is locked, which
4274 * once more may be not required
4276 * TODO: add a flag for filesystems which don't need this.
4278 dvs = vget_prep_smr(dvp);
4279 cache_fpl_smr_exit(fpl);
4280 if (__predict_false(dvs == VGET_NONE)) {
4281 return (cache_fpl_aborted(fpl));
4284 vget_finish_ref(dvp, dvs);
4285 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4287 return (cache_fpl_aborted(fpl));
4290 error = vn_lock(dvp, LK_EXCLUSIVE);
4291 if (__predict_false(error != 0)) {
4293 return (cache_fpl_aborted(fpl));
4297 cnp->cn_flags |= ISLASTCN;
4299 cnp->cn_flags |= MAKEENTRY;
4300 if (cache_fpl_isdotdot(cnp))
4301 cnp->cn_flags |= ISDOTDOT;
4302 cnp->cn_lkflags = LK_EXCLUSIVE;
4303 error = VOP_LOOKUP(dvp, &tvp, cnp);
4311 return (cache_fpl_handled_error(fpl, error));
4314 return (cache_fpl_aborted(fpl));
4318 fpl->savename = (cnp->cn_flags & SAVENAME) != 0;
4321 if ((cnp->cn_flags & SAVESTART) != 0) {
4322 ndp->ni_startdir = dvp;
4323 vrefact(ndp->ni_startdir);
4324 cnp->cn_flags |= SAVENAME;
4325 fpl->savename = true;
4327 MPASS(error == EJUSTRETURN);
4328 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4331 return (cache_fpl_handled(fpl));
4335 * There are very hairy corner cases concerning various flag combinations
4336 * and locking state. In particular here we only hold one lock instead of
4339 * Skip the complexity as it is of no significance for normal workloads.
4341 if (__predict_false(tvp == dvp)) {
4344 return (cache_fpl_aborted(fpl));
4348 * If they want the symlink itself we are fine, but if they want to
4349 * follow it regular lookup has to be engaged.
4351 if (tvp->v_type == VLNK) {
4352 if ((cnp->cn_flags & FOLLOW) != 0) {
4355 return (cache_fpl_aborted(fpl));
4360 * Since we expect this to be the terminal vnode it should almost never
4363 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4366 return (cache_fpl_aborted(fpl));
4369 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4372 return (cache_fpl_handled_error(fpl, EEXIST));
4375 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4379 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4383 if ((cnp->cn_flags & SAVESTART) != 0) {
4384 ndp->ni_startdir = dvp;
4385 vrefact(ndp->ni_startdir);
4386 cnp->cn_flags |= SAVENAME;
4387 fpl->savename = true;
4390 return (cache_fpl_handled(fpl));
4393 static int __noinline
4394 cache_fplookup_modifying(struct cache_fpl *fpl)
4396 struct nameidata *ndp;
4400 if (!cache_fpl_islastcn(ndp)) {
4401 return (cache_fpl_partial(fpl));
4403 return (cache_fplookup_final_modifying(fpl));
4406 static int __noinline
4407 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4409 struct componentname *cnp;
4410 enum vgetstate dvs, tvs;
4411 struct vnode *dvp, *tvp;
4417 dvp_seqc = fpl->dvp_seqc;
4420 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4423 * This is less efficient than it can be for simplicity.
4425 dvs = vget_prep_smr(dvp);
4426 if (__predict_false(dvs == VGET_NONE)) {
4427 return (cache_fpl_aborted(fpl));
4429 tvs = vget_prep_smr(tvp);
4430 if (__predict_false(tvs == VGET_NONE)) {
4431 cache_fpl_smr_exit(fpl);
4432 vget_abort(dvp, dvs);
4433 return (cache_fpl_aborted(fpl));
4436 cache_fpl_smr_exit(fpl);
4438 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4439 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4440 if (__predict_false(error != 0)) {
4441 vget_abort(tvp, tvs);
4442 return (cache_fpl_aborted(fpl));
4445 vget_finish_ref(dvp, dvs);
4448 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4449 vget_abort(tvp, tvs);
4450 if ((cnp->cn_flags & LOCKPARENT) != 0)
4454 return (cache_fpl_aborted(fpl));
4457 error = cache_fplookup_final_child(fpl, tvs);
4458 if (__predict_false(error != 0)) {
4459 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
4460 if ((cnp->cn_flags & LOCKPARENT) != 0)
4467 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4472 cache_fplookup_final(struct cache_fpl *fpl)
4474 struct componentname *cnp;
4476 struct vnode *dvp, *tvp;
4481 dvp_seqc = fpl->dvp_seqc;
4484 MPASS(*(cnp->cn_nameptr) != '/');
4486 if (cnp->cn_nameiop != LOOKUP) {
4487 return (cache_fplookup_final_modifying(fpl));
4490 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4491 return (cache_fplookup_final_withparent(fpl));
4493 tvs = vget_prep_smr(tvp);
4494 if (__predict_false(tvs == VGET_NONE)) {
4495 return (cache_fpl_partial(fpl));
4498 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4499 cache_fpl_smr_exit(fpl);
4500 vget_abort(tvp, tvs);
4501 return (cache_fpl_aborted(fpl));
4504 cache_fpl_smr_exit(fpl);
4505 return (cache_fplookup_final_child(fpl, tvs));
4509 * Comment from locked lookup:
4510 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4511 * directory, e.g. like "/." or ".".
4513 static int __noinline
4514 cache_fplookup_degenerate(struct cache_fpl *fpl)
4516 struct componentname *cnp;
4524 fpl->tvp = fpl->dvp;
4525 fpl->tvp_seqc = fpl->dvp_seqc;
4531 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4533 ("%s: encountered non-slash; string [%s]\n", __func__,
4538 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4539 cache_fpl_smr_exit(fpl);
4540 return (cache_fpl_handled_error(fpl, EISDIR));
4543 MPASS((cnp->cn_flags & SAVESTART) == 0);
4545 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4546 return (cache_fplookup_final_withparent(fpl));
4549 dvs = vget_prep_smr(dvp);
4550 cache_fpl_smr_exit(fpl);
4551 if (__predict_false(dvs == VGET_NONE)) {
4552 return (cache_fpl_aborted(fpl));
4555 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4556 lkflags = LK_SHARED;
4557 if ((cnp->cn_flags & LOCKSHARED) == 0)
4558 lkflags = LK_EXCLUSIVE;
4559 error = vget_finish(dvp, lkflags, dvs);
4560 if (__predict_false(error != 0)) {
4561 return (cache_fpl_aborted(fpl));
4564 vget_finish_ref(dvp, dvs);
4566 return (cache_fpl_handled(fpl));
4569 static int __noinline
4570 cache_fplookup_noentry(struct cache_fpl *fpl)
4572 struct nameidata *ndp;
4573 struct componentname *cnp;
4575 struct vnode *dvp, *tvp;
4583 dvp_seqc = fpl->dvp_seqc;
4585 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4586 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4587 MPASS(!cache_fpl_isdotdot(cnp));
4590 * Hack: delayed name len checking.
4592 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4593 cache_fpl_smr_exit(fpl);
4594 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
4597 if (cnp->cn_nameptr[0] == '/') {
4598 return (cache_fplookup_skip_slashes(fpl));
4601 if (cnp->cn_nameptr[0] == '\0') {
4602 if (fpl->tvp == NULL) {
4603 return (cache_fplookup_degenerate(fpl));
4605 return (cache_fplookup_trailingslash(fpl));
4608 if (cnp->cn_nameiop != LOOKUP) {
4610 return (cache_fplookup_modifying(fpl));
4613 MPASS((cnp->cn_flags & SAVESTART) == 0);
4616 * Only try to fill in the component if it is the last one,
4617 * otherwise not only there may be several to handle but the
4618 * walk may be complicated.
4620 if (!cache_fpl_islastcn(ndp)) {
4621 return (cache_fpl_partial(fpl));
4625 * Regular lookup nulifies the slash, which we don't do here.
4626 * Don't take chances with filesystem routines seeing it for
4629 if (cache_fpl_istrailingslash(fpl)) {
4630 return (cache_fpl_partial(fpl));
4634 * Secure access to dvp; check cache_fplookup_partial_setup for
4637 dvs = vget_prep_smr(dvp);
4638 cache_fpl_smr_exit(fpl);
4639 if (__predict_false(dvs == VGET_NONE)) {
4640 return (cache_fpl_aborted(fpl));
4643 vget_finish_ref(dvp, dvs);
4644 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4646 return (cache_fpl_aborted(fpl));
4649 error = vn_lock(dvp, LK_SHARED);
4650 if (__predict_false(error != 0)) {
4652 return (cache_fpl_aborted(fpl));
4657 * TODO: provide variants which don't require locking either vnode.
4659 cnp->cn_flags |= ISLASTCN;
4660 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4662 cnp->cn_flags |= MAKEENTRY;
4663 cnp->cn_lkflags = LK_SHARED;
4664 if ((cnp->cn_flags & LOCKSHARED) == 0) {
4665 cnp->cn_lkflags = LK_EXCLUSIVE;
4667 error = VOP_LOOKUP(dvp, &tvp, cnp);
4675 return (cache_fpl_handled_error(fpl, error));
4678 return (cache_fpl_aborted(fpl));
4682 if (!fpl->savename) {
4683 MPASS((cnp->cn_flags & SAVENAME) == 0);
4687 MPASS(error == EJUSTRETURN);
4688 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4690 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4693 return (cache_fpl_handled(fpl));
4696 if (tvp->v_type == VLNK) {
4697 if ((cnp->cn_flags & FOLLOW) != 0) {
4700 return (cache_fpl_aborted(fpl));
4704 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4707 return (cache_fpl_aborted(fpl));
4710 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4714 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
4716 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
4719 return (cache_fpl_handled(fpl));
4722 static int __noinline
4723 cache_fplookup_dot(struct cache_fpl *fpl)
4727 MPASS(!seqc_in_modify(fpl->dvp_seqc));
4729 * Just re-assign the value. seqc will be checked later for the first
4730 * non-dot path component in line and/or before deciding to return the
4733 fpl->tvp = fpl->dvp;
4734 fpl->tvp_seqc = fpl->dvp_seqc;
4736 counter_u64_add(dothits, 1);
4737 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
4740 if (cache_fplookup_is_mp(fpl)) {
4741 error = cache_fplookup_cross_mount(fpl);
4746 static int __noinline
4747 cache_fplookup_dotdot(struct cache_fpl *fpl)
4749 struct nameidata *ndp;
4750 struct componentname *cnp;
4751 struct namecache *ncp;
4760 MPASS(cache_fpl_isdotdot(cnp));
4763 * XXX this is racy the same way regular lookup is
4765 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
4767 if (dvp == pr->pr_root)
4770 if (dvp == ndp->ni_rootdir ||
4771 dvp == ndp->ni_topdir ||
4775 fpl->tvp_seqc = vn_seqc_read_any(dvp);
4776 if (seqc_in_modify(fpl->tvp_seqc)) {
4777 return (cache_fpl_aborted(fpl));
4782 if ((dvp->v_vflag & VV_ROOT) != 0) {
4785 * The opposite of climb mount is needed here.
4787 return (cache_fpl_partial(fpl));
4790 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
4792 return (cache_fpl_aborted(fpl));
4795 nc_flag = atomic_load_char(&ncp->nc_flag);
4796 if ((nc_flag & NCF_ISDOTDOT) != 0) {
4797 if ((nc_flag & NCF_NEGATIVE) != 0)
4798 return (cache_fpl_aborted(fpl));
4799 fpl->tvp = ncp->nc_vp;
4801 fpl->tvp = ncp->nc_dvp;
4804 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
4805 if (seqc_in_modify(fpl->tvp_seqc)) {
4806 return (cache_fpl_partial(fpl));
4810 * Acquire fence provided by vn_seqc_read_any above.
4812 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
4813 return (cache_fpl_aborted(fpl));
4816 if (!cache_ncp_canuse(ncp)) {
4817 return (cache_fpl_aborted(fpl));
4820 counter_u64_add(dotdothits, 1);
4824 static int __noinline
4825 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
4830 nc_flag = atomic_load_char(&ncp->nc_flag);
4831 MPASS((nc_flag & NCF_NEGATIVE) != 0);
4833 * If they want to create an entry we need to replace this one.
4835 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
4837 return (cache_fplookup_modifying(fpl));
4839 neg_promote = cache_neg_hit_prep(ncp);
4840 if (!cache_fpl_neg_ncp_canuse(ncp)) {
4841 cache_neg_hit_abort(ncp);
4842 return (cache_fpl_partial(fpl));
4845 return (cache_fplookup_negative_promote(fpl, ncp, hash));
4847 cache_neg_hit_finish(ncp);
4848 cache_fpl_smr_exit(fpl);
4849 return (cache_fpl_handled_error(fpl, ENOENT));
4853 * Resolve a symlink. Called by filesystem-specific routines.
4856 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
4859 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
4861 struct nameidata *ndp;
4862 struct componentname *cnp;
4868 if (__predict_false(len == 0)) {
4872 if (__predict_false(len > MAXPATHLEN - 2)) {
4873 if (cache_fpl_istrailingslash(fpl)) {
4878 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
4880 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4881 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4882 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4883 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4887 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
4888 return (ENAMETOOLONG);
4891 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
4896 if (ndp->ni_pathlen > 1) {
4897 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
4899 if (cache_fpl_istrailingslash(fpl)) {
4901 cnp->cn_pnbuf[len] = '/';
4902 cnp->cn_pnbuf[len + 1] = '\0';
4904 cnp->cn_pnbuf[len] = '\0';
4907 bcopy(string, cnp->cn_pnbuf, len);
4909 ndp->ni_pathlen += adjust;
4910 cache_fpl_pathlen_add(fpl, adjust);
4911 cnp->cn_nameptr = cnp->cn_pnbuf;
4912 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
4917 static int __noinline
4918 cache_fplookup_symlink(struct cache_fpl *fpl)
4921 struct nameidata *ndp;
4922 struct componentname *cnp;
4923 struct vnode *dvp, *tvp;
4931 if (cache_fpl_islastcn(ndp)) {
4932 if ((cnp->cn_flags & FOLLOW) == 0) {
4933 return (cache_fplookup_final(fpl));
4937 mp = atomic_load_ptr(&dvp->v_mount);
4938 if (__predict_false(mp == NULL)) {
4939 return (cache_fpl_aborted(fpl));
4943 * Note this check races against setting the flag just like regular
4946 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
4947 cache_fpl_smr_exit(fpl);
4948 return (cache_fpl_handled_error(fpl, EACCES));
4951 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
4952 if (__predict_false(error != 0)) {
4955 return (cache_fpl_partial(fpl));
4959 cache_fpl_smr_exit(fpl);
4960 return (cache_fpl_handled_error(fpl, error));
4962 return (cache_fpl_aborted(fpl));
4966 if (*(cnp->cn_nameptr) == '/') {
4967 fpl->dvp = cache_fpl_handle_root(fpl);
4968 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
4969 if (seqc_in_modify(fpl->dvp_seqc)) {
4970 return (cache_fpl_aborted(fpl));
4977 cache_fplookup_next(struct cache_fpl *fpl)
4979 struct componentname *cnp;
4980 struct namecache *ncp;
4981 struct vnode *dvp, *tvp;
4990 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
4991 if (cnp->cn_namelen == 1) {
4992 return (cache_fplookup_dot(fpl));
4994 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
4995 return (cache_fplookup_dotdot(fpl));
4999 MPASS(!cache_fpl_isdotdot(cnp));
5001 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5002 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5003 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5007 if (__predict_false(ncp == NULL)) {
5008 return (cache_fplookup_noentry(fpl));
5011 tvp = atomic_load_ptr(&ncp->nc_vp);
5012 nc_flag = atomic_load_char(&ncp->nc_flag);
5013 if ((nc_flag & NCF_NEGATIVE) != 0) {
5014 return (cache_fplookup_neg(fpl, ncp, hash));
5017 if (!cache_ncp_canuse(ncp)) {
5018 return (cache_fpl_partial(fpl));
5022 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5023 if (seqc_in_modify(fpl->tvp_seqc)) {
5024 return (cache_fpl_partial(fpl));
5027 counter_u64_add(numposhits, 1);
5028 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5031 if (cache_fplookup_is_mp(fpl)) {
5032 error = cache_fplookup_cross_mount(fpl);
5038 cache_fplookup_mp_supported(struct mount *mp)
5042 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5048 * Walk up the mount stack (if any).
5050 * Correctness is provided in the following ways:
5051 * - all vnodes are protected from freeing with SMR
5052 * - struct mount objects are type stable making them always safe to access
5053 * - stability of the particular mount is provided by busying it
5054 * - relationship between the vnode which is mounted on and the mount is
5055 * verified with the vnode sequence counter after busying
5056 * - association between root vnode of the mount and the mount is protected
5059 * From that point on we can read the sequence counter of the root vnode
5060 * and get the next mount on the stack (if any) using the same protection.
5062 * By the end of successful walk we are guaranteed the reached state was
5063 * indeed present at least at some point which matches the regular lookup.
5065 static int __noinline
5066 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5068 struct mount *mp, *prev_mp;
5069 struct mount_pcpu *mpcpu, *prev_mpcpu;
5074 vp_seqc = fpl->tvp_seqc;
5076 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5077 mp = atomic_load_ptr(&vp->v_mountedhere);
5078 if (__predict_false(mp == NULL)) {
5084 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5085 if (prev_mp != NULL)
5086 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5087 return (cache_fpl_partial(fpl));
5089 if (prev_mp != NULL)
5090 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5091 if (!vn_seqc_consistent(vp, vp_seqc)) {
5092 vfs_op_thread_exit_crit(mp, mpcpu);
5093 return (cache_fpl_partial(fpl));
5095 if (!cache_fplookup_mp_supported(mp)) {
5096 vfs_op_thread_exit_crit(mp, mpcpu);
5097 return (cache_fpl_partial(fpl));
5099 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5101 vfs_op_thread_exit_crit(mp, mpcpu);
5102 return (cache_fpl_partial(fpl));
5104 vp_seqc = vn_seqc_read_any(vp);
5105 if (seqc_in_modify(vp_seqc)) {
5106 vfs_op_thread_exit_crit(mp, mpcpu);
5107 return (cache_fpl_partial(fpl));
5111 mp = atomic_load_ptr(&vp->v_mountedhere);
5116 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5118 fpl->tvp_seqc = vp_seqc;
5122 static int __noinline
5123 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5126 struct mount_pcpu *mpcpu;
5131 vp_seqc = fpl->tvp_seqc;
5133 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
5134 mp = atomic_load_ptr(&vp->v_mountedhere);
5135 if (__predict_false(mp == NULL)) {
5139 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5140 return (cache_fpl_partial(fpl));
5142 if (!vn_seqc_consistent(vp, vp_seqc)) {
5143 vfs_op_thread_exit_crit(mp, mpcpu);
5144 return (cache_fpl_partial(fpl));
5146 if (!cache_fplookup_mp_supported(mp)) {
5147 vfs_op_thread_exit_crit(mp, mpcpu);
5148 return (cache_fpl_partial(fpl));
5150 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5151 if (__predict_false(vp == NULL)) {
5152 vfs_op_thread_exit_crit(mp, mpcpu);
5153 return (cache_fpl_partial(fpl));
5155 vp_seqc = vn_seqc_read_any(vp);
5156 vfs_op_thread_exit_crit(mp, mpcpu);
5157 if (seqc_in_modify(vp_seqc)) {
5158 return (cache_fpl_partial(fpl));
5160 mp = atomic_load_ptr(&vp->v_mountedhere);
5161 if (__predict_false(mp != NULL)) {
5163 * There are possibly more mount points on top.
5164 * Normally this does not happen so for simplicity just start
5167 return (cache_fplookup_climb_mount(fpl));
5171 fpl->tvp_seqc = vp_seqc;
5176 * Check if a vnode is mounted on.
5179 cache_fplookup_is_mp(struct cache_fpl *fpl)
5184 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5190 * The code was originally copy-pasted from regular lookup and despite
5191 * clean ups leaves performance on the table. Any modifications here
5192 * must take into account that in case off fallback the resulting
5193 * nameidata state has to be compatible with the original.
5197 * Debug ni_pathlen tracking.
5201 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5204 fpl->debug.ni_pathlen += n;
5205 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5206 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5210 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5213 fpl->debug.ni_pathlen -= n;
5214 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5215 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5219 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5222 cache_fpl_pathlen_add(fpl, 1);
5226 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5229 cache_fpl_pathlen_sub(fpl, 1);
5233 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5238 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5243 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5248 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5254 cache_fplookup_parse(struct cache_fpl *fpl)
5256 struct nameidata *ndp;
5257 struct componentname *cnp;
5267 * Find the end of this path component, it is either / or nul.
5269 * Store / as a temporary sentinel so that we only have one character
5270 * to test for. Pathnames tend to be short so this should not be
5271 * resulting in cache misses.
5273 * TODO: fix this to be word-sized.
5275 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5276 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5277 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5278 fpl->nulchar, cnp->cn_pnbuf));
5279 KASSERT(*fpl->nulchar == '\0',
5280 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5282 hash = cache_get_hash_iter_start(dvp);
5283 *fpl->nulchar = '/';
5284 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5285 KASSERT(*cp != '\0',
5286 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5288 hash = cache_get_hash_iter(*cp, hash);
5291 *fpl->nulchar = '\0';
5292 fpl->hash = cache_get_hash_iter_finish(hash);
5294 cnp->cn_namelen = cp - cnp->cn_nameptr;
5295 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5298 if (cnp->cn_namelen <= NAME_MAX) {
5299 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5300 panic("%s: mismatched hash for [%s] len %ld", __func__,
5301 cnp->cn_nameptr, cnp->cn_namelen);
5307 * Hack: we have to check if the found path component's length exceeds
5308 * NAME_MAX. However, the condition is very rarely true and check can
5309 * be elided in the common case -- if an entry was found in the cache,
5310 * then it could not have been too long to begin with.
5316 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5318 struct nameidata *ndp;
5319 struct componentname *cnp;
5324 cnp->cn_nameptr = ndp->ni_next;
5325 KASSERT(*(cnp->cn_nameptr) == '/',
5326 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5327 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5329 cache_fpl_pathlen_dec(fpl);
5333 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5335 * Lockless lookup tries to elide checking for spurious slashes and should they
5336 * be present is guaranteed to fail to find an entry. In this case the caller
5337 * must check if the name starts with a slash and call this routine. It is
5338 * going to fast forward across the spurious slashes and set the state up for
5341 static int __noinline
5342 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5344 struct nameidata *ndp;
5345 struct componentname *cnp;
5350 MPASS(*(cnp->cn_nameptr) == '/');
5353 cache_fpl_pathlen_dec(fpl);
5354 } while (*(cnp->cn_nameptr) == '/');
5357 * Go back to one slash so that cache_fplookup_parse_advance has
5358 * something to skip.
5361 cache_fpl_pathlen_inc(fpl);
5364 * cache_fplookup_parse_advance starts from ndp->ni_next
5366 ndp->ni_next = cnp->cn_nameptr;
5369 * See cache_fplookup_dot.
5371 fpl->tvp = fpl->dvp;
5372 fpl->tvp_seqc = fpl->dvp_seqc;
5378 * Handle trailing slashes (e.g., "foo/").
5380 * If a trailing slash is found the terminal vnode must be a directory.
5381 * Regular lookup shortens the path by nulifying the first trailing slash and
5382 * sets the TRAILINGSLASH flag to denote this took place. There are several
5383 * checks on it performed later.
5385 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5386 * manner relying on an invariant that a non-directory vnode will get a miss.
5387 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5389 * Thus for a path like "foo/bar/" the code unwinds the state back to 'bar/'
5390 * and denotes this is the last path component, which avoids looping back.
5392 * Only plain lookups are supported for now to restrict corner cases to handle.
5394 static int __noinline
5395 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5400 struct nameidata *ndp;
5401 struct componentname *cnp;
5402 struct namecache *ncp;
5404 char *cn_nameptr_orig, *cn_nameptr_slash;
5411 tvp_seqc = fpl->tvp_seqc;
5413 MPASS(fpl->dvp == fpl->tvp);
5414 KASSERT(cache_fpl_istrailingslash(fpl),
5415 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5417 KASSERT(cnp->cn_nameptr[0] == '\0',
5418 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5420 KASSERT(cnp->cn_namelen == 0,
5421 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5423 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5425 if (cnp->cn_nameiop != LOOKUP) {
5426 return (cache_fpl_aborted(fpl));
5429 if (__predict_false(tvp->v_type != VDIR)) {
5430 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5431 return (cache_fpl_aborted(fpl));
5433 cache_fpl_smr_exit(fpl);
5434 return (cache_fpl_handled_error(fpl, ENOTDIR));
5438 * Denote the last component.
5440 ndp->ni_next = &cnp->cn_nameptr[0];
5441 MPASS(cache_fpl_islastcn(ndp));
5444 * Unwind trailing slashes.
5446 cn_nameptr_orig = cnp->cn_nameptr;
5447 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5449 if (cnp->cn_nameptr[0] != '/') {
5455 * Unwind to the beginning of the path component.
5457 * Note the path may or may not have started with a slash.
5459 cn_nameptr_slash = cnp->cn_nameptr;
5460 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5462 if (cnp->cn_nameptr[0] == '/') {
5466 if (cnp->cn_nameptr[0] == '/') {
5470 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5471 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5472 cache_fpl_checkpoint(fpl);
5475 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5476 if (ni_pathlen != fpl->debug.ni_pathlen) {
5477 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5478 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5479 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5484 * The previous directory is this one.
5486 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5491 * The previous directory is something else.
5494 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5495 if (__predict_false(ncp == NULL)) {
5496 return (cache_fpl_aborted(fpl));
5498 nc_flag = atomic_load_char(&ncp->nc_flag);
5499 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5500 return (cache_fpl_aborted(fpl));
5502 fpl->dvp = ncp->nc_dvp;
5503 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5504 if (seqc_in_modify(fpl->dvp_seqc)) {
5505 return (cache_fpl_aborted(fpl));
5511 * See the API contract for VOP_FPLOOKUP_VEXEC.
5513 static int __noinline
5514 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5516 struct componentname *cnp;
5522 dvp_seqc = fpl->dvp_seqc;
5525 * TODO: Due to ignoring slashes lookup will perform a permission check
5526 * on the last dir when it should not have. If it fails, we get here.
5527 * It is possible possible to fix it up fully without resorting to
5528 * regular lookup, but for now just abort.
5530 if (cache_fpl_istrailingslash(fpl)) {
5531 return (cache_fpl_aborted(fpl));
5535 * Hack: delayed degenerate path checking.
5537 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5538 return (cache_fplookup_degenerate(fpl));
5542 * Hack: delayed name len checking.
5544 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5545 cache_fpl_smr_exit(fpl);
5546 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5550 * Hack: they may be looking up foo/bar, where foo is not a directory.
5551 * In such a case we need to return ENOTDIR, but we may happen to get
5552 * here with a different error.
5554 if (dvp->v_type != VDIR) {
5559 * Hack: handle O_SEARCH.
5561 * Open Group Base Specifications Issue 7, 2018 edition states:
5563 * If the access mode of the open file description associated with the
5564 * file descriptor is not O_SEARCH, the function shall check whether
5565 * directory searches are permitted using the current permissions of
5566 * the directory underlying the file descriptor. If the access mode is
5567 * O_SEARCH, the function shall not perform the check.
5570 * Regular lookup tests for the NOEXECCHECK flag for every path
5571 * component to decide whether to do the permission check. However,
5572 * since most lookups never have the flag (and when they do it is only
5573 * present for the first path component), lockless lookup only acts on
5574 * it if there is a permission problem. Here the flag is represented
5575 * with a boolean so that we don't have to clear it on the way out.
5577 * For simplicity this always aborts.
5578 * TODO: check if this is the first lookup and ignore the permission
5579 * problem. Note the flag has to survive fallback (if it happens to be
5583 return (cache_fpl_aborted(fpl));
5588 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5589 error = cache_fpl_aborted(fpl);
5591 cache_fpl_partial(fpl);
5595 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5596 error = cache_fpl_aborted(fpl);
5598 cache_fpl_smr_exit(fpl);
5599 cache_fpl_handled_error(fpl, error);
5607 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
5609 struct nameidata *ndp;
5610 struct componentname *cnp;
5617 cache_fpl_checkpoint(fpl);
5620 * The vnode at hand is almost always stable, skip checking for it.
5621 * Worst case this postpones the check towards the end of the iteration
5625 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
5627 mp = atomic_load_ptr(&dvp->v_mount);
5628 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
5629 return (cache_fpl_aborted(fpl));
5632 MPASS(fpl->tvp == NULL);
5635 cache_fplookup_parse(fpl);
5637 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
5638 if (__predict_false(error != 0)) {
5639 error = cache_fplookup_failed_vexec(fpl, error);
5643 error = cache_fplookup_next(fpl);
5644 if (__predict_false(cache_fpl_terminated(fpl))) {
5648 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
5650 if (fpl->tvp->v_type == VLNK) {
5651 error = cache_fplookup_symlink(fpl);
5652 if (cache_fpl_terminated(fpl)) {
5656 if (cache_fpl_islastcn(ndp)) {
5657 error = cache_fplookup_final(fpl);
5661 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
5662 error = cache_fpl_aborted(fpl);
5666 fpl->dvp = fpl->tvp;
5667 fpl->dvp_seqc = fpl->tvp_seqc;
5668 cache_fplookup_parse_advance(fpl);
5671 cache_fpl_checkpoint(fpl);
5678 * Fast path lookup protected with SMR and sequence counters.
5680 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
5682 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
5685 * Traditional vnode lookup conceptually looks like this:
5691 * vn_unlock(current);
5698 * Each jump to the next vnode is safe memory-wise and atomic with respect to
5699 * any modifications thanks to holding respective locks.
5701 * The same guarantee can be provided with a combination of safe memory
5702 * reclamation and sequence counters instead. If all operations which affect
5703 * the relationship between the current vnode and the one we are looking for
5704 * also modify the counter, we can verify whether all the conditions held as
5705 * we made the jump. This includes things like permissions, mount points etc.
5706 * Counter modification is provided by enclosing relevant places in
5707 * vn_seqc_write_begin()/end() calls.
5709 * Thus this translates to:
5712 * dvp_seqc = seqc_read_any(dvp);
5713 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
5717 * tvp_seqc = seqc_read_any(tvp);
5718 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
5720 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
5722 * dvp = tvp; // we know nothing of importance has changed
5723 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
5727 * vget(); // secure the vnode
5728 * if (!seqc_consistent(tvp, tvp_seqc) // final check
5730 * // at this point we know nothing has changed for any parent<->child pair
5731 * // as they were crossed during the lookup, meaning we matched the guarantee
5732 * // of the locked variant
5735 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
5736 * - they are called while within vfs_smr protection which they must never exit
5737 * - EAGAIN can be returned to denote checking could not be performed, it is
5738 * always valid to return it
5739 * - if the sequence counter has not changed the result must be valid
5740 * - if the sequence counter has changed both false positives and false negatives
5741 * are permitted (since the result will be rejected later)
5742 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
5744 * Caveats to watch out for:
5745 * - vnodes are passed unlocked and unreferenced with nothing stopping
5746 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
5747 * to use atomic_load_ptr to fetch it.
5748 * - the aforementioned object can also get freed, meaning absent other means it
5749 * should be protected with vfs_smr
5750 * - either safely checking permissions as they are modified or guaranteeing
5751 * their stability is left to the routine
5754 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
5757 struct cache_fpl fpl;
5760 struct componentname *cnp;
5763 fpl.status = CACHE_FPL_STATUS_UNSET;
5766 fpl.cnp = cnp = &ndp->ni_cnd;
5767 MPASS(ndp->ni_lcf == 0);
5768 MPASS(curthread == cnp->cn_thread);
5769 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
5770 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
5772 if ((cnp->cn_flags & SAVESTART) != 0) {
5773 MPASS(cnp->cn_nameiop != LOOKUP);
5775 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
5777 if (__predict_false(!cache_can_fplookup(&fpl))) {
5778 *status = fpl.status;
5779 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
5780 return (EOPNOTSUPP);
5783 cache_fpl_checkpoint_outer(&fpl);
5785 cache_fpl_smr_enter_initial(&fpl);
5787 fpl.debug.ni_pathlen = ndp->ni_pathlen;
5789 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5790 fpl.fsearch = false;
5791 fpl.savename = (cnp->cn_flags & SAVENAME) != 0;
5792 fpl.tvp = NULL; /* for degenerate path handling */
5794 pwd = pwd_get_smr();
5796 ndp->ni_rootdir = pwd->pwd_rdir;
5797 ndp->ni_topdir = pwd->pwd_jdir;
5799 if (cnp->cn_pnbuf[0] == '/') {
5800 dvp = cache_fpl_handle_root(&fpl);
5801 MPASS(ndp->ni_resflags == 0);
5802 ndp->ni_resflags = NIRES_ABS;
5804 if (ndp->ni_dirfd == AT_FDCWD) {
5805 dvp = pwd->pwd_cdir;
5807 error = cache_fplookup_dirfd(&fpl, &dvp);
5808 if (__predict_false(error != 0)) {
5814 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
5815 error = cache_fplookup_impl(dvp, &fpl);
5817 cache_fpl_smr_assert_not_entered(&fpl);
5818 cache_fpl_assert_status(&fpl);
5819 *status = fpl.status;
5820 if (SDT_PROBES_ENABLED()) {
5821 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
5822 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
5823 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
5827 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
5828 MPASS(error != CACHE_FPL_FAILED);
5830 MPASS(fpl.dvp == NULL);
5831 MPASS(fpl.tvp == NULL);
5832 MPASS(fpl.savename == false);
5834 ndp->ni_dvp = fpl.dvp;
5835 ndp->ni_vp = fpl.tvp;
5837 cnp->cn_flags |= HASBUF;
5839 cache_fpl_cleanup_cnp(cnp);