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 <sys/capsicum.h>
73 #include <security/audit/audit.h>
74 #include <security/mac/mac_framework.h>
82 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
85 SDT_PROVIDER_DECLARE(vfs);
86 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
88 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
90 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
92 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
94 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
95 "struct namecache *", "int", "int");
96 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
97 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
98 "char *", "struct vnode *");
99 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
100 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
101 "struct vnode *", "char *");
102 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
104 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
105 "struct vnode *", "char *");
106 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
108 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
109 "struct componentname *");
110 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
111 "struct componentname *");
112 SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
113 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
114 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
115 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
117 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
119 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
122 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
123 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
124 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
127 * This structure describes the elements in the cache of recent
128 * names looked up by namei.
134 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
135 "the state must fit in a union with a pointer without growing it");
138 LIST_ENTRY(namecache) nc_src; /* source vnode list */
139 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
140 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
141 struct vnode *nc_dvp; /* vnode of parent of name */
143 struct vnode *nu_vp; /* vnode the name refers to */
144 struct negstate nu_neg;/* negative entry state */
146 u_char nc_flag; /* flag bits */
147 u_char nc_nlen; /* length of name */
148 char nc_name[0]; /* segment name + nul */
152 * struct namecache_ts repeats struct namecache layout up to the
154 * struct namecache_ts is used in place of struct namecache when time(s) need
155 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
156 * both a non-dotdot directory name plus dotdot for the directory's
159 * See below for alignment requirement.
161 struct namecache_ts {
162 struct timespec nc_time; /* timespec provided by fs */
163 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
164 int nc_ticks; /* ticks value when entry was added */
166 struct namecache nc_nc;
170 * At least mips n32 performs 64-bit accesses to timespec as found
171 * in namecache_ts and requires them to be aligned. Since others
172 * may be in the same spot suffer a little bit and enforce the
173 * alignment for everyone. Note this is a nop for 64-bit platforms.
175 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
178 #define CACHE_PATH_CUTOFF 45
179 #define CACHE_LARGE_PAD 6
181 #define CACHE_PATH_CUTOFF 41
182 #define CACHE_LARGE_PAD 2
185 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
186 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
187 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
188 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
190 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
191 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
192 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
193 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
195 #define nc_vp n_un.nu_vp
196 #define nc_neg n_un.nu_neg
199 * Flags in namecache.nc_flag
201 #define NCF_WHITE 0x01
202 #define NCF_ISDOTDOT 0x02
205 #define NCF_DVDROP 0x10
206 #define NCF_NEGATIVE 0x20
207 #define NCF_INVALID 0x40
211 * Flags in negstate.neg_flag
216 * Mark an entry as invalid.
218 * This is called before it starts getting deconstructed.
221 cache_ncp_invalidate(struct namecache *ncp)
224 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
225 ("%s: entry %p already invalid", __func__, ncp));
226 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
227 atomic_thread_fence_rel();
231 * Check whether the entry can be safely used.
233 * All places which elide locks are supposed to call this after they are
234 * done with reading from an entry.
237 cache_ncp_canuse(struct namecache *ncp)
240 atomic_thread_fence_acq();
241 return ((atomic_load_char(&ncp->nc_flag) & (NCF_INVALID | NCF_WIP)) == 0);
245 * Name caching works as follows:
247 * Names found by directory scans are retained in a cache
248 * for future reference. It is managed LRU, so frequently
249 * used names will hang around. Cache is indexed by hash value
250 * obtained from (dvp, name) where dvp refers to the directory
253 * If it is a "negative" entry, (i.e. for a name that is known NOT to
254 * exist) the vnode pointer will be NULL.
256 * Upon reaching the last segment of a path, if the reference
257 * is for DELETE, or NOCACHE is set (rewrite), and the
258 * name is located in the cache, it will be dropped.
260 * These locks are used (in the order in which they can be taken):
262 * vnodelock mtx vnode lists and v_cache_dd field protection
263 * bucketlock mtx for access to given set of hash buckets
264 * neglist mtx negative entry LRU management
266 * It is legal to take multiple vnodelock and bucketlock locks. The locking
267 * order is lower address first. Both are recursive.
269 * "." lookups are lockless.
271 * ".." and vnode -> name lookups require vnodelock.
273 * name -> vnode lookup requires the relevant bucketlock to be held for reading.
275 * Insertions and removals of entries require involved vnodes and bucketlocks
276 * to be locked to provide safe operation against other threads modifying the
279 * Some lookups result in removal of the found entry (e.g. getting rid of a
280 * negative entry with the intent to create a positive one), which poses a
281 * problem when multiple threads reach the state. Similarly, two different
282 * threads can purge two different vnodes and try to remove the same name.
284 * If the already held vnode lock is lower than the second required lock, we
285 * can just take the other lock. However, in the opposite case, this could
286 * deadlock. As such, this is resolved by trylocking and if that fails unlocking
287 * the first node, locking everything in order and revalidating the state.
292 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
293 "Name cache parameters");
295 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
296 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
297 "Total namecache capacity");
299 u_int ncsizefactor = 2;
300 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
301 "Size factor for namecache");
303 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
304 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
305 "Ratio of negative namecache entries");
308 * Negative entry % of namecahe capacity above which automatic eviction is allowed.
310 * Check cache_neg_evict_cond for details.
312 static u_int ncnegminpct = 3;
314 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
315 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
316 "Negative entry count above which automatic eviction is allowed");
319 * Structures associated with name caching.
321 #define NCHHASH(hash) \
322 (&nchashtbl[(hash) & nchash])
323 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
324 static u_long __read_mostly nchash; /* size of hash table */
325 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
326 "Size of namecache hash table");
327 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
328 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
330 struct nchstats nchstats; /* cache effectiveness statistics */
332 static bool __read_frequently cache_fast_revlookup = true;
333 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
334 &cache_fast_revlookup, 0, "");
336 static u_int __exclusive_cache_line neg_cycle;
339 #define numneglists (ncneghash + 1)
342 struct mtx nl_evict_lock;
343 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
344 TAILQ_HEAD(, namecache) nl_list;
345 TAILQ_HEAD(, namecache) nl_hotlist;
347 } __aligned(CACHE_LINE_SIZE);
349 static struct neglist neglists[numneglists];
351 static inline struct neglist *
352 NCP2NEGLIST(struct namecache *ncp)
355 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
358 static inline struct negstate *
359 NCP2NEGSTATE(struct namecache *ncp)
362 MPASS(ncp->nc_flag & NCF_NEGATIVE);
363 return (&ncp->nc_neg);
366 #define numbucketlocks (ncbuckethash + 1)
367 static u_int __read_mostly ncbuckethash;
368 static struct mtx_padalign __read_mostly *bucketlocks;
369 #define HASH2BUCKETLOCK(hash) \
370 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
372 #define numvnodelocks (ncvnodehash + 1)
373 static u_int __read_mostly ncvnodehash;
374 static struct mtx __read_mostly *vnodelocks;
375 static inline struct mtx *
376 VP2VNODELOCK(struct vnode *vp)
379 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
383 * UMA zones for the VFS cache.
385 * The small cache is used for entries with short names, which are the
386 * most common. The large cache is used for entries which are too big to
387 * fit in the small cache.
389 static uma_zone_t __read_mostly cache_zone_small;
390 static uma_zone_t __read_mostly cache_zone_small_ts;
391 static uma_zone_t __read_mostly cache_zone_large;
392 static uma_zone_t __read_mostly cache_zone_large_ts;
394 static struct namecache *
395 cache_alloc(int len, int ts)
397 struct namecache_ts *ncp_ts;
398 struct namecache *ncp;
400 if (__predict_false(ts)) {
401 if (len <= CACHE_PATH_CUTOFF)
402 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
404 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
405 ncp = &ncp_ts->nc_nc;
407 if (len <= CACHE_PATH_CUTOFF)
408 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
410 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
416 cache_free(struct namecache *ncp)
418 struct namecache_ts *ncp_ts;
421 if ((ncp->nc_flag & NCF_DVDROP) != 0)
423 if (__predict_false(ncp->nc_flag & NCF_TS)) {
424 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
425 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
426 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
428 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
430 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
431 uma_zfree_smr(cache_zone_small, ncp);
433 uma_zfree_smr(cache_zone_large, ncp);
438 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
440 struct namecache_ts *ncp_ts;
442 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
443 (tsp == NULL && ticksp == NULL),
449 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
450 *tsp = ncp_ts->nc_time;
451 *ticksp = ncp_ts->nc_ticks;
455 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
456 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
457 "VFS namecache enabled");
460 /* Export size information to userland */
461 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
462 sizeof(struct namecache), "sizeof(struct namecache)");
465 * The new name cache statistics
467 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
468 "Name cache statistics");
470 #define STATNODE_ULONG(name, varname, descr) \
471 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
472 #define STATNODE_COUNTER(name, varname, descr) \
473 static COUNTER_U64_DEFINE_EARLY(varname); \
474 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
476 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
477 STATNODE_ULONG(count, numcache, "Number of cache entries");
478 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
479 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
480 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
481 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
482 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
483 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
484 STATNODE_COUNTER(posszaps, numposzaps,
485 "Number of cache hits (positive) we do not want to cache");
486 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
487 STATNODE_COUNTER(negzaps, numnegzaps,
488 "Number of cache hits (negative) we do not want to cache");
489 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
490 /* These count for vn_getcwd(), too. */
491 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
492 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
493 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
494 "Number of fullpath search errors (VOP_VPTOCNP failures)");
495 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
496 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
499 * Debug or developer statistics.
501 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
502 "Name cache debugging");
503 #define DEBUGNODE_ULONG(name, varname, descr) \
504 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
505 #define DEBUGNODE_COUNTER(name, varname, descr) \
506 static COUNTER_U64_DEFINE_EARLY(varname); \
507 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
509 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
510 "Number of successful removals after relocking");
511 static long zap_bucket_fail;
512 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
513 static long zap_bucket_fail2;
514 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
515 static long cache_lock_vnodes_cel_3_failures;
516 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
517 "Number of times 3-way vnode locking failed");
519 static void cache_zap_locked(struct namecache *ncp);
520 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
521 char **freebuf, size_t *buflen);
522 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
523 char **retbuf, size_t *buflen, size_t addend);
524 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
525 char **retbuf, size_t *buflen);
526 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
527 char **retbuf, size_t *len, size_t addend);
529 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
532 cache_assert_vlp_locked(struct mtx *vlp)
536 mtx_assert(vlp, MA_OWNED);
540 cache_assert_vnode_locked(struct vnode *vp)
544 vlp = VP2VNODELOCK(vp);
545 cache_assert_vlp_locked(vlp);
549 * TODO: With the value stored we can do better than computing the hash based
550 * on the address. The choice of FNV should also be revisited.
553 cache_prehash(struct vnode *vp)
556 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
560 cache_get_hash(char *name, u_char len, struct vnode *dvp)
563 return (fnv_32_buf(name, len, dvp->v_nchash));
566 static inline struct nchashhead *
567 NCP2BUCKET(struct namecache *ncp)
571 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
572 return (NCHHASH(hash));
575 static inline struct mtx *
576 NCP2BUCKETLOCK(struct namecache *ncp)
580 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
581 return (HASH2BUCKETLOCK(hash));
586 cache_assert_bucket_locked(struct namecache *ncp)
590 blp = NCP2BUCKETLOCK(ncp);
591 mtx_assert(blp, MA_OWNED);
595 cache_assert_bucket_unlocked(struct namecache *ncp)
599 blp = NCP2BUCKETLOCK(ncp);
600 mtx_assert(blp, MA_NOTOWNED);
603 #define cache_assert_bucket_locked(x) do { } while (0)
604 #define cache_assert_bucket_unlocked(x) do { } while (0)
607 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
609 _cache_sort_vnodes(void **p1, void **p2)
613 MPASS(*p1 != NULL || *p2 != NULL);
623 cache_lock_all_buckets(void)
627 for (i = 0; i < numbucketlocks; i++)
628 mtx_lock(&bucketlocks[i]);
632 cache_unlock_all_buckets(void)
636 for (i = 0; i < numbucketlocks; i++)
637 mtx_unlock(&bucketlocks[i]);
641 cache_lock_all_vnodes(void)
645 for (i = 0; i < numvnodelocks; i++)
646 mtx_lock(&vnodelocks[i]);
650 cache_unlock_all_vnodes(void)
654 for (i = 0; i < numvnodelocks; i++)
655 mtx_unlock(&vnodelocks[i]);
659 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
662 cache_sort_vnodes(&vlp1, &vlp2);
665 if (!mtx_trylock(vlp1))
668 if (!mtx_trylock(vlp2)) {
678 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
681 MPASS(vlp1 != NULL || vlp2 != NULL);
691 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
694 MPASS(vlp1 != NULL || vlp2 != NULL);
703 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
705 struct nchstats snap;
707 if (req->oldptr == NULL)
708 return (SYSCTL_OUT(req, 0, sizeof(snap)));
711 snap.ncs_goodhits = counter_u64_fetch(numposhits);
712 snap.ncs_neghits = counter_u64_fetch(numneghits);
713 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
714 counter_u64_fetch(numnegzaps);
715 snap.ncs_miss = counter_u64_fetch(nummisszap) +
716 counter_u64_fetch(nummiss);
718 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
720 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
721 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
722 "VFS cache effectiveness statistics");
725 cache_recalc_neg_min(u_int val)
728 neg_min = (ncsize * val) / 100;
732 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
738 error = sysctl_handle_int(oidp, &val, 0, req);
739 if (error != 0 || req->newptr == NULL)
742 if (val == ncnegminpct)
744 if (val < 0 || val > 99)
747 cache_recalc_neg_min(val);
751 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
752 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
753 "I", "Negative entry \% of namecahe capacity above which automatic eviction is allowed");
757 * Grab an atomic snapshot of the name cache hash chain lengths
759 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
760 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
764 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
766 struct nchashhead *ncpp;
767 struct namecache *ncp;
768 int i, error, n_nchash, *cntbuf;
771 n_nchash = nchash + 1; /* nchash is max index, not count */
772 if (req->oldptr == NULL)
773 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
774 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
775 cache_lock_all_buckets();
776 if (n_nchash != nchash + 1) {
777 cache_unlock_all_buckets();
778 free(cntbuf, M_TEMP);
781 /* Scan hash tables counting entries */
782 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
783 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
785 cache_unlock_all_buckets();
786 for (error = 0, i = 0; i < n_nchash; i++)
787 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
789 free(cntbuf, M_TEMP);
792 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
793 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
794 "nchash chain lengths");
797 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
800 struct nchashhead *ncpp;
801 struct namecache *ncp;
803 int count, maxlength, used, pct;
806 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
808 cache_lock_all_buckets();
809 n_nchash = nchash + 1; /* nchash is max index, not count */
813 /* Scan hash tables for applicable entries */
814 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
816 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
821 if (maxlength < count)
824 n_nchash = nchash + 1;
825 cache_unlock_all_buckets();
826 pct = (used * 100) / (n_nchash / 100);
827 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
830 error = SYSCTL_OUT(req, &used, sizeof(used));
833 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
836 error = SYSCTL_OUT(req, &pct, sizeof(pct));
841 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
842 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
843 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
847 * Negative entries management
849 * Various workloads create plenty of negative entries and barely use them
850 * afterwards. Moreover malicious users can keep performing bogus lookups
851 * adding even more entries. For example "make tinderbox" as of writing this
852 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
855 * As such, a rather aggressive eviction method is needed. The currently
856 * employed method is a placeholder.
858 * Entries are split over numneglists separate lists, each of which is further
859 * split into hot and cold entries. Entries get promoted after getting a hit.
860 * Eviction happens on addition of new entry.
862 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
863 "Name cache negative entry statistics");
865 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
866 "Number of negative cache entries");
868 static COUNTER_U64_DEFINE_EARLY(neg_created);
869 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
870 "Number of created negative entries");
872 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
873 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
874 "Number of evicted negative entries");
876 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
877 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
878 &neg_evict_skipped_empty,
879 "Number of times evicting failed due to lack of entries");
881 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
882 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
883 &neg_evict_skipped_missed,
884 "Number of times evicting failed due to target entry disappearing");
886 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
887 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
888 &neg_evict_skipped_contended,
889 "Number of times evicting failed due to contention");
891 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
892 "Number of cache hits (negative)");
895 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
900 for (i = 0; i < numneglists; i++)
901 out += neglists[i].nl_hotnum;
903 return (SYSCTL_OUT(req, &out, sizeof(out)));
905 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
906 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
907 "Number of hot negative entries");
910 cache_neg_init(struct namecache *ncp)
914 ncp->nc_flag |= NCF_NEGATIVE;
915 ns = NCP2NEGSTATE(ncp);
918 counter_u64_add(neg_created, 1);
921 #define CACHE_NEG_PROMOTION_THRESH 2
924 cache_neg_hit_prep(struct namecache *ncp)
929 ns = NCP2NEGSTATE(ncp);
930 n = atomic_load_char(&ns->neg_hit);
932 if (n >= CACHE_NEG_PROMOTION_THRESH)
934 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
937 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
941 * Nothing to do here but it is provided for completeness as some
942 * cache_neg_hit_prep callers may end up returning without even
945 #define cache_neg_hit_abort(ncp) do { } while (0)
948 cache_neg_hit_finish(struct namecache *ncp)
951 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
952 counter_u64_add(numneghits, 1);
956 * Move a negative entry to the hot list.
959 cache_neg_promote_locked(struct namecache *ncp)
964 ns = NCP2NEGSTATE(ncp);
965 nl = NCP2NEGLIST(ncp);
966 mtx_assert(&nl->nl_lock, MA_OWNED);
967 if ((ns->neg_flag & NEG_HOT) == 0) {
968 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
969 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
971 ns->neg_flag |= NEG_HOT;
976 * Move a hot negative entry to the cold list.
979 cache_neg_demote_locked(struct namecache *ncp)
984 ns = NCP2NEGSTATE(ncp);
985 nl = NCP2NEGLIST(ncp);
986 mtx_assert(&nl->nl_lock, MA_OWNED);
987 MPASS(ns->neg_flag & NEG_HOT);
988 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
989 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
991 ns->neg_flag &= ~NEG_HOT;
992 atomic_store_char(&ns->neg_hit, 0);
996 * Move a negative entry to the hot list if it matches the lookup.
998 * We have to take locks, but they may be contended and in the worst
999 * case we may need to go off CPU. We don't want to spin within the
1000 * smr section and we can't block with it. Exiting the section means
1001 * the found entry could have been evicted. We are going to look it
1005 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1006 struct namecache *oncp, uint32_t hash)
1008 struct namecache *ncp;
1012 nl = NCP2NEGLIST(oncp);
1014 mtx_lock(&nl->nl_lock);
1016 * For hash iteration.
1021 * Avoid all surprises by only succeeding if we got the same entry and
1022 * bailing completely otherwise.
1023 * XXX There are no provisions to keep the vnode around, meaning we may
1024 * end up promoting a negative entry for a *new* vnode and returning
1025 * ENOENT on its account. This is the error we want to return anyway
1026 * and promotion is harmless.
1028 * In particular at this point there can be a new ncp which matches the
1029 * search but hashes to a different neglist.
1031 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1037 * No match to begin with.
1039 if (__predict_false(ncp == NULL)) {
1044 * The newly found entry may be something different...
1046 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1047 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1052 * ... and not even negative.
1054 nc_flag = atomic_load_char(&ncp->nc_flag);
1055 if ((nc_flag & NCF_NEGATIVE) == 0) {
1059 if (__predict_false(!cache_ncp_canuse(ncp))) {
1063 cache_neg_promote_locked(ncp);
1064 cache_neg_hit_finish(ncp);
1066 mtx_unlock(&nl->nl_lock);
1070 mtx_unlock(&nl->nl_lock);
1075 cache_neg_promote(struct namecache *ncp)
1079 nl = NCP2NEGLIST(ncp);
1080 mtx_lock(&nl->nl_lock);
1081 cache_neg_promote_locked(ncp);
1082 mtx_unlock(&nl->nl_lock);
1086 cache_neg_insert(struct namecache *ncp)
1090 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1091 cache_assert_bucket_locked(ncp);
1092 nl = NCP2NEGLIST(ncp);
1093 mtx_lock(&nl->nl_lock);
1094 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1095 mtx_unlock(&nl->nl_lock);
1096 atomic_add_long(&numneg, 1);
1100 cache_neg_remove(struct namecache *ncp)
1103 struct negstate *ns;
1105 cache_assert_bucket_locked(ncp);
1106 nl = NCP2NEGLIST(ncp);
1107 ns = NCP2NEGSTATE(ncp);
1108 mtx_lock(&nl->nl_lock);
1109 if ((ns->neg_flag & NEG_HOT) != 0) {
1110 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1113 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1115 mtx_unlock(&nl->nl_lock);
1116 atomic_subtract_long(&numneg, 1);
1119 static struct neglist *
1120 cache_neg_evict_select_list(void)
1125 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1126 nl = &neglists[c % numneglists];
1127 if (!mtx_trylock(&nl->nl_evict_lock)) {
1128 counter_u64_add(neg_evict_skipped_contended, 1);
1134 static struct namecache *
1135 cache_neg_evict_select_entry(struct neglist *nl)
1137 struct namecache *ncp, *lncp;
1138 struct negstate *ns, *lns;
1141 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1142 mtx_assert(&nl->nl_lock, MA_OWNED);
1143 ncp = TAILQ_FIRST(&nl->nl_list);
1147 lns = NCP2NEGSTATE(lncp);
1148 for (i = 1; i < 4; i++) {
1149 ncp = TAILQ_NEXT(ncp, nc_dst);
1152 ns = NCP2NEGSTATE(ncp);
1153 if (ns->neg_hit < lns->neg_hit) {
1162 cache_neg_evict(void)
1164 struct namecache *ncp, *ncp2;
1166 struct negstate *ns;
1174 nl = cache_neg_evict_select_list();
1179 mtx_lock(&nl->nl_lock);
1180 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1182 cache_neg_demote_locked(ncp);
1184 ncp = cache_neg_evict_select_entry(nl);
1186 counter_u64_add(neg_evict_skipped_empty, 1);
1187 mtx_unlock(&nl->nl_lock);
1188 mtx_unlock(&nl->nl_evict_lock);
1191 ns = NCP2NEGSTATE(ncp);
1192 nlen = ncp->nc_nlen;
1194 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1195 dvlp = VP2VNODELOCK(dvp);
1196 blp = HASH2BUCKETLOCK(hash);
1197 mtx_unlock(&nl->nl_lock);
1198 mtx_unlock(&nl->nl_evict_lock);
1202 * Note that since all locks were dropped above, the entry may be
1203 * gone or reallocated to be something else.
1205 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1206 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1207 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1211 counter_u64_add(neg_evict_skipped_missed, 1);
1215 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1216 MPASS(blp == NCP2BUCKETLOCK(ncp));
1217 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1219 cache_zap_locked(ncp);
1220 counter_u64_add(neg_evicted, 1);
1231 * Maybe evict a negative entry to create more room.
1233 * The ncnegfactor parameter limits what fraction of the total count
1234 * can comprise of negative entries. However, if the cache is just
1235 * warming up this leads to excessive evictions. As such, ncnegminpct
1236 * (recomputed to neg_min) dictates whether the above should be
1239 * Try evicting if the cache is close to full capacity regardless of
1240 * other considerations.
1243 cache_neg_evict_cond(u_long lnumcache)
1247 if (ncsize - 1000 < lnumcache)
1249 lnumneg = atomic_load_long(&numneg);
1250 if (lnumneg < neg_min)
1252 if (lnumneg * ncnegfactor < lnumcache)
1255 return (cache_neg_evict());
1259 * cache_zap_locked():
1261 * Removes a namecache entry from cache, whether it contains an actual
1262 * pointer to a vnode or if it is just a negative cache entry.
1265 cache_zap_locked(struct namecache *ncp)
1267 struct nchashhead *ncpp;
1269 if (!(ncp->nc_flag & NCF_NEGATIVE))
1270 cache_assert_vnode_locked(ncp->nc_vp);
1271 cache_assert_vnode_locked(ncp->nc_dvp);
1272 cache_assert_bucket_locked(ncp);
1274 cache_ncp_invalidate(ncp);
1276 ncpp = NCP2BUCKET(ncp);
1277 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1278 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1279 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
1280 ncp->nc_name, ncp->nc_vp);
1281 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
1282 if (ncp == ncp->nc_vp->v_cache_dd) {
1283 vn_seqc_write_begin_unheld(ncp->nc_vp);
1284 ncp->nc_vp->v_cache_dd = NULL;
1285 vn_seqc_write_end(ncp->nc_vp);
1288 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
1290 cache_neg_remove(ncp);
1292 if (ncp->nc_flag & NCF_ISDOTDOT) {
1293 if (ncp == ncp->nc_dvp->v_cache_dd) {
1294 vn_seqc_write_begin_unheld(ncp->nc_dvp);
1295 ncp->nc_dvp->v_cache_dd = NULL;
1296 vn_seqc_write_end(ncp->nc_dvp);
1299 LIST_REMOVE(ncp, nc_src);
1300 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
1301 ncp->nc_flag |= NCF_DVDROP;
1302 counter_u64_add(numcachehv, -1);
1305 atomic_subtract_long(&numcache, 1);
1309 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1313 MPASS(ncp->nc_dvp == vp);
1314 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1315 cache_assert_vnode_locked(vp);
1317 blp = NCP2BUCKETLOCK(ncp);
1319 cache_zap_locked(ncp);
1324 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1327 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1330 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1331 cache_assert_vnode_locked(vp);
1333 if (ncp->nc_flag & NCF_NEGATIVE) {
1334 if (*vlpp != NULL) {
1338 cache_zap_negative_locked_vnode_kl(ncp, vp);
1342 pvlp = VP2VNODELOCK(vp);
1343 blp = NCP2BUCKETLOCK(ncp);
1344 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1345 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1347 if (*vlpp == vlp1 || *vlpp == vlp2) {
1351 if (*vlpp != NULL) {
1355 cache_sort_vnodes(&vlp1, &vlp2);
1360 if (!mtx_trylock(vlp1))
1366 cache_zap_locked(ncp);
1368 if (to_unlock != NULL)
1369 mtx_unlock(to_unlock);
1376 MPASS(*vlpp == NULL);
1382 * If trylocking failed we can get here. We know enough to take all needed locks
1383 * in the right order and re-lookup the entry.
1386 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1387 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1390 struct namecache *rncp;
1392 cache_assert_bucket_unlocked(ncp);
1394 cache_sort_vnodes(&dvlp, &vlp);
1395 cache_lock_vnodes(dvlp, vlp);
1397 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1398 if (rncp == ncp && rncp->nc_dvp == dvp &&
1399 rncp->nc_nlen == cnp->cn_namelen &&
1400 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1404 cache_zap_locked(rncp);
1406 cache_unlock_vnodes(dvlp, vlp);
1407 counter_u64_add(zap_bucket_relock_success, 1);
1412 cache_unlock_vnodes(dvlp, vlp);
1416 static int __noinline
1417 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1418 uint32_t hash, struct mtx *blp)
1420 struct mtx *dvlp, *vlp;
1423 cache_assert_bucket_locked(ncp);
1425 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1427 if (!(ncp->nc_flag & NCF_NEGATIVE))
1428 vlp = VP2VNODELOCK(ncp->nc_vp);
1429 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1430 cache_zap_locked(ncp);
1432 cache_unlock_vnodes(dvlp, vlp);
1438 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1441 static __noinline int
1442 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1444 struct namecache *ncp;
1446 struct mtx *dvlp, *dvlp2;
1450 if (cnp->cn_namelen == 2 &&
1451 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1452 dvlp = VP2VNODELOCK(dvp);
1456 ncp = dvp->v_cache_dd;
1461 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1464 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1465 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1467 MPASS(dvp->v_cache_dd == NULL);
1473 vn_seqc_write_begin(dvp);
1474 dvp->v_cache_dd = NULL;
1475 vn_seqc_write_end(dvp);
1480 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1484 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1485 blp = HASH2BUCKETLOCK(hash);
1487 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1492 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1493 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1494 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1503 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1504 if (__predict_false(error != 0)) {
1508 counter_u64_add(numposzaps, 1);
1509 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1513 counter_u64_add(nummisszap, 1);
1514 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1518 static int __noinline
1519 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1520 struct timespec *tsp, int *ticksp)
1525 counter_u64_add(dothits, 1);
1526 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1533 * When we lookup "." we still can be asked to lock it
1536 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1537 if (ltype != VOP_ISLOCKED(*vpp)) {
1538 if (ltype == LK_EXCLUSIVE) {
1539 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1540 if (VN_IS_DOOMED((*vpp))) {
1541 /* forced unmount */
1547 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1552 static int __noinline
1553 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1554 struct timespec *tsp, int *ticksp)
1556 struct namecache_ts *ncp_ts;
1557 struct namecache *ncp;
1563 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1565 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1566 cache_remove_cnp(dvp, cnp);
1570 counter_u64_add(dotdothits, 1);
1572 dvlp = VP2VNODELOCK(dvp);
1574 ncp = dvp->v_cache_dd;
1576 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, "..", NULL);
1580 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1581 if (ncp->nc_flag & NCF_NEGATIVE)
1588 goto negative_success;
1589 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1590 cache_out_ts(ncp, tsp, ticksp);
1591 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1592 NCF_DTS && tsp != NULL) {
1593 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1594 *tsp = ncp_ts->nc_dotdottime;
1598 ltype = VOP_ISLOCKED(dvp);
1600 vs = vget_prep(*vpp);
1602 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1603 vn_lock(dvp, ltype | LK_RETRY);
1604 if (VN_IS_DOOMED(dvp)) {
1616 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1617 if (cnp->cn_flags & ISLASTCN) {
1618 counter_u64_add(numnegzaps, 1);
1619 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1626 whiteout = (ncp->nc_flag & NCF_WHITE);
1627 cache_out_ts(ncp, tsp, ticksp);
1628 if (cache_neg_hit_prep(ncp))
1629 cache_neg_promote(ncp);
1631 cache_neg_hit_finish(ncp);
1634 cnp->cn_flags |= ISWHITEOUT;
1639 * Lookup a name in the name cache
1643 * - dvp: Parent directory in which to search.
1644 * - vpp: Return argument. Will contain desired vnode on cache hit.
1645 * - cnp: Parameters of the name search. The most interesting bits of
1646 * the cn_flags field have the following meanings:
1647 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1649 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1650 * - tsp: Return storage for cache timestamp. On a successful (positive
1651 * or negative) lookup, tsp will be filled with any timespec that
1652 * was stored when this cache entry was created. However, it will
1653 * be clear for "." entries.
1654 * - ticks: Return storage for alternate cache timestamp. On a successful
1655 * (positive or negative) lookup, it will contain the ticks value
1656 * that was current when the cache entry was created, unless cnp
1659 * Either both tsp and ticks have to be provided or neither of them.
1663 * - -1: A positive cache hit. vpp will contain the desired vnode.
1664 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1665 * to a forced unmount. vpp will not be modified. If the entry
1666 * is a whiteout, then the ISWHITEOUT flag will be set in
1668 * - 0: A cache miss. vpp will not be modified.
1672 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1673 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1674 * lock is not recursively acquired.
1676 static int __noinline
1677 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1678 struct timespec *tsp, int *ticksp)
1680 struct namecache *ncp;
1687 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1688 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1691 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1692 blp = HASH2BUCKETLOCK(hash);
1695 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1696 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1697 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1701 if (__predict_false(ncp == NULL)) {
1703 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1705 counter_u64_add(nummiss, 1);
1709 if (ncp->nc_flag & NCF_NEGATIVE)
1710 goto negative_success;
1712 counter_u64_add(numposhits, 1);
1714 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1715 cache_out_ts(ncp, tsp, ticksp);
1717 vs = vget_prep(*vpp);
1719 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1726 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1727 if (cnp->cn_flags & ISLASTCN) {
1728 counter_u64_add(numnegzaps, 1);
1729 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1730 if (__predict_false(error != 0)) {
1739 whiteout = (ncp->nc_flag & NCF_WHITE);
1740 cache_out_ts(ncp, tsp, ticksp);
1741 if (cache_neg_hit_prep(ncp))
1742 cache_neg_promote(ncp);
1744 cache_neg_hit_finish(ncp);
1747 cnp->cn_flags |= ISWHITEOUT;
1752 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1753 struct timespec *tsp, int *ticksp)
1755 struct namecache *ncp;
1759 bool whiteout, neg_promote;
1762 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
1765 if (__predict_false(!doingcache)) {
1766 cnp->cn_flags &= ~MAKEENTRY;
1771 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1772 if (cnp->cn_namelen == 1)
1773 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1774 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
1775 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
1778 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1780 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
1781 cache_remove_cnp(dvp, cnp);
1785 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1788 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1789 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1790 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1794 if (__predict_false(ncp == NULL)) {
1796 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1798 counter_u64_add(nummiss, 1);
1802 nc_flag = atomic_load_char(&ncp->nc_flag);
1803 if (nc_flag & NCF_NEGATIVE)
1804 goto negative_success;
1806 counter_u64_add(numposhits, 1);
1808 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1809 cache_out_ts(ncp, tsp, ticksp);
1811 if (!cache_ncp_canuse(ncp)) {
1816 vs = vget_prep_smr(*vpp);
1818 if (__predict_false(vs == VGET_NONE)) {
1822 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1829 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1830 if (cnp->cn_flags & ISLASTCN) {
1836 cache_out_ts(ncp, tsp, ticksp);
1837 whiteout = (ncp->nc_flag & NCF_WHITE);
1838 neg_promote = cache_neg_hit_prep(ncp);
1839 if (__predict_false(!cache_ncp_canuse(ncp))) {
1840 cache_neg_hit_abort(ncp);
1846 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
1849 cache_neg_hit_finish(ncp);
1853 cnp->cn_flags |= ISWHITEOUT;
1856 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
1859 struct celockstate {
1863 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1864 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1867 cache_celockstate_init(struct celockstate *cel)
1870 bzero(cel, sizeof(*cel));
1874 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1877 struct mtx *vlp1, *vlp2;
1879 MPASS(cel->vlp[0] == NULL);
1880 MPASS(cel->vlp[1] == NULL);
1881 MPASS(cel->vlp[2] == NULL);
1883 MPASS(vp != NULL || dvp != NULL);
1885 vlp1 = VP2VNODELOCK(vp);
1886 vlp2 = VP2VNODELOCK(dvp);
1887 cache_sort_vnodes(&vlp1, &vlp2);
1898 cache_unlock_vnodes_cel(struct celockstate *cel)
1901 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
1903 if (cel->vlp[0] != NULL)
1904 mtx_unlock(cel->vlp[0]);
1905 if (cel->vlp[1] != NULL)
1906 mtx_unlock(cel->vlp[1]);
1907 if (cel->vlp[2] != NULL)
1908 mtx_unlock(cel->vlp[2]);
1912 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
1917 cache_assert_vlp_locked(cel->vlp[0]);
1918 cache_assert_vlp_locked(cel->vlp[1]);
1919 MPASS(cel->vlp[2] == NULL);
1922 vlp = VP2VNODELOCK(vp);
1925 if (vlp >= cel->vlp[1]) {
1928 if (mtx_trylock(vlp))
1930 cache_lock_vnodes_cel_3_failures++;
1931 cache_unlock_vnodes_cel(cel);
1932 if (vlp < cel->vlp[0]) {
1934 mtx_lock(cel->vlp[0]);
1935 mtx_lock(cel->vlp[1]);
1937 if (cel->vlp[0] != NULL)
1938 mtx_lock(cel->vlp[0]);
1940 mtx_lock(cel->vlp[1]);
1950 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
1954 MPASS(cel->blp[0] == NULL);
1955 MPASS(cel->blp[1] == NULL);
1957 cache_sort_vnodes(&blp1, &blp2);
1968 cache_unlock_buckets_cel(struct celockstate *cel)
1971 if (cel->blp[0] != NULL)
1972 mtx_unlock(cel->blp[0]);
1973 mtx_unlock(cel->blp[1]);
1977 * Lock part of the cache affected by the insertion.
1979 * This means vnodelocks for dvp, vp and the relevant bucketlock.
1980 * However, insertion can result in removal of an old entry. In this
1981 * case we have an additional vnode and bucketlock pair to lock.
1983 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
1984 * preserving the locking order (smaller address first).
1987 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1990 struct namecache *ncp;
1991 struct mtx *blps[2];
1993 blps[0] = HASH2BUCKETLOCK(hash);
1996 cache_lock_vnodes_cel(cel, dvp, vp);
1997 if (vp == NULL || vp->v_type != VDIR)
1999 ncp = vp->v_cache_dd;
2002 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2004 MPASS(ncp->nc_dvp == vp);
2005 blps[1] = NCP2BUCKETLOCK(ncp);
2006 if (ncp->nc_flag & NCF_NEGATIVE)
2008 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2011 * All vnodes got re-locked. Re-validate the state and if
2012 * nothing changed we are done. Otherwise restart.
2014 if (ncp == vp->v_cache_dd &&
2015 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2016 blps[1] == NCP2BUCKETLOCK(ncp) &&
2017 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2019 cache_unlock_vnodes_cel(cel);
2024 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2028 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2031 struct namecache *ncp;
2032 struct mtx *blps[2];
2034 blps[0] = HASH2BUCKETLOCK(hash);
2037 cache_lock_vnodes_cel(cel, dvp, vp);
2038 ncp = dvp->v_cache_dd;
2041 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2043 MPASS(ncp->nc_dvp == dvp);
2044 blps[1] = NCP2BUCKETLOCK(ncp);
2045 if (ncp->nc_flag & NCF_NEGATIVE)
2047 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2049 if (ncp == dvp->v_cache_dd &&
2050 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2051 blps[1] == NCP2BUCKETLOCK(ncp) &&
2052 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2054 cache_unlock_vnodes_cel(cel);
2059 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2063 cache_enter_unlock(struct celockstate *cel)
2066 cache_unlock_buckets_cel(cel);
2067 cache_unlock_vnodes_cel(cel);
2070 static void __noinline
2071 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2072 struct componentname *cnp)
2074 struct celockstate cel;
2075 struct namecache *ncp;
2079 if (dvp->v_cache_dd == NULL)
2081 len = cnp->cn_namelen;
2082 cache_celockstate_init(&cel);
2083 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2084 cache_enter_lock_dd(&cel, dvp, vp, hash);
2085 vn_seqc_write_begin(dvp);
2086 ncp = dvp->v_cache_dd;
2087 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2088 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2089 cache_zap_locked(ncp);
2093 dvp->v_cache_dd = NULL;
2094 vn_seqc_write_end(dvp);
2095 cache_enter_unlock(&cel);
2101 * Add an entry to the cache.
2104 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2105 struct timespec *tsp, struct timespec *dtsp)
2107 struct celockstate cel;
2108 struct namecache *ncp, *n2, *ndd;
2109 struct namecache_ts *ncp_ts;
2110 struct nchashhead *ncpp;
2116 VNPASS(dvp != vp, dvp);
2117 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2118 VNPASS(dvp->v_type != VNON, dvp);
2120 VNPASS(!VN_IS_DOOMED(vp), vp);
2121 VNPASS(vp->v_type != VNON, vp);
2125 if (__predict_false(!doingcache))
2130 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2131 if (cnp->cn_namelen == 1)
2133 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2134 cache_enter_dotdot_prep(dvp, vp, cnp);
2135 flag = NCF_ISDOTDOT;
2140 * Avoid blowout in namecache entries.
2143 * 1. filesystems may end up tryng to add an already existing entry
2144 * (for example this can happen after a cache miss during concurrent
2145 * lookup), in which case we will call cache_neg_evict despite not
2147 * 2. the routine may fail to free anything and no provisions are made
2148 * to make it try harder (see the inside for failure modes)
2149 * 3. it only ever looks at negative entries.
2151 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
2152 if (cache_neg_evict_cond(lnumcache)) {
2153 lnumcache = atomic_load_long(&numcache);
2155 if (__predict_false(lnumcache >= ncsize)) {
2156 atomic_subtract_long(&numcache, 1);
2157 counter_u64_add(numdrops, 1);
2161 cache_celockstate_init(&cel);
2166 * Calculate the hash key and setup as much of the new
2167 * namecache entry as possible before acquiring the lock.
2169 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2170 ncp->nc_flag = flag | NCF_WIP;
2173 cache_neg_init(ncp);
2176 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2177 ncp_ts->nc_time = *tsp;
2178 ncp_ts->nc_ticks = ticks;
2179 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2181 ncp_ts->nc_dotdottime = *dtsp;
2182 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2185 len = ncp->nc_nlen = cnp->cn_namelen;
2186 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2187 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2188 ncp->nc_name[len] = '\0';
2189 cache_enter_lock(&cel, dvp, vp, hash);
2192 * See if this vnode or negative entry is already in the cache
2193 * with this name. This can happen with concurrent lookups of
2194 * the same path name.
2196 ncpp = NCHHASH(hash);
2197 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2198 if (n2->nc_dvp == dvp &&
2199 n2->nc_nlen == cnp->cn_namelen &&
2200 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2201 MPASS(cache_ncp_canuse(n2));
2202 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2204 ("%s: found entry pointing to a different vnode (%p != %p)",
2205 __func__, NULL, vp));
2207 KASSERT(n2->nc_vp == vp,
2208 ("%s: found entry pointing to a different vnode (%p != %p)",
2209 __func__, n2->nc_vp, vp));
2211 * Entries are supposed to be immutable unless in the
2212 * process of getting destroyed. Accommodating for
2213 * changing timestamps is possible but not worth it.
2214 * This should be harmless in terms of correctness, in
2215 * the worst case resulting in an earlier expiration.
2216 * Alternatively, the found entry can be replaced
2219 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2222 KASSERT((n2->nc_flag & NCF_TS) != 0,
2224 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2225 n2_ts->nc_time = ncp_ts->nc_time;
2226 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2228 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2229 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2233 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2235 goto out_unlock_free;
2239 if (flag == NCF_ISDOTDOT) {
2241 * See if we are trying to add .. entry, but some other lookup
2242 * has populated v_cache_dd pointer already.
2244 if (dvp->v_cache_dd != NULL)
2245 goto out_unlock_free;
2246 KASSERT(vp == NULL || vp->v_type == VDIR,
2247 ("wrong vnode type %p", vp));
2248 vn_seqc_write_begin(dvp);
2249 dvp->v_cache_dd = ncp;
2250 vn_seqc_write_end(dvp);
2254 if (flag != NCF_ISDOTDOT) {
2256 * For this case, the cache entry maps both the
2257 * directory name in it and the name ".." for the
2258 * directory's parent.
2260 vn_seqc_write_begin(vp);
2261 if ((ndd = vp->v_cache_dd) != NULL) {
2262 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2263 cache_zap_locked(ndd);
2267 vp->v_cache_dd = ncp;
2268 vn_seqc_write_end(vp);
2269 } else if (vp->v_type != VDIR) {
2270 if (vp->v_cache_dd != NULL) {
2271 vn_seqc_write_begin(vp);
2272 vp->v_cache_dd = NULL;
2273 vn_seqc_write_end(vp);
2278 if (flag != NCF_ISDOTDOT) {
2279 if (LIST_EMPTY(&dvp->v_cache_src)) {
2281 counter_u64_add(numcachehv, 1);
2283 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2287 * If the entry is "negative", we place it into the
2288 * "negative" cache queue, otherwise, we place it into the
2289 * destination vnode's cache entries queue.
2292 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2293 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2296 if (cnp->cn_flags & ISWHITEOUT)
2297 ncp->nc_flag |= NCF_WHITE;
2298 cache_neg_insert(ncp);
2299 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2304 * Insert the new namecache entry into the appropriate chain
2305 * within the cache entries table.
2307 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2309 atomic_thread_fence_rel();
2311 * Mark the entry as fully constructed.
2312 * It is immutable past this point until its removal.
2314 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2316 cache_enter_unlock(&cel);
2321 cache_enter_unlock(&cel);
2322 atomic_subtract_long(&numcache, 1);
2328 cache_roundup_2(u_int val)
2332 for (res = 1; res <= val; res <<= 1)
2338 static struct nchashhead *
2339 nchinittbl(u_long elements, u_long *hashmask)
2341 struct nchashhead *hashtbl;
2344 hashsize = cache_roundup_2(elements) / 2;
2346 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2347 for (i = 0; i < hashsize; i++)
2348 CK_SLIST_INIT(&hashtbl[i]);
2349 *hashmask = hashsize - 1;
2354 ncfreetbl(struct nchashhead *hashtbl)
2357 free(hashtbl, M_VFSCACHE);
2361 * Name cache initialization, from vfs_init() when we are booting
2364 nchinit(void *dummy __unused)
2368 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2369 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2370 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2371 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2372 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2373 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2374 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2375 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2377 VFS_SMR_ZONE_SET(cache_zone_small);
2378 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2379 VFS_SMR_ZONE_SET(cache_zone_large);
2380 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2382 ncsize = desiredvnodes * ncsizefactor;
2383 cache_recalc_neg_min(ncnegminpct);
2384 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2385 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2386 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2388 if (ncbuckethash > nchash)
2389 ncbuckethash = nchash;
2390 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2392 for (i = 0; i < numbucketlocks; i++)
2393 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2394 ncvnodehash = ncbuckethash;
2395 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2397 for (i = 0; i < numvnodelocks; i++)
2398 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2400 for (i = 0; i < numneglists; i++) {
2401 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2402 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2403 TAILQ_INIT(&neglists[i].nl_list);
2404 TAILQ_INIT(&neglists[i].nl_hotlist);
2407 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2410 cache_vnode_init(struct vnode *vp)
2413 LIST_INIT(&vp->v_cache_src);
2414 TAILQ_INIT(&vp->v_cache_dst);
2415 vp->v_cache_dd = NULL;
2420 cache_changesize(u_long newmaxvnodes)
2422 struct nchashhead *new_nchashtbl, *old_nchashtbl;
2423 u_long new_nchash, old_nchash;
2424 struct namecache *ncp;
2429 newncsize = newmaxvnodes * ncsizefactor;
2430 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2431 if (newmaxvnodes < numbucketlocks)
2432 newmaxvnodes = numbucketlocks;
2434 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2435 /* If same hash table size, nothing to do */
2436 if (nchash == new_nchash) {
2437 ncfreetbl(new_nchashtbl);
2441 * Move everything from the old hash table to the new table.
2442 * None of the namecache entries in the table can be removed
2443 * because to do so, they have to be removed from the hash table.
2445 cache_lock_all_vnodes();
2446 cache_lock_all_buckets();
2447 old_nchashtbl = nchashtbl;
2448 old_nchash = nchash;
2449 nchashtbl = new_nchashtbl;
2450 nchash = new_nchash;
2451 for (i = 0; i <= old_nchash; i++) {
2452 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2453 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2455 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2456 CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2460 cache_recalc_neg_min(ncnegminpct);
2461 cache_unlock_all_buckets();
2462 cache_unlock_all_vnodes();
2463 ncfreetbl(old_nchashtbl);
2467 * Invalidate all entries from and to a particular vnode.
2470 cache_purge_impl(struct vnode *vp)
2472 TAILQ_HEAD(, namecache) ncps;
2473 struct namecache *ncp, *nnp;
2474 struct mtx *vlp, *vlp2;
2477 vlp = VP2VNODELOCK(vp);
2481 while (!LIST_EMPTY(&vp->v_cache_src)) {
2482 ncp = LIST_FIRST(&vp->v_cache_src);
2483 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2485 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2487 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2488 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2489 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2491 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2493 ncp = vp->v_cache_dd;
2495 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2496 ("lost dotdot link"));
2497 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2499 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2501 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2505 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2511 * Opportunistic check to see if there is anything to do.
2514 cache_has_entries(struct vnode *vp)
2517 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2518 vp->v_cache_dd == NULL)
2524 cache_purge(struct vnode *vp)
2527 SDT_PROBE1(vfs, namecache, purge, done, vp);
2528 if (!cache_has_entries(vp))
2530 cache_purge_impl(vp);
2534 * Only to be used by vgone.
2537 cache_purge_vgone(struct vnode *vp)
2541 VNPASS(VN_IS_DOOMED(vp), vp);
2542 if (cache_has_entries(vp)) {
2543 cache_purge_impl(vp);
2548 * Serialize against a potential thread doing cache_purge.
2550 vlp = VP2VNODELOCK(vp);
2551 mtx_wait_unlocked(vlp);
2552 if (cache_has_entries(vp)) {
2553 cache_purge_impl(vp);
2560 * Invalidate all negative entries for a particular directory vnode.
2563 cache_purge_negative(struct vnode *vp)
2565 TAILQ_HEAD(, namecache) ncps;
2566 struct namecache *ncp, *nnp;
2569 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2570 if (LIST_EMPTY(&vp->v_cache_src))
2573 vlp = VP2VNODELOCK(vp);
2575 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2576 if (!(ncp->nc_flag & NCF_NEGATIVE))
2578 cache_zap_negative_locked_vnode_kl(ncp, vp);
2579 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2582 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2588 cache_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2589 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2592 ASSERT_VOP_IN_SEQC(fdvp);
2593 ASSERT_VOP_IN_SEQC(fvp);
2594 ASSERT_VOP_IN_SEQC(tdvp);
2596 ASSERT_VOP_IN_SEQC(tvp);
2601 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2602 ("%s: lingering negative entry", __func__));
2604 cache_remove_cnp(tdvp, tcnp);
2610 * Validate that if an entry exists it matches.
2613 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2615 struct namecache *ncp;
2619 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2620 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2622 blp = HASH2BUCKETLOCK(hash);
2624 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2625 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2626 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2627 if (ncp->nc_vp != vp)
2628 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p vp %p\n",
2629 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp,
2638 * Flush all entries referencing a particular filesystem.
2641 cache_purgevfs(struct mount *mp)
2643 struct vnode *vp, *mvp;
2645 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2647 * Somewhat wasteful iteration over all vnodes. Would be better to
2648 * support filtering and avoid the interlock to begin with.
2650 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2651 if (!cache_has_entries(vp)) {
2663 * Perform canonical checks and cache lookup and pass on to filesystem
2664 * through the vop_cachedlookup only if needed.
2668 vfs_cache_lookup(struct vop_lookup_args *ap)
2672 struct vnode **vpp = ap->a_vpp;
2673 struct componentname *cnp = ap->a_cnp;
2674 int flags = cnp->cn_flags;
2679 if (dvp->v_type != VDIR)
2682 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2683 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2686 error = vn_dir_check_exec(dvp, cnp);
2690 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2692 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2698 /* Implementation of the getcwd syscall. */
2700 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2706 buflen = uap->buflen;
2707 if (__predict_false(buflen < 2))
2709 if (buflen > MAXPATHLEN)
2710 buflen = MAXPATHLEN;
2712 buf = uma_zalloc(namei_zone, M_WAITOK);
2713 error = vn_getcwd(buf, &retbuf, &buflen);
2715 error = copyout(retbuf, uap->buf, buflen);
2716 uma_zfree(namei_zone, buf);
2721 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
2727 pwd = pwd_get_smr();
2728 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
2730 VFS_SMR_ASSERT_NOT_ENTERED();
2732 pwd = pwd_hold(curthread);
2733 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
2739 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2746 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2747 size_t size, int flags, enum uio_seg pathseg)
2749 struct nameidata nd;
2750 char *retbuf, *freebuf;
2755 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2756 pathseg, path, fd, &cap_fstat_rights, td);
2757 if ((error = namei(&nd)) != 0)
2759 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
2761 error = copyout(retbuf, buf, size);
2762 free(freebuf, M_TEMP);
2769 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2772 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2773 uap->flags, UIO_USERSPACE));
2777 * Retrieve the full filesystem path that correspond to a vnode from the name
2778 * cache (if available)
2781 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
2788 if (__predict_false(vp == NULL))
2791 buflen = MAXPATHLEN;
2792 buf = malloc(buflen, M_TEMP, M_WAITOK);
2794 pwd = pwd_get_smr();
2795 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
2796 VFS_SMR_ASSERT_NOT_ENTERED();
2798 pwd = pwd_hold(curthread);
2799 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
2810 * This function is similar to vn_fullpath, but it attempts to lookup the
2811 * pathname relative to the global root mount point. This is required for the
2812 * auditing sub-system, as audited pathnames must be absolute, relative to the
2813 * global root mount point.
2816 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
2822 if (__predict_false(vp == NULL))
2824 buflen = MAXPATHLEN;
2825 buf = malloc(buflen, M_TEMP, M_WAITOK);
2827 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
2828 VFS_SMR_ASSERT_NOT_ENTERED();
2830 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
2839 static struct namecache *
2840 vn_dd_from_dst(struct vnode *vp)
2842 struct namecache *ncp;
2844 cache_assert_vnode_locked(vp);
2845 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
2846 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2853 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
2856 struct namecache *ncp;
2860 vlp = VP2VNODELOCK(*vp);
2862 ncp = (*vp)->v_cache_dd;
2863 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
2864 KASSERT(ncp == vn_dd_from_dst(*vp),
2865 ("%s: mismatch for dd entry (%p != %p)", __func__,
2866 ncp, vn_dd_from_dst(*vp)));
2868 ncp = vn_dd_from_dst(*vp);
2871 if (*buflen < ncp->nc_nlen) {
2874 counter_u64_add(numfullpathfail4, 1);
2876 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2880 *buflen -= ncp->nc_nlen;
2881 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2882 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2891 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2894 vn_lock(*vp, LK_SHARED | LK_RETRY);
2895 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
2898 counter_u64_add(numfullpathfail2, 1);
2899 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2904 if (VN_IS_DOOMED(dvp)) {
2905 /* forced unmount */
2908 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2912 * *vp has its use count incremented still.
2919 * Resolve a directory to a pathname.
2921 * The name of the directory can always be found in the namecache or fetched
2922 * from the filesystem. There is also guaranteed to be only one parent, meaning
2923 * we can just follow vnodes up until we find the root.
2925 * The vnode must be referenced.
2928 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
2929 size_t *len, size_t addend)
2931 #ifdef KDTRACE_HOOKS
2932 struct vnode *startvp = vp;
2937 bool slash_prefixed;
2939 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
2940 VNPASS(vp->v_usecount > 0, vp);
2944 slash_prefixed = true;
2949 slash_prefixed = false;
2954 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
2955 counter_u64_add(numfullpathcalls, 1);
2956 while (vp != rdir && vp != rootvnode) {
2958 * The vp vnode must be already fully constructed,
2959 * since it is either found in namecache or obtained
2960 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
2961 * without obtaining the vnode lock.
2963 if ((vp->v_vflag & VV_ROOT) != 0) {
2964 vn_lock(vp, LK_RETRY | LK_SHARED);
2967 * With the vnode locked, check for races with
2968 * unmount, forced or not. Note that we
2969 * already verified that vp is not equal to
2970 * the root vnode, which means that
2971 * mnt_vnodecovered can be NULL only for the
2974 if (VN_IS_DOOMED(vp) ||
2975 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
2976 vp1->v_mountedhere != vp->v_mount) {
2979 SDT_PROBE3(vfs, namecache, fullpath, return,
2989 if (vp->v_type != VDIR) {
2991 counter_u64_add(numfullpathfail1, 1);
2993 SDT_PROBE3(vfs, namecache, fullpath, return,
2997 error = vn_vptocnp(&vp, buf, &buflen);
3003 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3007 buf[--buflen] = '/';
3008 slash_prefixed = true;
3012 if (!slash_prefixed) {
3015 counter_u64_add(numfullpathfail4, 1);
3016 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3020 buf[--buflen] = '/';
3022 counter_u64_add(numfullpathfound, 1);
3025 *retbuf = buf + buflen;
3026 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3033 * Resolve an arbitrary vnode to a pathname.
3036 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3037 * resolve to a different path than the one used to find it
3038 * - namecache is not mandatory, meaning names are not guaranteed to be added
3039 * (in which case resolving fails)
3041 static void __inline
3042 cache_rev_failed_impl(int *reason, int line)
3047 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3050 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3051 char **retbuf, size_t *buflen, size_t addend)
3053 #ifdef KDTRACE_HOOKS
3054 struct vnode *startvp = vp;
3058 struct namecache *ncp;
3062 #ifdef KDTRACE_HOOKS
3065 seqc_t vp_seqc, tvp_seqc;
3068 VFS_SMR_ASSERT_ENTERED();
3070 if (!cache_fast_revlookup) {
3075 orig_buflen = *buflen;
3078 MPASS(*buflen >= 2);
3080 buf[*buflen] = '\0';
3083 if (vp == rdir || vp == rootvnode) {
3091 #ifdef KDTRACE_HOOKS
3095 ncp = NULL; /* for sdt probe down below */
3096 vp_seqc = vn_seqc_read_any(vp);
3097 if (seqc_in_modify(vp_seqc)) {
3098 cache_rev_failed(&reason);
3103 #ifdef KDTRACE_HOOKS
3106 if ((vp->v_vflag & VV_ROOT) != 0) {
3107 mp = atomic_load_ptr(&vp->v_mount);
3109 cache_rev_failed(&reason);
3112 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3113 tvp_seqc = vn_seqc_read_any(tvp);
3114 if (seqc_in_modify(tvp_seqc)) {
3115 cache_rev_failed(&reason);
3118 if (!vn_seqc_consistent(vp, vp_seqc)) {
3119 cache_rev_failed(&reason);
3126 ncp = atomic_load_ptr(&vp->v_cache_dd);
3128 cache_rev_failed(&reason);
3131 nc_flag = atomic_load_char(&ncp->nc_flag);
3132 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3133 cache_rev_failed(&reason);
3136 if (!cache_ncp_canuse(ncp)) {
3137 cache_rev_failed(&reason);
3140 if (ncp->nc_nlen >= *buflen) {
3141 cache_rev_failed(&reason);
3145 *buflen -= ncp->nc_nlen;
3146 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3150 tvp_seqc = vn_seqc_read_any(tvp);
3151 if (seqc_in_modify(tvp_seqc)) {
3152 cache_rev_failed(&reason);
3155 if (!vn_seqc_consistent(vp, vp_seqc)) {
3156 cache_rev_failed(&reason);
3161 if (vp == rdir || vp == rootvnode)
3166 *retbuf = buf + *buflen;
3167 *buflen = orig_buflen - *buflen + addend;
3168 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3172 *buflen = orig_buflen;
3173 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3179 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3182 size_t orig_buflen, addend;
3188 orig_buflen = *buflen;
3192 if (vp->v_type != VDIR) {
3194 buf[*buflen] = '\0';
3195 error = vn_vptocnp(&vp, buf, buflen);
3204 addend = orig_buflen - *buflen;
3207 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3211 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3213 * Since the namecache does not track handlings, the caller is expected to first
3214 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3216 * Then we have 2 cases:
3217 * - if the found vnode is a directory, the path can be constructed just by
3218 * fullowing names up the chain
3219 * - otherwise we populate the buffer with the saved name and start resolving
3223 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3228 struct componentname *cnp;
3236 if (*buflen > MAXPATHLEN)
3237 *buflen = MAXPATHLEN;
3239 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3244 * Check for VBAD to work around the vp_crossmp bug in lookup().
3246 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3247 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3248 * If the type is VDIR (like in this very case) we can skip looking
3249 * at ni_dvp in the first place. However, since vnodes get passed here
3250 * unlocked the target may transition to doomed state (type == VBAD)
3251 * before we get to evaluate the condition. If this happens, we will
3252 * populate part of the buffer and descend to vn_fullpath_dir with
3253 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3255 * This should be atomic_load(&vp->v_type) but it is ilegal to take
3256 * an address of a bit field, even if said field is sized to char.
3257 * Work around the problem by reading the value into a full-sized enum
3258 * and then re-reading it with atomic_load which will still prevent
3259 * the compiler from re-reading down the road.
3262 type = atomic_load_int(&type);
3269 addend = cnp->cn_namelen + 2;
3270 if (*buflen < addend) {
3275 tmpbuf = buf + *buflen;
3277 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3278 tmpbuf[addend - 1] = '\0';
3283 pwd = pwd_get_smr();
3284 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3286 VFS_SMR_ASSERT_NOT_ENTERED();
3288 pwd = pwd_hold(curthread);
3290 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3306 vn_dir_dd_ino(struct vnode *vp)
3308 struct namecache *ncp;
3313 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3314 vlp = VP2VNODELOCK(vp);
3316 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3317 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3320 vs = vget_prep(ddvp);
3322 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3331 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3333 struct namecache *ncp;
3337 vlp = VP2VNODELOCK(vp);
3339 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3340 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3346 l = min(ncp->nc_nlen, buflen - 1);
3347 memcpy(buf, ncp->nc_name, l);
3354 * This function updates path string to vnode's full global path
3355 * and checks the size of the new path string against the pathlen argument.
3357 * Requires a locked, referenced vnode.
3358 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3360 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3361 * because it falls back to the ".." lookup if the namecache lookup fails.
3364 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3367 struct nameidata nd;
3372 ASSERT_VOP_ELOCKED(vp, __func__);
3374 /* Construct global filesystem path from vp. */
3376 error = vn_fullpath_global(vp, &rpath, &fbuf);
3383 if (strlen(rpath) >= pathlen) {
3385 error = ENAMETOOLONG;
3390 * Re-lookup the vnode by path to detect a possible rename.
3391 * As a side effect, the vnode is relocked.
3392 * If vnode was renamed, return ENOENT.
3394 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3395 UIO_SYSSPACE, path, td);
3401 NDFREE(&nd, NDF_ONLY_PNBUF);
3405 strcpy(path, rpath);
3418 db_print_vpath(struct vnode *vp)
3421 while (vp != NULL) {
3422 db_printf("%p: ", vp);
3423 if (vp == rootvnode) {
3427 if (vp->v_vflag & VV_ROOT) {
3428 db_printf("<mount point>");
3429 vp = vp->v_mount->mnt_vnodecovered;
3431 struct namecache *ncp;
3435 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3438 for (i = 0; i < ncp->nc_nlen; i++)
3439 db_printf("%c", *ncn++);
3452 DB_SHOW_COMMAND(vpath, db_show_vpath)
3457 db_printf("usage: show vpath <struct vnode *>\n");
3461 vp = (struct vnode *)addr;
3467 static bool __read_frequently cache_fast_lookup = true;
3468 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_lookup, CTLFLAG_RW,
3469 &cache_fast_lookup, 0, "");
3471 #define CACHE_FPL_FAILED -2020
3474 cache_fpl_cleanup_cnp(struct componentname *cnp)
3477 uma_zfree(namei_zone, cnp->cn_pnbuf);
3479 cnp->cn_pnbuf = NULL;
3480 cnp->cn_nameptr = NULL;
3485 cache_fpl_handle_root(struct nameidata *ndp, struct vnode **dpp)
3487 struct componentname *cnp;
3490 while (*(cnp->cn_nameptr) == '/') {
3495 *dpp = ndp->ni_rootdir;
3499 * Components of nameidata (or objects it can point to) which may
3500 * need restoring in case fast path lookup fails.
3502 struct nameidata_saved {
3510 struct nameidata *ndp;
3511 struct componentname *cnp;
3517 struct nameidata_saved snd;
3519 enum cache_fpl_status status:8;
3525 cache_fpl_checkpoint(struct cache_fpl *fpl, struct nameidata_saved *snd)
3528 snd->cn_flags = fpl->ndp->ni_cnd.cn_flags;
3529 snd->cn_namelen = fpl->ndp->ni_cnd.cn_namelen;
3530 snd->cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3531 snd->ni_pathlen = fpl->ndp->ni_pathlen;
3535 cache_fpl_restore(struct cache_fpl *fpl, struct nameidata_saved *snd)
3538 fpl->ndp->ni_cnd.cn_flags = snd->cn_flags;
3539 fpl->ndp->ni_cnd.cn_namelen = snd->cn_namelen;
3540 fpl->ndp->ni_cnd.cn_nameptr = snd->cn_nameptr;
3541 fpl->ndp->ni_pathlen = snd->ni_pathlen;
3545 #define cache_fpl_smr_assert_entered(fpl) ({ \
3546 struct cache_fpl *_fpl = (fpl); \
3547 MPASS(_fpl->in_smr == true); \
3548 VFS_SMR_ASSERT_ENTERED(); \
3550 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
3551 struct cache_fpl *_fpl = (fpl); \
3552 MPASS(_fpl->in_smr == false); \
3553 VFS_SMR_ASSERT_NOT_ENTERED(); \
3556 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3557 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3560 #define cache_fpl_smr_enter_initial(fpl) ({ \
3561 struct cache_fpl *_fpl = (fpl); \
3563 _fpl->in_smr = true; \
3566 #define cache_fpl_smr_enter(fpl) ({ \
3567 struct cache_fpl *_fpl = (fpl); \
3568 MPASS(_fpl->in_smr == false); \
3570 _fpl->in_smr = true; \
3573 #define cache_fpl_smr_exit(fpl) ({ \
3574 struct cache_fpl *_fpl = (fpl); \
3575 MPASS(_fpl->in_smr == true); \
3577 _fpl->in_smr = false; \
3581 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3584 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3585 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3586 ("%s: converting to abort from %d at %d, set at %d\n",
3587 __func__, fpl->status, line, fpl->line));
3589 fpl->status = CACHE_FPL_STATUS_ABORTED;
3591 return (CACHE_FPL_FAILED);
3594 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
3597 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3600 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3601 ("%s: setting to partial at %d, but already set to %d at %d\n",
3602 __func__, line, fpl->status, fpl->line));
3603 cache_fpl_smr_assert_entered(fpl);
3604 fpl->status = CACHE_FPL_STATUS_PARTIAL;
3606 return (CACHE_FPL_FAILED);
3609 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
3612 cache_fpl_handled_impl(struct cache_fpl *fpl, int error, int line)
3615 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3616 ("%s: setting to handled at %d, but already set to %d at %d\n",
3617 __func__, line, fpl->status, fpl->line));
3618 cache_fpl_smr_assert_not_entered(fpl);
3619 MPASS(error != CACHE_FPL_FAILED);
3620 fpl->status = CACHE_FPL_STATUS_HANDLED;
3625 #define cache_fpl_handled(x, e) cache_fpl_handled_impl((x), (e), __LINE__)
3627 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3628 (LOCKLEAF | LOCKPARENT | WANTPARENT | NOCACHE | FOLLOW | LOCKSHARED | SAVENAME | \
3629 SAVESTART | WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
3631 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3632 (ISDOTDOT | MAKEENTRY | ISLASTCN)
3634 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3635 "supported and internal flags overlap");
3638 cache_fpl_islastcn(struct nameidata *ndp)
3641 return (*ndp->ni_next == 0);
3645 cache_fpl_isdotdot(struct componentname *cnp)
3648 if (cnp->cn_namelen == 2 &&
3649 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3655 cache_can_fplookup(struct cache_fpl *fpl)
3657 struct nameidata *ndp;
3658 struct componentname *cnp;
3663 td = cnp->cn_thread;
3665 if (!cache_fast_lookup) {
3666 cache_fpl_aborted(fpl);
3670 if (mac_vnode_check_lookup_enabled()) {
3671 cache_fpl_aborted(fpl);
3675 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3676 cache_fpl_aborted(fpl);
3679 if (IN_CAPABILITY_MODE(td)) {
3680 cache_fpl_aborted(fpl);
3683 if (AUDITING_TD(td)) {
3684 cache_fpl_aborted(fpl);
3687 if (ndp->ni_startdir != NULL) {
3688 cache_fpl_aborted(fpl);
3695 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
3697 struct nameidata *ndp;
3702 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
3703 if (__predict_false(error != 0)) {
3704 cache_fpl_smr_exit(fpl);
3705 return (cache_fpl_aborted(fpl));
3707 fpl->fsearch = fsearch;
3712 cache_fplookup_vnode_supported(struct vnode *vp)
3715 return (vp->v_type != VLNK);
3718 static int __noinline
3719 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
3722 struct componentname *cnp;
3728 cache_fpl_smr_exit(fpl);
3729 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
3730 return (cache_fpl_handled(fpl, ENOENT));
3732 return (cache_fpl_aborted(fpl));
3736 * The target vnode is not supported, prepare for the slow path to take over.
3738 static int __noinline
3739 cache_fplookup_partial_setup(struct cache_fpl *fpl)
3741 struct nameidata *ndp;
3742 struct componentname *cnp;
3752 dvp_seqc = fpl->dvp_seqc;
3754 if (!pwd_hold_smr(pwd)) {
3755 cache_fpl_smr_exit(fpl);
3756 return (cache_fpl_aborted(fpl));
3759 dvs = vget_prep_smr(dvp);
3760 cache_fpl_smr_exit(fpl);
3761 if (__predict_false(dvs == VGET_NONE)) {
3763 return (cache_fpl_aborted(fpl));
3766 vget_finish_ref(dvp, dvs);
3767 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3770 return (cache_fpl_aborted(fpl));
3773 cache_fpl_restore(fpl, &fpl->snd);
3775 ndp->ni_startdir = dvp;
3776 cnp->cn_flags |= MAKEENTRY;
3777 if (cache_fpl_islastcn(ndp))
3778 cnp->cn_flags |= ISLASTCN;
3779 if (cache_fpl_isdotdot(cnp))
3780 cnp->cn_flags |= ISDOTDOT;
3786 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
3788 struct componentname *cnp;
3795 tvp_seqc = fpl->tvp_seqc;
3797 if ((cnp->cn_flags & LOCKLEAF) != 0) {
3798 lkflags = LK_SHARED;
3799 if ((cnp->cn_flags & LOCKSHARED) == 0)
3800 lkflags = LK_EXCLUSIVE;
3801 error = vget_finish(tvp, lkflags, tvs);
3802 if (__predict_false(error != 0)) {
3803 return (cache_fpl_aborted(fpl));
3806 vget_finish_ref(tvp, tvs);
3809 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
3810 if ((cnp->cn_flags & LOCKLEAF) != 0)
3814 return (cache_fpl_aborted(fpl));
3817 return (cache_fpl_handled(fpl, 0));
3821 * They want to possibly modify the state of the namecache.
3823 * Don't try to match the API contract, just leave.
3824 * TODO: this leaves scalability on the table
3827 cache_fplookup_final_modifying(struct cache_fpl *fpl)
3829 struct componentname *cnp;
3832 MPASS(cnp->cn_nameiop != LOOKUP);
3833 return (cache_fpl_partial(fpl));
3836 static int __noinline
3837 cache_fplookup_final_withparent(struct cache_fpl *fpl)
3839 struct componentname *cnp;
3840 enum vgetstate dvs, tvs;
3841 struct vnode *dvp, *tvp;
3847 dvp_seqc = fpl->dvp_seqc;
3850 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
3853 * This is less efficient than it can be for simplicity.
3855 dvs = vget_prep_smr(dvp);
3856 if (__predict_false(dvs == VGET_NONE)) {
3857 return (cache_fpl_aborted(fpl));
3859 tvs = vget_prep_smr(tvp);
3860 if (__predict_false(tvs == VGET_NONE)) {
3861 cache_fpl_smr_exit(fpl);
3862 vget_abort(dvp, dvs);
3863 return (cache_fpl_aborted(fpl));
3866 cache_fpl_smr_exit(fpl);
3868 if ((cnp->cn_flags & LOCKPARENT) != 0) {
3869 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
3870 if (__predict_false(error != 0)) {
3871 vget_abort(tvp, tvs);
3872 return (cache_fpl_aborted(fpl));
3875 vget_finish_ref(dvp, dvs);
3878 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3879 vget_abort(tvp, tvs);
3880 if ((cnp->cn_flags & LOCKPARENT) != 0)
3884 return (cache_fpl_aborted(fpl));
3887 error = cache_fplookup_final_child(fpl, tvs);
3888 if (__predict_false(error != 0)) {
3889 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
3890 if ((cnp->cn_flags & LOCKPARENT) != 0)
3897 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
3902 cache_fplookup_final(struct cache_fpl *fpl)
3904 struct componentname *cnp;
3906 struct vnode *dvp, *tvp;
3911 dvp_seqc = fpl->dvp_seqc;
3914 VNPASS(cache_fplookup_vnode_supported(dvp), dvp);
3916 if (cnp->cn_nameiop != LOOKUP) {
3917 return (cache_fplookup_final_modifying(fpl));
3920 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
3921 return (cache_fplookup_final_withparent(fpl));
3923 tvs = vget_prep_smr(tvp);
3924 if (__predict_false(tvs == VGET_NONE)) {
3925 return (cache_fpl_partial(fpl));
3928 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3929 cache_fpl_smr_exit(fpl);
3930 vget_abort(tvp, tvs);
3931 return (cache_fpl_aborted(fpl));
3934 cache_fpl_smr_exit(fpl);
3935 return (cache_fplookup_final_child(fpl, tvs));
3938 static int __noinline
3939 cache_fplookup_dot(struct cache_fpl *fpl)
3946 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3947 if (seqc_in_modify(fpl->tvp_seqc)) {
3948 return (cache_fpl_aborted(fpl));
3951 counter_u64_add(dothits, 1);
3952 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", dvp);
3957 static int __noinline
3958 cache_fplookup_dotdot(struct cache_fpl *fpl)
3960 struct nameidata *ndp;
3961 struct componentname *cnp;
3962 struct namecache *ncp;
3972 * XXX this is racy the same way regular lookup is
3974 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
3976 if (dvp == pr->pr_root)
3979 if (dvp == ndp->ni_rootdir ||
3980 dvp == ndp->ni_topdir ||
3984 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3985 if (seqc_in_modify(fpl->tvp_seqc)) {
3986 return (cache_fpl_aborted(fpl));
3991 if ((dvp->v_vflag & VV_ROOT) != 0) {
3994 * The opposite of climb mount is needed here.
3996 return (cache_fpl_aborted(fpl));
3999 ncp = atomic_load_ptr(&dvp->v_cache_dd);
4001 return (cache_fpl_aborted(fpl));
4004 nc_flag = atomic_load_char(&ncp->nc_flag);
4005 if ((nc_flag & NCF_ISDOTDOT) != 0) {
4006 if ((nc_flag & NCF_NEGATIVE) != 0)
4007 return (cache_fpl_aborted(fpl));
4008 fpl->tvp = ncp->nc_vp;
4010 fpl->tvp = ncp->nc_dvp;
4013 if (__predict_false(!cache_ncp_canuse(ncp))) {
4014 return (cache_fpl_aborted(fpl));
4017 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
4018 if (seqc_in_modify(fpl->tvp_seqc)) {
4019 return (cache_fpl_partial(fpl));
4022 counter_u64_add(dotdothits, 1);
4026 static int __noinline
4027 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
4032 nc_flag = atomic_load_char(&ncp->nc_flag);
4033 MPASS((nc_flag & NCF_NEGATIVE) != 0);
4035 * If they want to create an entry we need to replace this one.
4037 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
4040 * This should call something similar to
4041 * cache_fplookup_final_modifying.
4043 return (cache_fpl_partial(fpl));
4045 neg_promote = cache_neg_hit_prep(ncp);
4046 if (__predict_false(!cache_ncp_canuse(ncp))) {
4047 cache_neg_hit_abort(ncp);
4048 return (cache_fpl_partial(fpl));
4050 if (__predict_false((nc_flag & NCF_WHITE) != 0)) {
4051 cache_neg_hit_abort(ncp);
4052 return (cache_fpl_partial(fpl));
4055 return (cache_fplookup_negative_promote(fpl, ncp, hash));
4057 cache_neg_hit_finish(ncp);
4058 cache_fpl_smr_exit(fpl);
4059 return (cache_fpl_handled(fpl, ENOENT));
4063 cache_fplookup_next(struct cache_fpl *fpl)
4065 struct componentname *cnp;
4066 struct namecache *ncp;
4067 struct vnode *dvp, *tvp;
4074 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.')) {
4075 return (cache_fplookup_dot(fpl));
4078 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
4080 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
4081 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
4082 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
4087 * If there is no entry we have to punt to the slow path to perform
4088 * actual lookup. Should there be nothing with this name a negative
4089 * entry will be created.
4091 if (__predict_false(ncp == NULL)) {
4092 return (cache_fpl_partial(fpl));
4095 tvp = atomic_load_ptr(&ncp->nc_vp);
4096 nc_flag = atomic_load_char(&ncp->nc_flag);
4097 if ((nc_flag & NCF_NEGATIVE) != 0) {
4098 return (cache_fplookup_neg(fpl, ncp, hash));
4101 if (__predict_false(!cache_ncp_canuse(ncp))) {
4102 return (cache_fpl_partial(fpl));
4106 fpl->tvp_seqc = vn_seqc_read_any(tvp);
4107 if (seqc_in_modify(fpl->tvp_seqc)) {
4108 return (cache_fpl_partial(fpl));
4111 if (!cache_fplookup_vnode_supported(tvp)) {
4112 return (cache_fpl_partial(fpl));
4115 counter_u64_add(numposhits, 1);
4116 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
4121 cache_fplookup_mp_supported(struct mount *mp)
4126 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4132 * Walk up the mount stack (if any).
4134 * Correctness is provided in the following ways:
4135 * - all vnodes are protected from freeing with SMR
4136 * - struct mount objects are type stable making them always safe to access
4137 * - stability of the particular mount is provided by busying it
4138 * - relationship between the vnode which is mounted on and the mount is
4139 * verified with the vnode sequence counter after busying
4140 * - association between root vnode of the mount and the mount is protected
4143 * From that point on we can read the sequence counter of the root vnode
4144 * and get the next mount on the stack (if any) using the same protection.
4146 * By the end of successful walk we are guaranteed the reached state was
4147 * indeed present at least at some point which matches the regular lookup.
4149 static int __noinline
4150 cache_fplookup_climb_mount(struct cache_fpl *fpl)
4152 struct mount *mp, *prev_mp;
4157 vp_seqc = fpl->tvp_seqc;
4159 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
4160 mp = atomic_load_ptr(&vp->v_mountedhere);
4166 if (!vfs_op_thread_enter_crit(mp)) {
4167 if (prev_mp != NULL)
4168 vfs_op_thread_exit_crit(prev_mp);
4169 return (cache_fpl_partial(fpl));
4171 if (prev_mp != NULL)
4172 vfs_op_thread_exit_crit(prev_mp);
4173 if (!vn_seqc_consistent(vp, vp_seqc)) {
4174 vfs_op_thread_exit_crit(mp);
4175 return (cache_fpl_partial(fpl));
4177 if (!cache_fplookup_mp_supported(mp)) {
4178 vfs_op_thread_exit_crit(mp);
4179 return (cache_fpl_partial(fpl));
4181 vp = atomic_load_ptr(&mp->mnt_rootvnode);
4182 if (vp == NULL || VN_IS_DOOMED(vp)) {
4183 vfs_op_thread_exit_crit(mp);
4184 return (cache_fpl_partial(fpl));
4186 vp_seqc = vn_seqc_read_any(vp);
4187 if (seqc_in_modify(vp_seqc)) {
4188 vfs_op_thread_exit_crit(mp);
4189 return (cache_fpl_partial(fpl));
4192 mp = atomic_load_ptr(&vp->v_mountedhere);
4197 vfs_op_thread_exit_crit(prev_mp);
4199 fpl->tvp_seqc = vp_seqc;
4204 cache_fplookup_need_climb_mount(struct cache_fpl *fpl)
4212 * Hack: while this is a union, the pointer tends to be NULL so save on
4215 mp = atomic_load_ptr(&vp->v_mountedhere);
4218 if (vp->v_type == VDIR)
4226 * The code was originally copy-pasted from regular lookup and despite
4227 * clean ups leaves performance on the table. Any modifications here
4228 * must take into account that in case off fallback the resulting
4229 * nameidata state has to be compatible with the original.
4232 cache_fplookup_parse(struct cache_fpl *fpl)
4234 struct nameidata *ndp;
4235 struct componentname *cnp;
4242 * Search a new directory.
4244 * The last component of the filename is left accessible via
4245 * cnp->cn_nameptr for callers that need the name. Callers needing
4246 * the name set the SAVENAME flag. When done, they assume
4247 * responsibility for freeing the pathname buffer.
4249 for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
4251 cnp->cn_namelen = cp - cnp->cn_nameptr;
4252 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4253 cache_fpl_smr_exit(fpl);
4254 return (cache_fpl_handled(fpl, ENAMETOOLONG));
4256 ndp->ni_pathlen -= cnp->cn_namelen;
4257 KASSERT(ndp->ni_pathlen <= PATH_MAX,
4258 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
4262 * Replace multiple slashes by a single slash and trailing slashes
4263 * by a null. This must be done before VOP_LOOKUP() because some
4264 * fs's don't know about trailing slashes. Remember if there were
4265 * trailing slashes to handle symlinks, existing non-directories
4266 * and non-existing files that won't be directories specially later.
4268 while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
4274 * Regular lookup performs the following:
4275 * *ndp->ni_next = '\0';
4276 * cnp->cn_flags |= TRAILINGSLASH;
4278 * Which is problematic since it modifies data read
4279 * from userspace. Then if fast path lookup was to
4280 * abort we would have to either restore it or convey
4281 * the flag. Since this is a corner case just ignore
4282 * it for simplicity.
4284 return (cache_fpl_partial(fpl));
4290 * Check for degenerate name (e.g. / or "")
4291 * which is a way of talking about a directory,
4292 * e.g. like "/." or ".".
4295 * Another corner case handled by the regular lookup
4297 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
4298 return (cache_fpl_partial(fpl));
4304 cache_fplookup_parse_advance(struct cache_fpl *fpl)
4306 struct nameidata *ndp;
4307 struct componentname *cnp;
4312 cnp->cn_nameptr = ndp->ni_next;
4313 while (*cnp->cn_nameptr == '/') {
4320 * See the API contract for VOP_FPLOOKUP_VEXEC.
4322 static int __noinline
4323 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
4325 struct componentname *cnp;
4331 dvp_seqc = fpl->dvp_seqc;
4334 * Hack: they may be looking up foo/bar, where foo is a
4335 * regular file. In such a case we need to turn ENOTDIR,
4336 * but we may happen to get here with a different error.
4338 if (dvp->v_type != VDIR) {
4340 * The check here is predominantly to catch
4341 * EOPNOTSUPP from dead_vnodeops. If the vnode
4342 * gets doomed past this point it is going to
4343 * fail seqc verification.
4345 if (VN_IS_DOOMED(dvp)) {
4346 return (cache_fpl_aborted(fpl));
4352 * Hack: handle O_SEARCH.
4354 * Open Group Base Specifications Issue 7, 2018 edition states:
4355 * If the access mode of the open file description associated with the
4356 * file descriptor is not O_SEARCH, the function shall check whether
4357 * directory searches are permitted using the current permissions of
4358 * the directory underlying the file descriptor. If the access mode is
4359 * O_SEARCH, the function shall not perform the check.
4361 * Regular lookup tests for the NOEXECCHECK flag for every path
4362 * component to decide whether to do the permission check. However,
4363 * since most lookups never have the flag (and when they do it is only
4364 * present for the first path component), lockless lookup only acts on
4365 * it if there is a permission problem. Here the flag is represented
4366 * with a boolean so that we don't have to clear it on the way out.
4368 * For simplicity this always aborts.
4369 * TODO: check if this is the first lookup and ignore the permission
4370 * problem. Note the flag has to survive fallback (if it happens to be
4374 return (cache_fpl_aborted(fpl));
4379 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4380 error = cache_fpl_aborted(fpl);
4382 cache_fpl_partial(fpl);
4386 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4387 error = cache_fpl_aborted(fpl);
4389 cache_fpl_smr_exit(fpl);
4390 cache_fpl_handled(fpl, error);
4398 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
4400 struct nameidata *ndp;
4401 struct componentname *cnp;
4405 error = CACHE_FPL_FAILED;
4409 cache_fpl_checkpoint(fpl, &fpl->snd);
4412 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
4413 if (seqc_in_modify(fpl->dvp_seqc)) {
4414 cache_fpl_aborted(fpl);
4417 mp = atomic_load_ptr(&fpl->dvp->v_mount);
4418 if (!cache_fplookup_mp_supported(mp)) {
4419 cache_fpl_aborted(fpl);
4423 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4426 error = cache_fplookup_parse(fpl);
4427 if (__predict_false(error != 0)) {
4431 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4433 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
4434 if (__predict_false(error != 0)) {
4435 error = cache_fplookup_failed_vexec(fpl, error);
4439 if (__predict_false(cache_fpl_isdotdot(cnp))) {
4440 error = cache_fplookup_dotdot(fpl);
4441 if (__predict_false(error != 0)) {
4445 error = cache_fplookup_next(fpl);
4446 if (__predict_false(error != 0)) {
4450 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4452 if (cache_fplookup_need_climb_mount(fpl)) {
4453 error = cache_fplookup_climb_mount(fpl);
4454 if (__predict_false(error != 0)) {
4460 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4462 if (cache_fpl_islastcn(ndp)) {
4463 error = cache_fplookup_final(fpl);
4467 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
4468 error = cache_fpl_aborted(fpl);
4472 fpl->dvp = fpl->tvp;
4473 fpl->dvp_seqc = fpl->tvp_seqc;
4475 cache_fplookup_parse_advance(fpl);
4476 cache_fpl_checkpoint(fpl, &fpl->snd);
4479 switch (fpl->status) {
4480 case CACHE_FPL_STATUS_UNSET:
4481 __assert_unreachable();
4483 case CACHE_FPL_STATUS_PARTIAL:
4484 cache_fpl_smr_assert_entered(fpl);
4485 return (cache_fplookup_partial_setup(fpl));
4486 case CACHE_FPL_STATUS_ABORTED:
4488 cache_fpl_smr_exit(fpl);
4489 return (CACHE_FPL_FAILED);
4490 case CACHE_FPL_STATUS_HANDLED:
4491 MPASS(error != CACHE_FPL_FAILED);
4492 cache_fpl_smr_assert_not_entered(fpl);
4493 if (__predict_false(error != 0)) {
4496 cache_fpl_cleanup_cnp(cnp);
4499 ndp->ni_dvp = fpl->dvp;
4500 ndp->ni_vp = fpl->tvp;
4501 if (cnp->cn_flags & SAVENAME)
4502 cnp->cn_flags |= HASBUF;
4504 cache_fpl_cleanup_cnp(cnp);
4510 * Fast path lookup protected with SMR and sequence counters.
4512 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
4514 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
4517 * Traditional vnode lookup conceptually looks like this:
4523 * vn_unlock(current);
4530 * Each jump to the next vnode is safe memory-wise and atomic with respect to
4531 * any modifications thanks to holding respective locks.
4533 * The same guarantee can be provided with a combination of safe memory
4534 * reclamation and sequence counters instead. If all operations which affect
4535 * the relationship between the current vnode and the one we are looking for
4536 * also modify the counter, we can verify whether all the conditions held as
4537 * we made the jump. This includes things like permissions, mount points etc.
4538 * Counter modification is provided by enclosing relevant places in
4539 * vn_seqc_write_begin()/end() calls.
4541 * Thus this translates to:
4544 * dvp_seqc = seqc_read_any(dvp);
4545 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
4549 * tvp_seqc = seqc_read_any(tvp);
4550 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
4552 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
4554 * dvp = tvp; // we know nothing of importance has changed
4555 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
4559 * vget(); // secure the vnode
4560 * if (!seqc_consistent(tvp, tvp_seqc) // final check
4562 * // at this point we know nothing has changed for any parent<->child pair
4563 * // as they were crossed during the lookup, meaning we matched the guarantee
4564 * // of the locked variant
4567 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
4568 * - they are called while within vfs_smr protection which they must never exit
4569 * - EAGAIN can be returned to denote checking could not be performed, it is
4570 * always valid to return it
4571 * - if the sequence counter has not changed the result must be valid
4572 * - if the sequence counter has changed both false positives and false negatives
4573 * are permitted (since the result will be rejected later)
4574 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
4576 * Caveats to watch out for:
4577 * - vnodes are passed unlocked and unreferenced with nothing stopping
4578 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
4579 * to use atomic_load_ptr to fetch it.
4580 * - the aforementioned object can also get freed, meaning absent other means it
4581 * should be protected with vfs_smr
4582 * - either safely checking permissions as they are modified or guaranteeing
4583 * their stability is left to the routine
4586 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
4589 struct cache_fpl fpl;
4592 struct componentname *cnp;
4593 struct nameidata_saved orig;
4596 MPASS(ndp->ni_lcf == 0);
4598 fpl.status = CACHE_FPL_STATUS_UNSET;
4600 fpl.cnp = &ndp->ni_cnd;
4601 MPASS(curthread == fpl.cnp->cn_thread);
4603 if ((fpl.cnp->cn_flags & SAVESTART) != 0)
4604 MPASS(fpl.cnp->cn_nameiop != LOOKUP);
4606 if (!cache_can_fplookup(&fpl)) {
4607 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4608 *status = fpl.status;
4609 return (EOPNOTSUPP);
4612 cache_fpl_checkpoint(&fpl, &orig);
4614 cache_fpl_smr_enter_initial(&fpl);
4615 fpl.fsearch = false;
4616 pwd = pwd_get_smr();
4618 ndp->ni_rootdir = pwd->pwd_rdir;
4619 ndp->ni_topdir = pwd->pwd_jdir;
4622 cnp->cn_nameptr = cnp->cn_pnbuf;
4623 if (cnp->cn_pnbuf[0] == '/') {
4624 cache_fpl_handle_root(ndp, &dvp);
4626 if (ndp->ni_dirfd == AT_FDCWD) {
4627 dvp = pwd->pwd_cdir;
4629 error = cache_fplookup_dirfd(&fpl, &dvp);
4630 if (__predict_false(error != 0)) {
4636 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
4638 error = cache_fplookup_impl(dvp, &fpl);
4640 cache_fpl_smr_assert_not_entered(&fpl);
4641 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4643 *status = fpl.status;
4644 switch (fpl.status) {
4645 case CACHE_FPL_STATUS_UNSET:
4646 __assert_unreachable();
4648 case CACHE_FPL_STATUS_HANDLED:
4649 SDT_PROBE3(vfs, namei, lookup, return, error,
4650 (error == 0 ? ndp->ni_vp : NULL), true);
4652 case CACHE_FPL_STATUS_PARTIAL:
4655 * Status restored by cache_fplookup_partial_setup.
4658 case CACHE_FPL_STATUS_ABORTED:
4659 cache_fpl_restore(&fpl, &orig);