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 */
165 struct namecache nc_nc;
169 * At least mips n32 performs 64-bit accesses to timespec as found
170 * in namecache_ts and requires them to be aligned. Since others
171 * may be in the same spot suffer a little bit and enforce the
172 * alignment for everyone. Note this is a nop for 64-bit platforms.
174 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
175 #define CACHE_PATH_CUTOFF 39
177 #define CACHE_ZONE_SMALL_SIZE (sizeof(struct namecache) + CACHE_PATH_CUTOFF + 1)
178 #define CACHE_ZONE_SMALL_TS_SIZE (sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1)
179 #define CACHE_ZONE_LARGE_SIZE (sizeof(struct namecache) + NAME_MAX + 1)
180 #define CACHE_ZONE_LARGE_TS_SIZE (sizeof(struct namecache_ts) + NAME_MAX + 1)
182 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
183 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
184 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
185 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
187 #define nc_vp n_un.nu_vp
188 #define nc_neg n_un.nu_neg
191 * Flags in namecache.nc_flag
193 #define NCF_WHITE 0x01
194 #define NCF_ISDOTDOT 0x02
197 #define NCF_DVDROP 0x10
198 #define NCF_NEGATIVE 0x20
199 #define NCF_INVALID 0x40
203 * Flags in negstate.neg_flag
208 * Mark an entry as invalid.
210 * This is called before it starts getting deconstructed.
213 cache_ncp_invalidate(struct namecache *ncp)
216 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
217 ("%s: entry %p already invalid", __func__, ncp));
218 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
219 atomic_thread_fence_rel();
223 * Check whether the entry can be safely used.
225 * All places which elide locks are supposed to call this after they are
226 * done with reading from an entry.
229 cache_ncp_canuse(struct namecache *ncp)
232 atomic_thread_fence_acq();
233 return ((atomic_load_char(&ncp->nc_flag) & (NCF_INVALID | NCF_WIP)) == 0);
237 * Name caching works as follows:
239 * Names found by directory scans are retained in a cache
240 * for future reference. It is managed LRU, so frequently
241 * used names will hang around. Cache is indexed by hash value
242 * obtained from (dvp, name) where dvp refers to the directory
245 * If it is a "negative" entry, (i.e. for a name that is known NOT to
246 * exist) the vnode pointer will be NULL.
248 * Upon reaching the last segment of a path, if the reference
249 * is for DELETE, or NOCACHE is set (rewrite), and the
250 * name is located in the cache, it will be dropped.
252 * These locks are used (in the order in which they can be taken):
254 * vnodelock mtx vnode lists and v_cache_dd field protection
255 * bucketlock mtx for access to given set of hash buckets
256 * neglist mtx negative entry LRU management
258 * It is legal to take multiple vnodelock and bucketlock locks. The locking
259 * order is lower address first. Both are recursive.
261 * "." lookups are lockless.
263 * ".." and vnode -> name lookups require vnodelock.
265 * name -> vnode lookup requires the relevant bucketlock to be held for reading.
267 * Insertions and removals of entries require involved vnodes and bucketlocks
268 * to be locked to provide safe operation against other threads modifying the
271 * Some lookups result in removal of the found entry (e.g. getting rid of a
272 * negative entry with the intent to create a positive one), which poses a
273 * problem when multiple threads reach the state. Similarly, two different
274 * threads can purge two different vnodes and try to remove the same name.
276 * If the already held vnode lock is lower than the second required lock, we
277 * can just take the other lock. However, in the opposite case, this could
278 * deadlock. As such, this is resolved by trylocking and if that fails unlocking
279 * the first node, locking everything in order and revalidating the state.
284 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
285 "Name cache parameters");
287 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
288 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
289 "Total namecache capacity");
291 u_int ncsizefactor = 2;
292 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
293 "Size factor for namecache");
295 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
296 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
297 "Ratio of negative namecache entries");
300 * Negative entry % of namecahe capacity above which automatic eviction is allowed.
302 * Check cache_neg_evict_cond for details.
304 static u_int ncnegminpct = 3;
306 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
307 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
308 "Negative entry count above which automatic eviction is allowed");
311 * Structures associated with name caching.
313 #define NCHHASH(hash) \
314 (&nchashtbl[(hash) & nchash])
315 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
316 static u_long __read_mostly nchash; /* size of hash table */
317 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
318 "Size of namecache hash table");
319 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
320 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
322 struct nchstats nchstats; /* cache effectiveness statistics */
324 static bool __read_frequently cache_fast_revlookup = true;
325 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
326 &cache_fast_revlookup, 0, "");
328 static u_int __exclusive_cache_line neg_cycle;
331 #define numneglists (ncneghash + 1)
334 struct mtx nl_evict_lock;
335 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
336 TAILQ_HEAD(, namecache) nl_list;
337 TAILQ_HEAD(, namecache) nl_hotlist;
339 } __aligned(CACHE_LINE_SIZE);
341 static struct neglist neglists[numneglists];
343 static inline struct neglist *
344 NCP2NEGLIST(struct namecache *ncp)
347 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
350 static inline struct negstate *
351 NCP2NEGSTATE(struct namecache *ncp)
354 MPASS(ncp->nc_flag & NCF_NEGATIVE);
355 return (&ncp->nc_neg);
358 #define numbucketlocks (ncbuckethash + 1)
359 static u_int __read_mostly ncbuckethash;
360 static struct mtx_padalign __read_mostly *bucketlocks;
361 #define HASH2BUCKETLOCK(hash) \
362 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
364 #define numvnodelocks (ncvnodehash + 1)
365 static u_int __read_mostly ncvnodehash;
366 static struct mtx __read_mostly *vnodelocks;
367 static inline struct mtx *
368 VP2VNODELOCK(struct vnode *vp)
371 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
375 * UMA zones for the VFS cache.
377 * The small cache is used for entries with short names, which are the
378 * most common. The large cache is used for entries which are too big to
379 * fit in the small cache.
381 static uma_zone_t __read_mostly cache_zone_small;
382 static uma_zone_t __read_mostly cache_zone_small_ts;
383 static uma_zone_t __read_mostly cache_zone_large;
384 static uma_zone_t __read_mostly cache_zone_large_ts;
386 static struct namecache *
387 cache_alloc(int len, int ts)
389 struct namecache_ts *ncp_ts;
390 struct namecache *ncp;
392 if (__predict_false(ts)) {
393 if (len <= CACHE_PATH_CUTOFF)
394 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
396 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
397 ncp = &ncp_ts->nc_nc;
399 if (len <= CACHE_PATH_CUTOFF)
400 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
402 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
408 cache_free(struct namecache *ncp)
410 struct namecache_ts *ncp_ts;
413 if ((ncp->nc_flag & NCF_DVDROP) != 0)
415 if (__predict_false(ncp->nc_flag & NCF_TS)) {
416 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
417 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
418 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
420 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
422 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
423 uma_zfree_smr(cache_zone_small, ncp);
425 uma_zfree_smr(cache_zone_large, ncp);
430 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
432 struct namecache_ts *ncp_ts;
434 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
435 (tsp == NULL && ticksp == NULL),
441 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
442 *tsp = ncp_ts->nc_time;
443 *ticksp = ncp_ts->nc_ticks;
447 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
448 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
449 "VFS namecache enabled");
452 /* Export size information to userland */
453 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
454 sizeof(struct namecache), "sizeof(struct namecache)");
457 * The new name cache statistics
459 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
460 "Name cache statistics");
462 #define STATNODE_ULONG(name, varname, descr) \
463 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
464 #define STATNODE_COUNTER(name, varname, descr) \
465 static COUNTER_U64_DEFINE_EARLY(varname); \
466 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
468 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
469 STATNODE_ULONG(count, numcache, "Number of cache entries");
470 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
471 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
472 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
473 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
474 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
475 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
476 STATNODE_COUNTER(posszaps, numposzaps,
477 "Number of cache hits (positive) we do not want to cache");
478 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
479 STATNODE_COUNTER(negzaps, numnegzaps,
480 "Number of cache hits (negative) we do not want to cache");
481 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
482 /* These count for vn_getcwd(), too. */
483 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
484 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
485 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
486 "Number of fullpath search errors (VOP_VPTOCNP failures)");
487 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
488 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
491 * Debug or developer statistics.
493 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
494 "Name cache debugging");
495 #define DEBUGNODE_ULONG(name, varname, descr) \
496 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
497 #define DEBUGNODE_COUNTER(name, varname, descr) \
498 static COUNTER_U64_DEFINE_EARLY(varname); \
499 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
501 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
502 "Number of successful removals after relocking");
503 static long zap_bucket_fail;
504 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
505 static long zap_bucket_fail2;
506 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
507 static long cache_lock_vnodes_cel_3_failures;
508 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
509 "Number of times 3-way vnode locking failed");
511 static void cache_zap_locked(struct namecache *ncp);
512 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
513 char **freebuf, size_t *buflen);
514 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
515 char **retbuf, size_t *buflen, size_t addend);
516 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
517 char **retbuf, size_t *buflen);
518 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
519 char **retbuf, size_t *len, size_t addend);
521 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
524 cache_assert_vlp_locked(struct mtx *vlp)
528 mtx_assert(vlp, MA_OWNED);
532 cache_assert_vnode_locked(struct vnode *vp)
536 vlp = VP2VNODELOCK(vp);
537 cache_assert_vlp_locked(vlp);
541 * TODO: With the value stored we can do better than computing the hash based
542 * on the address. The choice of FNV should also be revisited.
545 cache_prehash(struct vnode *vp)
548 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
552 cache_get_hash(char *name, u_char len, struct vnode *dvp)
555 return (fnv_32_buf(name, len, dvp->v_nchash));
558 static inline struct nchashhead *
559 NCP2BUCKET(struct namecache *ncp)
563 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
564 return (NCHHASH(hash));
567 static inline struct mtx *
568 NCP2BUCKETLOCK(struct namecache *ncp)
572 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
573 return (HASH2BUCKETLOCK(hash));
578 cache_assert_bucket_locked(struct namecache *ncp)
582 blp = NCP2BUCKETLOCK(ncp);
583 mtx_assert(blp, MA_OWNED);
587 cache_assert_bucket_unlocked(struct namecache *ncp)
591 blp = NCP2BUCKETLOCK(ncp);
592 mtx_assert(blp, MA_NOTOWNED);
595 #define cache_assert_bucket_locked(x) do { } while (0)
596 #define cache_assert_bucket_unlocked(x) do { } while (0)
599 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
601 _cache_sort_vnodes(void **p1, void **p2)
605 MPASS(*p1 != NULL || *p2 != NULL);
615 cache_lock_all_buckets(void)
619 for (i = 0; i < numbucketlocks; i++)
620 mtx_lock(&bucketlocks[i]);
624 cache_unlock_all_buckets(void)
628 for (i = 0; i < numbucketlocks; i++)
629 mtx_unlock(&bucketlocks[i]);
633 cache_lock_all_vnodes(void)
637 for (i = 0; i < numvnodelocks; i++)
638 mtx_lock(&vnodelocks[i]);
642 cache_unlock_all_vnodes(void)
646 for (i = 0; i < numvnodelocks; i++)
647 mtx_unlock(&vnodelocks[i]);
651 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
654 cache_sort_vnodes(&vlp1, &vlp2);
657 if (!mtx_trylock(vlp1))
660 if (!mtx_trylock(vlp2)) {
670 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
673 MPASS(vlp1 != NULL || vlp2 != NULL);
683 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
686 MPASS(vlp1 != NULL || vlp2 != NULL);
695 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
697 struct nchstats snap;
699 if (req->oldptr == NULL)
700 return (SYSCTL_OUT(req, 0, sizeof(snap)));
703 snap.ncs_goodhits = counter_u64_fetch(numposhits);
704 snap.ncs_neghits = counter_u64_fetch(numneghits);
705 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
706 counter_u64_fetch(numnegzaps);
707 snap.ncs_miss = counter_u64_fetch(nummisszap) +
708 counter_u64_fetch(nummiss);
710 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
712 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
713 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
714 "VFS cache effectiveness statistics");
717 cache_recalc_neg_min(u_int val)
720 neg_min = (ncsize * val) / 100;
724 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
730 error = sysctl_handle_int(oidp, &val, 0, req);
731 if (error != 0 || req->newptr == NULL)
734 if (val == ncnegminpct)
736 if (val < 0 || val > 99)
739 cache_recalc_neg_min(val);
743 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
744 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
745 "I", "Negative entry \% of namecahe capacity above which automatic eviction is allowed");
749 * Grab an atomic snapshot of the name cache hash chain lengths
751 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
752 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
756 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
758 struct nchashhead *ncpp;
759 struct namecache *ncp;
760 int i, error, n_nchash, *cntbuf;
763 n_nchash = nchash + 1; /* nchash is max index, not count */
764 if (req->oldptr == NULL)
765 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
766 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
767 cache_lock_all_buckets();
768 if (n_nchash != nchash + 1) {
769 cache_unlock_all_buckets();
770 free(cntbuf, M_TEMP);
773 /* Scan hash tables counting entries */
774 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
775 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
777 cache_unlock_all_buckets();
778 for (error = 0, i = 0; i < n_nchash; i++)
779 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
781 free(cntbuf, M_TEMP);
784 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
785 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
786 "nchash chain lengths");
789 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
792 struct nchashhead *ncpp;
793 struct namecache *ncp;
795 int count, maxlength, used, pct;
798 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
800 cache_lock_all_buckets();
801 n_nchash = nchash + 1; /* nchash is max index, not count */
805 /* Scan hash tables for applicable entries */
806 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
808 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
813 if (maxlength < count)
816 n_nchash = nchash + 1;
817 cache_unlock_all_buckets();
818 pct = (used * 100) / (n_nchash / 100);
819 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
822 error = SYSCTL_OUT(req, &used, sizeof(used));
825 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
828 error = SYSCTL_OUT(req, &pct, sizeof(pct));
833 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
834 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
835 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
839 * Negative entries management
841 * Various workloads create plenty of negative entries and barely use them
842 * afterwards. Moreover malicious users can keep performing bogus lookups
843 * adding even more entries. For example "make tinderbox" as of writing this
844 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
847 * As such, a rather aggressive eviction method is needed. The currently
848 * employed method is a placeholder.
850 * Entries are split over numneglists separate lists, each of which is further
851 * split into hot and cold entries. Entries get promoted after getting a hit.
852 * Eviction happens on addition of new entry.
854 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
855 "Name cache negative entry statistics");
857 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
858 "Number of negative cache entries");
860 static COUNTER_U64_DEFINE_EARLY(neg_created);
861 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
862 "Number of created negative entries");
864 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
865 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
866 "Number of evicted negative entries");
868 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
869 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
870 &neg_evict_skipped_empty,
871 "Number of times evicting failed due to lack of entries");
873 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
874 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
875 &neg_evict_skipped_missed,
876 "Number of times evicting failed due to target entry disappearing");
878 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
879 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
880 &neg_evict_skipped_contended,
881 "Number of times evicting failed due to contention");
883 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
884 "Number of cache hits (negative)");
887 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
892 for (i = 0; i < numneglists; i++)
893 out += neglists[i].nl_hotnum;
895 return (SYSCTL_OUT(req, &out, sizeof(out)));
897 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
898 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
899 "Number of hot negative entries");
902 cache_neg_init(struct namecache *ncp)
906 ncp->nc_flag |= NCF_NEGATIVE;
907 ns = NCP2NEGSTATE(ncp);
910 counter_u64_add(neg_created, 1);
913 #define CACHE_NEG_PROMOTION_THRESH 2
916 cache_neg_hit_prep(struct namecache *ncp)
921 ns = NCP2NEGSTATE(ncp);
922 n = atomic_load_char(&ns->neg_hit);
924 if (n >= CACHE_NEG_PROMOTION_THRESH)
926 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
929 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
933 * Nothing to do here but it is provided for completeness as some
934 * cache_neg_hit_prep callers may end up returning without even
937 #define cache_neg_hit_abort(ncp) do { } while (0)
940 cache_neg_hit_finish(struct namecache *ncp)
943 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
944 counter_u64_add(numneghits, 1);
948 * Move a negative entry to the hot list.
951 cache_neg_promote_locked(struct namecache *ncp)
956 ns = NCP2NEGSTATE(ncp);
957 nl = NCP2NEGLIST(ncp);
958 mtx_assert(&nl->nl_lock, MA_OWNED);
959 if ((ns->neg_flag & NEG_HOT) == 0) {
960 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
961 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
963 ns->neg_flag |= NEG_HOT;
968 * Move a hot negative entry to the cold list.
971 cache_neg_demote_locked(struct namecache *ncp)
976 ns = NCP2NEGSTATE(ncp);
977 nl = NCP2NEGLIST(ncp);
978 mtx_assert(&nl->nl_lock, MA_OWNED);
979 MPASS(ns->neg_flag & NEG_HOT);
980 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
981 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
983 ns->neg_flag &= ~NEG_HOT;
984 atomic_store_char(&ns->neg_hit, 0);
988 * Move a negative entry to the hot list if it matches the lookup.
990 * We have to take locks, but they may be contended and in the worst
991 * case we may need to go off CPU. We don't want to spin within the
992 * smr section and we can't block with it. Exiting the section means
993 * the found entry could have been evicted. We are going to look it
997 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
998 struct namecache *oncp, uint32_t hash)
1000 struct namecache *ncp;
1004 nl = NCP2NEGLIST(oncp);
1006 mtx_lock(&nl->nl_lock);
1008 * For hash iteration.
1013 * Avoid all surprises by only succeeding if we got the same entry and
1014 * bailing completely otherwise.
1015 * XXX There are no provisions to keep the vnode around, meaning we may
1016 * end up promoting a negative entry for a *new* vnode and returning
1017 * ENOENT on its account. This is the error we want to return anyway
1018 * and promotion is harmless.
1020 * In particular at this point there can be a new ncp which matches the
1021 * search but hashes to a different neglist.
1023 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1029 * No match to begin with.
1031 if (__predict_false(ncp == NULL)) {
1036 * The newly found entry may be something different...
1038 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1039 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1044 * ... and not even negative.
1046 nc_flag = atomic_load_char(&ncp->nc_flag);
1047 if ((nc_flag & NCF_NEGATIVE) == 0) {
1051 if (__predict_false(!cache_ncp_canuse(ncp))) {
1055 cache_neg_promote_locked(ncp);
1056 cache_neg_hit_finish(ncp);
1058 mtx_unlock(&nl->nl_lock);
1062 mtx_unlock(&nl->nl_lock);
1067 cache_neg_promote(struct namecache *ncp)
1071 nl = NCP2NEGLIST(ncp);
1072 mtx_lock(&nl->nl_lock);
1073 cache_neg_promote_locked(ncp);
1074 mtx_unlock(&nl->nl_lock);
1078 cache_neg_insert(struct namecache *ncp)
1082 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1083 cache_assert_bucket_locked(ncp);
1084 nl = NCP2NEGLIST(ncp);
1085 mtx_lock(&nl->nl_lock);
1086 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1087 mtx_unlock(&nl->nl_lock);
1088 atomic_add_long(&numneg, 1);
1092 cache_neg_remove(struct namecache *ncp)
1095 struct negstate *ns;
1097 cache_assert_bucket_locked(ncp);
1098 nl = NCP2NEGLIST(ncp);
1099 ns = NCP2NEGSTATE(ncp);
1100 mtx_lock(&nl->nl_lock);
1101 if ((ns->neg_flag & NEG_HOT) != 0) {
1102 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1105 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1107 mtx_unlock(&nl->nl_lock);
1108 atomic_subtract_long(&numneg, 1);
1111 static struct neglist *
1112 cache_neg_evict_select_list(void)
1117 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1118 nl = &neglists[c % numneglists];
1119 if (!mtx_trylock(&nl->nl_evict_lock)) {
1120 counter_u64_add(neg_evict_skipped_contended, 1);
1126 static struct namecache *
1127 cache_neg_evict_select_entry(struct neglist *nl)
1129 struct namecache *ncp, *lncp;
1130 struct negstate *ns, *lns;
1133 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1134 mtx_assert(&nl->nl_lock, MA_OWNED);
1135 ncp = TAILQ_FIRST(&nl->nl_list);
1139 lns = NCP2NEGSTATE(lncp);
1140 for (i = 1; i < 4; i++) {
1141 ncp = TAILQ_NEXT(ncp, nc_dst);
1144 ns = NCP2NEGSTATE(ncp);
1145 if (ns->neg_hit < lns->neg_hit) {
1154 cache_neg_evict(void)
1156 struct namecache *ncp, *ncp2;
1158 struct negstate *ns;
1166 nl = cache_neg_evict_select_list();
1171 mtx_lock(&nl->nl_lock);
1172 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1174 cache_neg_demote_locked(ncp);
1176 ncp = cache_neg_evict_select_entry(nl);
1178 counter_u64_add(neg_evict_skipped_empty, 1);
1179 mtx_unlock(&nl->nl_lock);
1180 mtx_unlock(&nl->nl_evict_lock);
1183 ns = NCP2NEGSTATE(ncp);
1184 nlen = ncp->nc_nlen;
1186 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1187 dvlp = VP2VNODELOCK(dvp);
1188 blp = HASH2BUCKETLOCK(hash);
1189 mtx_unlock(&nl->nl_lock);
1190 mtx_unlock(&nl->nl_evict_lock);
1194 * Note that since all locks were dropped above, the entry may be
1195 * gone or reallocated to be something else.
1197 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1198 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1199 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1203 counter_u64_add(neg_evict_skipped_missed, 1);
1207 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1208 MPASS(blp == NCP2BUCKETLOCK(ncp));
1209 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1211 cache_zap_locked(ncp);
1212 counter_u64_add(neg_evicted, 1);
1223 * Maybe evict a negative entry to create more room.
1225 * The ncnegfactor parameter limits what fraction of the total count
1226 * can comprise of negative entries. However, if the cache is just
1227 * warming up this leads to excessive evictions. As such, ncnegminpct
1228 * (recomputed to neg_min) dictates whether the above should be
1231 * Try evicting if the cache is close to full capacity regardless of
1232 * other considerations.
1235 cache_neg_evict_cond(u_long lnumcache)
1239 if (ncsize - 1000 < lnumcache)
1241 lnumneg = atomic_load_long(&numneg);
1242 if (lnumneg < neg_min)
1244 if (lnumneg * ncnegfactor < lnumcache)
1247 return (cache_neg_evict());
1251 * cache_zap_locked():
1253 * Removes a namecache entry from cache, whether it contains an actual
1254 * pointer to a vnode or if it is just a negative cache entry.
1257 cache_zap_locked(struct namecache *ncp)
1259 struct nchashhead *ncpp;
1261 if (!(ncp->nc_flag & NCF_NEGATIVE))
1262 cache_assert_vnode_locked(ncp->nc_vp);
1263 cache_assert_vnode_locked(ncp->nc_dvp);
1264 cache_assert_bucket_locked(ncp);
1266 cache_ncp_invalidate(ncp);
1268 ncpp = NCP2BUCKET(ncp);
1269 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1270 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1271 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
1272 ncp->nc_name, ncp->nc_vp);
1273 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
1274 if (ncp == ncp->nc_vp->v_cache_dd) {
1275 vn_seqc_write_begin_unheld(ncp->nc_vp);
1276 ncp->nc_vp->v_cache_dd = NULL;
1277 vn_seqc_write_end(ncp->nc_vp);
1280 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
1282 cache_neg_remove(ncp);
1284 if (ncp->nc_flag & NCF_ISDOTDOT) {
1285 if (ncp == ncp->nc_dvp->v_cache_dd) {
1286 vn_seqc_write_begin_unheld(ncp->nc_dvp);
1287 ncp->nc_dvp->v_cache_dd = NULL;
1288 vn_seqc_write_end(ncp->nc_dvp);
1291 LIST_REMOVE(ncp, nc_src);
1292 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
1293 ncp->nc_flag |= NCF_DVDROP;
1294 counter_u64_add(numcachehv, -1);
1297 atomic_subtract_long(&numcache, 1);
1301 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1305 MPASS(ncp->nc_dvp == vp);
1306 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1307 cache_assert_vnode_locked(vp);
1309 blp = NCP2BUCKETLOCK(ncp);
1311 cache_zap_locked(ncp);
1316 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1319 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1322 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1323 cache_assert_vnode_locked(vp);
1325 if (ncp->nc_flag & NCF_NEGATIVE) {
1326 if (*vlpp != NULL) {
1330 cache_zap_negative_locked_vnode_kl(ncp, vp);
1334 pvlp = VP2VNODELOCK(vp);
1335 blp = NCP2BUCKETLOCK(ncp);
1336 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1337 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1339 if (*vlpp == vlp1 || *vlpp == vlp2) {
1343 if (*vlpp != NULL) {
1347 cache_sort_vnodes(&vlp1, &vlp2);
1352 if (!mtx_trylock(vlp1))
1358 cache_zap_locked(ncp);
1360 if (to_unlock != NULL)
1361 mtx_unlock(to_unlock);
1368 MPASS(*vlpp == NULL);
1374 * If trylocking failed we can get here. We know enough to take all needed locks
1375 * in the right order and re-lookup the entry.
1378 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1379 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1382 struct namecache *rncp;
1384 cache_assert_bucket_unlocked(ncp);
1386 cache_sort_vnodes(&dvlp, &vlp);
1387 cache_lock_vnodes(dvlp, vlp);
1389 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1390 if (rncp == ncp && rncp->nc_dvp == dvp &&
1391 rncp->nc_nlen == cnp->cn_namelen &&
1392 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1396 cache_zap_locked(rncp);
1398 cache_unlock_vnodes(dvlp, vlp);
1399 counter_u64_add(zap_bucket_relock_success, 1);
1404 cache_unlock_vnodes(dvlp, vlp);
1408 static int __noinline
1409 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1410 uint32_t hash, struct mtx *blp)
1412 struct mtx *dvlp, *vlp;
1415 cache_assert_bucket_locked(ncp);
1417 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1419 if (!(ncp->nc_flag & NCF_NEGATIVE))
1420 vlp = VP2VNODELOCK(ncp->nc_vp);
1421 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1422 cache_zap_locked(ncp);
1424 cache_unlock_vnodes(dvlp, vlp);
1430 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1433 static __noinline int
1434 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1436 struct namecache *ncp;
1438 struct mtx *dvlp, *dvlp2;
1442 if (cnp->cn_namelen == 2 &&
1443 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1444 dvlp = VP2VNODELOCK(dvp);
1448 ncp = dvp->v_cache_dd;
1453 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1456 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1457 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1459 MPASS(dvp->v_cache_dd == NULL);
1465 vn_seqc_write_begin(dvp);
1466 dvp->v_cache_dd = NULL;
1467 vn_seqc_write_end(dvp);
1472 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1476 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1477 blp = HASH2BUCKETLOCK(hash);
1479 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1484 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1485 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1486 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1495 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1496 if (__predict_false(error != 0)) {
1500 counter_u64_add(numposzaps, 1);
1501 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1505 counter_u64_add(nummisszap, 1);
1506 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1510 static int __noinline
1511 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1512 struct timespec *tsp, int *ticksp)
1517 counter_u64_add(dothits, 1);
1518 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1525 * When we lookup "." we still can be asked to lock it
1528 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1529 if (ltype != VOP_ISLOCKED(*vpp)) {
1530 if (ltype == LK_EXCLUSIVE) {
1531 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1532 if (VN_IS_DOOMED((*vpp))) {
1533 /* forced unmount */
1539 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1544 static int __noinline
1545 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1546 struct timespec *tsp, int *ticksp)
1548 struct namecache_ts *ncp_ts;
1549 struct namecache *ncp;
1555 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1557 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1558 cache_remove_cnp(dvp, cnp);
1562 counter_u64_add(dotdothits, 1);
1564 dvlp = VP2VNODELOCK(dvp);
1566 ncp = dvp->v_cache_dd;
1568 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, "..", NULL);
1572 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1573 if (ncp->nc_flag & NCF_NEGATIVE)
1580 goto negative_success;
1581 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1582 cache_out_ts(ncp, tsp, ticksp);
1583 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1584 NCF_DTS && tsp != NULL) {
1585 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1586 *tsp = ncp_ts->nc_dotdottime;
1590 ltype = VOP_ISLOCKED(dvp);
1592 vs = vget_prep(*vpp);
1594 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1595 vn_lock(dvp, ltype | LK_RETRY);
1596 if (VN_IS_DOOMED(dvp)) {
1608 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1609 if (cnp->cn_flags & ISLASTCN) {
1610 counter_u64_add(numnegzaps, 1);
1611 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1618 whiteout = (ncp->nc_flag & NCF_WHITE);
1619 cache_out_ts(ncp, tsp, ticksp);
1620 if (cache_neg_hit_prep(ncp))
1621 cache_neg_promote(ncp);
1623 cache_neg_hit_finish(ncp);
1626 cnp->cn_flags |= ISWHITEOUT;
1631 * Lookup a name in the name cache
1635 * - dvp: Parent directory in which to search.
1636 * - vpp: Return argument. Will contain desired vnode on cache hit.
1637 * - cnp: Parameters of the name search. The most interesting bits of
1638 * the cn_flags field have the following meanings:
1639 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1641 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1642 * - tsp: Return storage for cache timestamp. On a successful (positive
1643 * or negative) lookup, tsp will be filled with any timespec that
1644 * was stored when this cache entry was created. However, it will
1645 * be clear for "." entries.
1646 * - ticks: Return storage for alternate cache timestamp. On a successful
1647 * (positive or negative) lookup, it will contain the ticks value
1648 * that was current when the cache entry was created, unless cnp
1651 * Either both tsp and ticks have to be provided or neither of them.
1655 * - -1: A positive cache hit. vpp will contain the desired vnode.
1656 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1657 * to a forced unmount. vpp will not be modified. If the entry
1658 * is a whiteout, then the ISWHITEOUT flag will be set in
1660 * - 0: A cache miss. vpp will not be modified.
1664 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1665 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1666 * lock is not recursively acquired.
1668 static int __noinline
1669 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1670 struct timespec *tsp, int *ticksp)
1672 struct namecache *ncp;
1679 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1680 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1683 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1684 blp = HASH2BUCKETLOCK(hash);
1687 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1688 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1689 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1693 if (__predict_false(ncp == NULL)) {
1695 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1697 counter_u64_add(nummiss, 1);
1701 if (ncp->nc_flag & NCF_NEGATIVE)
1702 goto negative_success;
1704 counter_u64_add(numposhits, 1);
1706 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1707 cache_out_ts(ncp, tsp, ticksp);
1709 vs = vget_prep(*vpp);
1711 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1718 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1719 if (cnp->cn_flags & ISLASTCN) {
1720 counter_u64_add(numnegzaps, 1);
1721 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1722 if (__predict_false(error != 0)) {
1731 whiteout = (ncp->nc_flag & NCF_WHITE);
1732 cache_out_ts(ncp, tsp, ticksp);
1733 if (cache_neg_hit_prep(ncp))
1734 cache_neg_promote(ncp);
1736 cache_neg_hit_finish(ncp);
1739 cnp->cn_flags |= ISWHITEOUT;
1744 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1745 struct timespec *tsp, int *ticksp)
1747 struct namecache *ncp;
1751 bool whiteout, neg_promote;
1754 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
1757 if (__predict_false(!doingcache)) {
1758 cnp->cn_flags &= ~MAKEENTRY;
1763 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1764 if (cnp->cn_namelen == 1)
1765 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1766 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
1767 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
1770 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1772 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
1773 cache_remove_cnp(dvp, cnp);
1777 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1780 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1781 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1782 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1786 if (__predict_false(ncp == NULL)) {
1788 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1790 counter_u64_add(nummiss, 1);
1794 nc_flag = atomic_load_char(&ncp->nc_flag);
1795 if (nc_flag & NCF_NEGATIVE)
1796 goto negative_success;
1798 counter_u64_add(numposhits, 1);
1800 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1801 cache_out_ts(ncp, tsp, ticksp);
1803 if (!cache_ncp_canuse(ncp)) {
1808 vs = vget_prep_smr(*vpp);
1810 if (__predict_false(vs == VGET_NONE)) {
1814 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1821 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1822 if (cnp->cn_flags & ISLASTCN) {
1828 cache_out_ts(ncp, tsp, ticksp);
1829 whiteout = (ncp->nc_flag & NCF_WHITE);
1830 neg_promote = cache_neg_hit_prep(ncp);
1831 if (__predict_false(!cache_ncp_canuse(ncp))) {
1832 cache_neg_hit_abort(ncp);
1838 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
1841 cache_neg_hit_finish(ncp);
1845 cnp->cn_flags |= ISWHITEOUT;
1848 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
1851 struct celockstate {
1855 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1856 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1859 cache_celockstate_init(struct celockstate *cel)
1862 bzero(cel, sizeof(*cel));
1866 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1869 struct mtx *vlp1, *vlp2;
1871 MPASS(cel->vlp[0] == NULL);
1872 MPASS(cel->vlp[1] == NULL);
1873 MPASS(cel->vlp[2] == NULL);
1875 MPASS(vp != NULL || dvp != NULL);
1877 vlp1 = VP2VNODELOCK(vp);
1878 vlp2 = VP2VNODELOCK(dvp);
1879 cache_sort_vnodes(&vlp1, &vlp2);
1890 cache_unlock_vnodes_cel(struct celockstate *cel)
1893 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
1895 if (cel->vlp[0] != NULL)
1896 mtx_unlock(cel->vlp[0]);
1897 if (cel->vlp[1] != NULL)
1898 mtx_unlock(cel->vlp[1]);
1899 if (cel->vlp[2] != NULL)
1900 mtx_unlock(cel->vlp[2]);
1904 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
1909 cache_assert_vlp_locked(cel->vlp[0]);
1910 cache_assert_vlp_locked(cel->vlp[1]);
1911 MPASS(cel->vlp[2] == NULL);
1914 vlp = VP2VNODELOCK(vp);
1917 if (vlp >= cel->vlp[1]) {
1920 if (mtx_trylock(vlp))
1922 cache_lock_vnodes_cel_3_failures++;
1923 cache_unlock_vnodes_cel(cel);
1924 if (vlp < cel->vlp[0]) {
1926 mtx_lock(cel->vlp[0]);
1927 mtx_lock(cel->vlp[1]);
1929 if (cel->vlp[0] != NULL)
1930 mtx_lock(cel->vlp[0]);
1932 mtx_lock(cel->vlp[1]);
1942 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
1946 MPASS(cel->blp[0] == NULL);
1947 MPASS(cel->blp[1] == NULL);
1949 cache_sort_vnodes(&blp1, &blp2);
1960 cache_unlock_buckets_cel(struct celockstate *cel)
1963 if (cel->blp[0] != NULL)
1964 mtx_unlock(cel->blp[0]);
1965 mtx_unlock(cel->blp[1]);
1969 * Lock part of the cache affected by the insertion.
1971 * This means vnodelocks for dvp, vp and the relevant bucketlock.
1972 * However, insertion can result in removal of an old entry. In this
1973 * case we have an additional vnode and bucketlock pair to lock.
1975 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
1976 * preserving the locking order (smaller address first).
1979 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1982 struct namecache *ncp;
1983 struct mtx *blps[2];
1985 blps[0] = HASH2BUCKETLOCK(hash);
1988 cache_lock_vnodes_cel(cel, dvp, vp);
1989 if (vp == NULL || vp->v_type != VDIR)
1991 ncp = vp->v_cache_dd;
1994 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1996 MPASS(ncp->nc_dvp == vp);
1997 blps[1] = NCP2BUCKETLOCK(ncp);
1998 if (ncp->nc_flag & NCF_NEGATIVE)
2000 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2003 * All vnodes got re-locked. Re-validate the state and if
2004 * nothing changed we are done. Otherwise restart.
2006 if (ncp == vp->v_cache_dd &&
2007 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2008 blps[1] == NCP2BUCKETLOCK(ncp) &&
2009 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2011 cache_unlock_vnodes_cel(cel);
2016 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2020 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2023 struct namecache *ncp;
2024 struct mtx *blps[2];
2026 blps[0] = HASH2BUCKETLOCK(hash);
2029 cache_lock_vnodes_cel(cel, dvp, vp);
2030 ncp = dvp->v_cache_dd;
2033 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2035 MPASS(ncp->nc_dvp == dvp);
2036 blps[1] = NCP2BUCKETLOCK(ncp);
2037 if (ncp->nc_flag & NCF_NEGATIVE)
2039 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2041 if (ncp == dvp->v_cache_dd &&
2042 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2043 blps[1] == NCP2BUCKETLOCK(ncp) &&
2044 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2046 cache_unlock_vnodes_cel(cel);
2051 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2055 cache_enter_unlock(struct celockstate *cel)
2058 cache_unlock_buckets_cel(cel);
2059 cache_unlock_vnodes_cel(cel);
2062 static void __noinline
2063 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2064 struct componentname *cnp)
2066 struct celockstate cel;
2067 struct namecache *ncp;
2071 if (dvp->v_cache_dd == NULL)
2073 len = cnp->cn_namelen;
2074 cache_celockstate_init(&cel);
2075 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2076 cache_enter_lock_dd(&cel, dvp, vp, hash);
2077 vn_seqc_write_begin(dvp);
2078 ncp = dvp->v_cache_dd;
2079 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2080 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2081 cache_zap_locked(ncp);
2085 dvp->v_cache_dd = NULL;
2086 vn_seqc_write_end(dvp);
2087 cache_enter_unlock(&cel);
2093 * Add an entry to the cache.
2096 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2097 struct timespec *tsp, struct timespec *dtsp)
2099 struct celockstate cel;
2100 struct namecache *ncp, *n2, *ndd;
2101 struct namecache_ts *ncp_ts;
2102 struct nchashhead *ncpp;
2108 VNPASS(dvp != vp, dvp);
2109 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2110 VNPASS(dvp->v_type != VNON, dvp);
2112 VNPASS(!VN_IS_DOOMED(vp), vp);
2113 VNPASS(vp->v_type != VNON, vp);
2117 if (__predict_false(!doingcache))
2122 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2123 if (cnp->cn_namelen == 1)
2125 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2126 cache_enter_dotdot_prep(dvp, vp, cnp);
2127 flag = NCF_ISDOTDOT;
2132 * Avoid blowout in namecache entries.
2135 * 1. filesystems may end up tryng to add an already existing entry
2136 * (for example this can happen after a cache miss during concurrent
2137 * lookup), in which case we will call cache_neg_evict despite not
2139 * 2. the routine may fail to free anything and no provisions are made
2140 * to make it try harder (see the inside for failure modes)
2141 * 3. it only ever looks at negative entries.
2143 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
2144 if (cache_neg_evict_cond(lnumcache)) {
2145 lnumcache = atomic_load_long(&numcache);
2147 if (__predict_false(lnumcache >= ncsize)) {
2148 atomic_subtract_long(&numcache, 1);
2149 counter_u64_add(numdrops, 1);
2153 cache_celockstate_init(&cel);
2158 * Calculate the hash key and setup as much of the new
2159 * namecache entry as possible before acquiring the lock.
2161 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2162 ncp->nc_flag = flag | NCF_WIP;
2165 cache_neg_init(ncp);
2168 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2169 ncp_ts->nc_time = *tsp;
2170 ncp_ts->nc_ticks = ticks;
2171 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2173 ncp_ts->nc_dotdottime = *dtsp;
2174 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2177 len = ncp->nc_nlen = cnp->cn_namelen;
2178 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2179 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2180 ncp->nc_name[len] = '\0';
2181 cache_enter_lock(&cel, dvp, vp, hash);
2184 * See if this vnode or negative entry is already in the cache
2185 * with this name. This can happen with concurrent lookups of
2186 * the same path name.
2188 ncpp = NCHHASH(hash);
2189 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2190 if (n2->nc_dvp == dvp &&
2191 n2->nc_nlen == cnp->cn_namelen &&
2192 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2193 MPASS(cache_ncp_canuse(n2));
2194 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2196 ("%s: found entry pointing to a different vnode (%p != %p)",
2197 __func__, NULL, vp));
2199 KASSERT(n2->nc_vp == vp,
2200 ("%s: found entry pointing to a different vnode (%p != %p)",
2201 __func__, n2->nc_vp, vp));
2203 * Entries are supposed to be immutable unless in the
2204 * process of getting destroyed. Accommodating for
2205 * changing timestamps is possible but not worth it.
2206 * This should be harmless in terms of correctness, in
2207 * the worst case resulting in an earlier expiration.
2208 * Alternatively, the found entry can be replaced
2211 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2214 KASSERT((n2->nc_flag & NCF_TS) != 0,
2216 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2217 n2_ts->nc_time = ncp_ts->nc_time;
2218 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2220 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2221 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2225 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2227 goto out_unlock_free;
2231 if (flag == NCF_ISDOTDOT) {
2233 * See if we are trying to add .. entry, but some other lookup
2234 * has populated v_cache_dd pointer already.
2236 if (dvp->v_cache_dd != NULL)
2237 goto out_unlock_free;
2238 KASSERT(vp == NULL || vp->v_type == VDIR,
2239 ("wrong vnode type %p", vp));
2240 vn_seqc_write_begin(dvp);
2241 dvp->v_cache_dd = ncp;
2242 vn_seqc_write_end(dvp);
2246 if (flag != NCF_ISDOTDOT) {
2248 * For this case, the cache entry maps both the
2249 * directory name in it and the name ".." for the
2250 * directory's parent.
2252 vn_seqc_write_begin(vp);
2253 if ((ndd = vp->v_cache_dd) != NULL) {
2254 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2255 cache_zap_locked(ndd);
2259 vp->v_cache_dd = ncp;
2260 vn_seqc_write_end(vp);
2261 } else if (vp->v_type != VDIR) {
2262 if (vp->v_cache_dd != NULL) {
2263 vn_seqc_write_begin(vp);
2264 vp->v_cache_dd = NULL;
2265 vn_seqc_write_end(vp);
2270 if (flag != NCF_ISDOTDOT) {
2271 if (LIST_EMPTY(&dvp->v_cache_src)) {
2273 counter_u64_add(numcachehv, 1);
2275 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2279 * If the entry is "negative", we place it into the
2280 * "negative" cache queue, otherwise, we place it into the
2281 * destination vnode's cache entries queue.
2284 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2285 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2288 if (cnp->cn_flags & ISWHITEOUT)
2289 ncp->nc_flag |= NCF_WHITE;
2290 cache_neg_insert(ncp);
2291 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2296 * Insert the new namecache entry into the appropriate chain
2297 * within the cache entries table.
2299 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2301 atomic_thread_fence_rel();
2303 * Mark the entry as fully constructed.
2304 * It is immutable past this point until its removal.
2306 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2308 cache_enter_unlock(&cel);
2313 cache_enter_unlock(&cel);
2314 atomic_subtract_long(&numcache, 1);
2320 cache_roundup_2(u_int val)
2324 for (res = 1; res <= val; res <<= 1)
2330 static struct nchashhead *
2331 nchinittbl(u_long elements, u_long *hashmask)
2333 struct nchashhead *hashtbl;
2336 hashsize = cache_roundup_2(elements) / 2;
2338 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2339 for (i = 0; i < hashsize; i++)
2340 CK_SLIST_INIT(&hashtbl[i]);
2341 *hashmask = hashsize - 1;
2346 ncfreetbl(struct nchashhead *hashtbl)
2349 free(hashtbl, M_VFSCACHE);
2353 * Name cache initialization, from vfs_init() when we are booting
2356 nchinit(void *dummy __unused)
2360 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2361 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2362 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2363 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2364 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2365 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2366 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2367 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2369 VFS_SMR_ZONE_SET(cache_zone_small);
2370 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2371 VFS_SMR_ZONE_SET(cache_zone_large);
2372 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2374 ncsize = desiredvnodes * ncsizefactor;
2375 cache_recalc_neg_min(ncnegminpct);
2376 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2377 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2378 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2380 if (ncbuckethash > nchash)
2381 ncbuckethash = nchash;
2382 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2384 for (i = 0; i < numbucketlocks; i++)
2385 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2386 ncvnodehash = ncbuckethash;
2387 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2389 for (i = 0; i < numvnodelocks; i++)
2390 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2392 for (i = 0; i < numneglists; i++) {
2393 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2394 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2395 TAILQ_INIT(&neglists[i].nl_list);
2396 TAILQ_INIT(&neglists[i].nl_hotlist);
2399 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2402 cache_vnode_init(struct vnode *vp)
2405 LIST_INIT(&vp->v_cache_src);
2406 TAILQ_INIT(&vp->v_cache_dst);
2407 vp->v_cache_dd = NULL;
2412 cache_changesize(u_long newmaxvnodes)
2414 struct nchashhead *new_nchashtbl, *old_nchashtbl;
2415 u_long new_nchash, old_nchash;
2416 struct namecache *ncp;
2421 newncsize = newmaxvnodes * ncsizefactor;
2422 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2423 if (newmaxvnodes < numbucketlocks)
2424 newmaxvnodes = numbucketlocks;
2426 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2427 /* If same hash table size, nothing to do */
2428 if (nchash == new_nchash) {
2429 ncfreetbl(new_nchashtbl);
2433 * Move everything from the old hash table to the new table.
2434 * None of the namecache entries in the table can be removed
2435 * because to do so, they have to be removed from the hash table.
2437 cache_lock_all_vnodes();
2438 cache_lock_all_buckets();
2439 old_nchashtbl = nchashtbl;
2440 old_nchash = nchash;
2441 nchashtbl = new_nchashtbl;
2442 nchash = new_nchash;
2443 for (i = 0; i <= old_nchash; i++) {
2444 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2445 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2447 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2448 CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2452 cache_recalc_neg_min(ncnegminpct);
2453 cache_unlock_all_buckets();
2454 cache_unlock_all_vnodes();
2455 ncfreetbl(old_nchashtbl);
2459 * Invalidate all entries from and to a particular vnode.
2462 cache_purge_impl(struct vnode *vp)
2464 TAILQ_HEAD(, namecache) ncps;
2465 struct namecache *ncp, *nnp;
2466 struct mtx *vlp, *vlp2;
2469 vlp = VP2VNODELOCK(vp);
2473 while (!LIST_EMPTY(&vp->v_cache_src)) {
2474 ncp = LIST_FIRST(&vp->v_cache_src);
2475 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2477 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2479 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2480 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2481 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2483 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2485 ncp = vp->v_cache_dd;
2487 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2488 ("lost dotdot link"));
2489 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2491 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2493 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2497 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2503 * Opportunistic check to see if there is anything to do.
2506 cache_has_entries(struct vnode *vp)
2509 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2510 vp->v_cache_dd == NULL)
2516 cache_purge(struct vnode *vp)
2519 SDT_PROBE1(vfs, namecache, purge, done, vp);
2520 if (!cache_has_entries(vp))
2522 cache_purge_impl(vp);
2526 * Only to be used by vgone.
2529 cache_purge_vgone(struct vnode *vp)
2533 VNPASS(VN_IS_DOOMED(vp), vp);
2534 if (cache_has_entries(vp)) {
2535 cache_purge_impl(vp);
2540 * Serialize against a potential thread doing cache_purge.
2542 vlp = VP2VNODELOCK(vp);
2543 mtx_wait_unlocked(vlp);
2544 if (cache_has_entries(vp)) {
2545 cache_purge_impl(vp);
2552 * Invalidate all negative entries for a particular directory vnode.
2555 cache_purge_negative(struct vnode *vp)
2557 TAILQ_HEAD(, namecache) ncps;
2558 struct namecache *ncp, *nnp;
2561 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2562 if (LIST_EMPTY(&vp->v_cache_src))
2565 vlp = VP2VNODELOCK(vp);
2567 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2568 if (!(ncp->nc_flag & NCF_NEGATIVE))
2570 cache_zap_negative_locked_vnode_kl(ncp, vp);
2571 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2574 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2580 cache_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2581 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2584 ASSERT_VOP_IN_SEQC(fdvp);
2585 ASSERT_VOP_IN_SEQC(fvp);
2586 ASSERT_VOP_IN_SEQC(tdvp);
2588 ASSERT_VOP_IN_SEQC(tvp);
2593 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2594 ("%s: lingering negative entry", __func__));
2596 cache_remove_cnp(tdvp, tcnp);
2602 * Validate that if an entry exists it matches.
2605 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2607 struct namecache *ncp;
2611 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2612 if (CK_SLIST_EMPTY(NCHHASH(hash)))
2614 blp = HASH2BUCKETLOCK(hash);
2616 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2617 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2618 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2619 if (ncp->nc_vp != vp)
2620 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p vp %p\n",
2621 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp,
2630 * Flush all entries referencing a particular filesystem.
2633 cache_purgevfs(struct mount *mp)
2635 struct vnode *vp, *mvp;
2637 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2639 * Somewhat wasteful iteration over all vnodes. Would be better to
2640 * support filtering and avoid the interlock to begin with.
2642 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2643 if (!cache_has_entries(vp)) {
2655 * Perform canonical checks and cache lookup and pass on to filesystem
2656 * through the vop_cachedlookup only if needed.
2660 vfs_cache_lookup(struct vop_lookup_args *ap)
2664 struct vnode **vpp = ap->a_vpp;
2665 struct componentname *cnp = ap->a_cnp;
2666 int flags = cnp->cn_flags;
2671 if (dvp->v_type != VDIR)
2674 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2675 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2678 error = vn_dir_check_exec(dvp, cnp);
2682 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2684 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2690 /* Implementation of the getcwd syscall. */
2692 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2698 buflen = uap->buflen;
2699 if (__predict_false(buflen < 2))
2701 if (buflen > MAXPATHLEN)
2702 buflen = MAXPATHLEN;
2704 buf = uma_zalloc(namei_zone, M_WAITOK);
2705 error = vn_getcwd(buf, &retbuf, &buflen);
2707 error = copyout(retbuf, uap->buf, buflen);
2708 uma_zfree(namei_zone, buf);
2713 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
2719 pwd = pwd_get_smr();
2720 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
2722 VFS_SMR_ASSERT_NOT_ENTERED();
2724 pwd = pwd_hold(curthread);
2725 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
2731 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2738 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2739 size_t size, int flags, enum uio_seg pathseg)
2741 struct nameidata nd;
2742 char *retbuf, *freebuf;
2747 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2748 pathseg, path, fd, &cap_fstat_rights, td);
2749 if ((error = namei(&nd)) != 0)
2751 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
2753 error = copyout(retbuf, buf, size);
2754 free(freebuf, M_TEMP);
2761 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2764 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2765 uap->flags, UIO_USERSPACE));
2769 * Retrieve the full filesystem path that correspond to a vnode from the name
2770 * cache (if available)
2773 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
2780 if (__predict_false(vp == NULL))
2783 buflen = MAXPATHLEN;
2784 buf = malloc(buflen, M_TEMP, M_WAITOK);
2786 pwd = pwd_get_smr();
2787 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
2788 VFS_SMR_ASSERT_NOT_ENTERED();
2790 pwd = pwd_hold(curthread);
2791 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
2802 * This function is similar to vn_fullpath, but it attempts to lookup the
2803 * pathname relative to the global root mount point. This is required for the
2804 * auditing sub-system, as audited pathnames must be absolute, relative to the
2805 * global root mount point.
2808 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
2814 if (__predict_false(vp == NULL))
2816 buflen = MAXPATHLEN;
2817 buf = malloc(buflen, M_TEMP, M_WAITOK);
2819 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
2820 VFS_SMR_ASSERT_NOT_ENTERED();
2822 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
2831 static struct namecache *
2832 vn_dd_from_dst(struct vnode *vp)
2834 struct namecache *ncp;
2836 cache_assert_vnode_locked(vp);
2837 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
2838 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2845 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
2848 struct namecache *ncp;
2852 vlp = VP2VNODELOCK(*vp);
2854 ncp = (*vp)->v_cache_dd;
2855 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
2856 KASSERT(ncp == vn_dd_from_dst(*vp),
2857 ("%s: mismatch for dd entry (%p != %p)", __func__,
2858 ncp, vn_dd_from_dst(*vp)));
2860 ncp = vn_dd_from_dst(*vp);
2863 if (*buflen < ncp->nc_nlen) {
2866 counter_u64_add(numfullpathfail4, 1);
2868 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2872 *buflen -= ncp->nc_nlen;
2873 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2874 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2883 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2886 vn_lock(*vp, LK_SHARED | LK_RETRY);
2887 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
2890 counter_u64_add(numfullpathfail2, 1);
2891 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2896 if (VN_IS_DOOMED(dvp)) {
2897 /* forced unmount */
2900 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2904 * *vp has its use count incremented still.
2911 * Resolve a directory to a pathname.
2913 * The name of the directory can always be found in the namecache or fetched
2914 * from the filesystem. There is also guaranteed to be only one parent, meaning
2915 * we can just follow vnodes up until we find the root.
2917 * The vnode must be referenced.
2920 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
2921 size_t *len, size_t addend)
2923 #ifdef KDTRACE_HOOKS
2924 struct vnode *startvp = vp;
2929 bool slash_prefixed;
2931 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
2932 VNPASS(vp->v_usecount > 0, vp);
2936 slash_prefixed = true;
2941 slash_prefixed = false;
2946 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
2947 counter_u64_add(numfullpathcalls, 1);
2948 while (vp != rdir && vp != rootvnode) {
2950 * The vp vnode must be already fully constructed,
2951 * since it is either found in namecache or obtained
2952 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
2953 * without obtaining the vnode lock.
2955 if ((vp->v_vflag & VV_ROOT) != 0) {
2956 vn_lock(vp, LK_RETRY | LK_SHARED);
2959 * With the vnode locked, check for races with
2960 * unmount, forced or not. Note that we
2961 * already verified that vp is not equal to
2962 * the root vnode, which means that
2963 * mnt_vnodecovered can be NULL only for the
2966 if (VN_IS_DOOMED(vp) ||
2967 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
2968 vp1->v_mountedhere != vp->v_mount) {
2971 SDT_PROBE3(vfs, namecache, fullpath, return,
2981 if (vp->v_type != VDIR) {
2983 counter_u64_add(numfullpathfail1, 1);
2985 SDT_PROBE3(vfs, namecache, fullpath, return,
2989 error = vn_vptocnp(&vp, buf, &buflen);
2995 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2999 buf[--buflen] = '/';
3000 slash_prefixed = true;
3004 if (!slash_prefixed) {
3007 counter_u64_add(numfullpathfail4, 1);
3008 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3012 buf[--buflen] = '/';
3014 counter_u64_add(numfullpathfound, 1);
3017 *retbuf = buf + buflen;
3018 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3025 * Resolve an arbitrary vnode to a pathname.
3028 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3029 * resolve to a different path than the one used to find it
3030 * - namecache is not mandatory, meaning names are not guaranteed to be added
3031 * (in which case resolving fails)
3033 static void __inline
3034 cache_rev_failed_impl(int *reason, int line)
3039 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3042 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3043 char **retbuf, size_t *buflen, size_t addend)
3045 #ifdef KDTRACE_HOOKS
3046 struct vnode *startvp = vp;
3050 struct namecache *ncp;
3054 #ifdef KDTRACE_HOOKS
3057 seqc_t vp_seqc, tvp_seqc;
3060 VFS_SMR_ASSERT_ENTERED();
3062 if (!cache_fast_revlookup) {
3067 orig_buflen = *buflen;
3070 MPASS(*buflen >= 2);
3072 buf[*buflen] = '\0';
3075 if (vp == rdir || vp == rootvnode) {
3083 #ifdef KDTRACE_HOOKS
3087 ncp = NULL; /* for sdt probe down below */
3088 vp_seqc = vn_seqc_read_any(vp);
3089 if (seqc_in_modify(vp_seqc)) {
3090 cache_rev_failed(&reason);
3095 #ifdef KDTRACE_HOOKS
3098 if ((vp->v_vflag & VV_ROOT) != 0) {
3099 mp = atomic_load_ptr(&vp->v_mount);
3101 cache_rev_failed(&reason);
3104 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3105 tvp_seqc = vn_seqc_read_any(tvp);
3106 if (seqc_in_modify(tvp_seqc)) {
3107 cache_rev_failed(&reason);
3110 if (!vn_seqc_consistent(vp, vp_seqc)) {
3111 cache_rev_failed(&reason);
3118 ncp = atomic_load_ptr(&vp->v_cache_dd);
3120 cache_rev_failed(&reason);
3123 nc_flag = atomic_load_char(&ncp->nc_flag);
3124 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3125 cache_rev_failed(&reason);
3128 if (!cache_ncp_canuse(ncp)) {
3129 cache_rev_failed(&reason);
3132 if (ncp->nc_nlen >= *buflen) {
3133 cache_rev_failed(&reason);
3137 *buflen -= ncp->nc_nlen;
3138 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3142 tvp_seqc = vn_seqc_read_any(tvp);
3143 if (seqc_in_modify(tvp_seqc)) {
3144 cache_rev_failed(&reason);
3147 if (!vn_seqc_consistent(vp, vp_seqc)) {
3148 cache_rev_failed(&reason);
3153 if (vp == rdir || vp == rootvnode)
3158 *retbuf = buf + *buflen;
3159 *buflen = orig_buflen - *buflen + addend;
3160 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3164 *buflen = orig_buflen;
3165 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3171 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3174 size_t orig_buflen, addend;
3180 orig_buflen = *buflen;
3184 if (vp->v_type != VDIR) {
3186 buf[*buflen] = '\0';
3187 error = vn_vptocnp(&vp, buf, buflen);
3196 addend = orig_buflen - *buflen;
3199 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3203 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3205 * Since the namecache does not track handlings, the caller is expected to first
3206 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3208 * Then we have 2 cases:
3209 * - if the found vnode is a directory, the path can be constructed just by
3210 * fullowing names up the chain
3211 * - otherwise we populate the buffer with the saved name and start resolving
3215 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3220 struct componentname *cnp;
3228 if (*buflen > MAXPATHLEN)
3229 *buflen = MAXPATHLEN;
3231 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3236 * Check for VBAD to work around the vp_crossmp bug in lookup().
3238 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3239 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3240 * If the type is VDIR (like in this very case) we can skip looking
3241 * at ni_dvp in the first place. However, since vnodes get passed here
3242 * unlocked the target may transition to doomed state (type == VBAD)
3243 * before we get to evaluate the condition. If this happens, we will
3244 * populate part of the buffer and descend to vn_fullpath_dir with
3245 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3247 * This should be atomic_load(&vp->v_type) but it is ilegal to take
3248 * an address of a bit field, even if said field is sized to char.
3249 * Work around the problem by reading the value into a full-sized enum
3250 * and then re-reading it with atomic_load which will still prevent
3251 * the compiler from re-reading down the road.
3254 type = atomic_load_int(&type);
3261 addend = cnp->cn_namelen + 2;
3262 if (*buflen < addend) {
3267 tmpbuf = buf + *buflen;
3269 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3270 tmpbuf[addend - 1] = '\0';
3275 pwd = pwd_get_smr();
3276 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3278 VFS_SMR_ASSERT_NOT_ENTERED();
3280 pwd = pwd_hold(curthread);
3282 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3298 vn_dir_dd_ino(struct vnode *vp)
3300 struct namecache *ncp;
3305 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3306 vlp = VP2VNODELOCK(vp);
3308 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3309 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3312 vs = vget_prep(ddvp);
3314 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3323 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3325 struct namecache *ncp;
3329 vlp = VP2VNODELOCK(vp);
3331 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3332 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3338 l = min(ncp->nc_nlen, buflen - 1);
3339 memcpy(buf, ncp->nc_name, l);
3346 * This function updates path string to vnode's full global path
3347 * and checks the size of the new path string against the pathlen argument.
3349 * Requires a locked, referenced vnode.
3350 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3352 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3353 * because it falls back to the ".." lookup if the namecache lookup fails.
3356 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3359 struct nameidata nd;
3364 ASSERT_VOP_ELOCKED(vp, __func__);
3366 /* Construct global filesystem path from vp. */
3368 error = vn_fullpath_global(vp, &rpath, &fbuf);
3375 if (strlen(rpath) >= pathlen) {
3377 error = ENAMETOOLONG;
3382 * Re-lookup the vnode by path to detect a possible rename.
3383 * As a side effect, the vnode is relocked.
3384 * If vnode was renamed, return ENOENT.
3386 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3387 UIO_SYSSPACE, path, td);
3393 NDFREE(&nd, NDF_ONLY_PNBUF);
3397 strcpy(path, rpath);
3410 db_print_vpath(struct vnode *vp)
3413 while (vp != NULL) {
3414 db_printf("%p: ", vp);
3415 if (vp == rootvnode) {
3419 if (vp->v_vflag & VV_ROOT) {
3420 db_printf("<mount point>");
3421 vp = vp->v_mount->mnt_vnodecovered;
3423 struct namecache *ncp;
3427 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3430 for (i = 0; i < ncp->nc_nlen; i++)
3431 db_printf("%c", *ncn++);
3444 DB_SHOW_COMMAND(vpath, db_show_vpath)
3449 db_printf("usage: show vpath <struct vnode *>\n");
3453 vp = (struct vnode *)addr;
3459 static bool __read_frequently cache_fast_lookup = true;
3460 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_lookup, CTLFLAG_RW,
3461 &cache_fast_lookup, 0, "");
3463 #define CACHE_FPL_FAILED -2020
3466 cache_fpl_cleanup_cnp(struct componentname *cnp)
3469 uma_zfree(namei_zone, cnp->cn_pnbuf);
3471 cnp->cn_pnbuf = NULL;
3472 cnp->cn_nameptr = NULL;
3477 cache_fpl_handle_root(struct nameidata *ndp, struct vnode **dpp)
3479 struct componentname *cnp;
3482 while (*(cnp->cn_nameptr) == '/') {
3487 *dpp = ndp->ni_rootdir;
3491 * Components of nameidata (or objects it can point to) which may
3492 * need restoring in case fast path lookup fails.
3494 struct nameidata_saved {
3502 struct nameidata *ndp;
3503 struct componentname *cnp;
3509 struct nameidata_saved snd;
3511 enum cache_fpl_status status:8;
3517 cache_fpl_checkpoint(struct cache_fpl *fpl, struct nameidata_saved *snd)
3520 snd->cn_flags = fpl->ndp->ni_cnd.cn_flags;
3521 snd->cn_namelen = fpl->ndp->ni_cnd.cn_namelen;
3522 snd->cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3523 snd->ni_pathlen = fpl->ndp->ni_pathlen;
3527 cache_fpl_restore(struct cache_fpl *fpl, struct nameidata_saved *snd)
3530 fpl->ndp->ni_cnd.cn_flags = snd->cn_flags;
3531 fpl->ndp->ni_cnd.cn_namelen = snd->cn_namelen;
3532 fpl->ndp->ni_cnd.cn_nameptr = snd->cn_nameptr;
3533 fpl->ndp->ni_pathlen = snd->ni_pathlen;
3537 #define cache_fpl_smr_assert_entered(fpl) ({ \
3538 struct cache_fpl *_fpl = (fpl); \
3539 MPASS(_fpl->in_smr == true); \
3540 VFS_SMR_ASSERT_ENTERED(); \
3542 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
3543 struct cache_fpl *_fpl = (fpl); \
3544 MPASS(_fpl->in_smr == false); \
3545 VFS_SMR_ASSERT_NOT_ENTERED(); \
3548 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3549 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3552 #define cache_fpl_smr_enter_initial(fpl) ({ \
3553 struct cache_fpl *_fpl = (fpl); \
3555 _fpl->in_smr = true; \
3558 #define cache_fpl_smr_enter(fpl) ({ \
3559 struct cache_fpl *_fpl = (fpl); \
3560 MPASS(_fpl->in_smr == false); \
3562 _fpl->in_smr = true; \
3565 #define cache_fpl_smr_exit(fpl) ({ \
3566 struct cache_fpl *_fpl = (fpl); \
3567 MPASS(_fpl->in_smr == true); \
3569 _fpl->in_smr = false; \
3573 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3576 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3577 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3578 ("%s: converting to abort from %d at %d, set at %d\n",
3579 __func__, fpl->status, line, fpl->line));
3581 fpl->status = CACHE_FPL_STATUS_ABORTED;
3583 return (CACHE_FPL_FAILED);
3586 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
3589 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3592 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3593 ("%s: setting to partial at %d, but already set to %d at %d\n",
3594 __func__, line, fpl->status, fpl->line));
3595 cache_fpl_smr_assert_entered(fpl);
3596 fpl->status = CACHE_FPL_STATUS_PARTIAL;
3598 return (CACHE_FPL_FAILED);
3601 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
3604 cache_fpl_handled_impl(struct cache_fpl *fpl, int error, int line)
3607 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3608 ("%s: setting to handled at %d, but already set to %d at %d\n",
3609 __func__, line, fpl->status, fpl->line));
3610 cache_fpl_smr_assert_not_entered(fpl);
3611 MPASS(error != CACHE_FPL_FAILED);
3612 fpl->status = CACHE_FPL_STATUS_HANDLED;
3617 #define cache_fpl_handled(x, e) cache_fpl_handled_impl((x), (e), __LINE__)
3619 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3620 (LOCKLEAF | LOCKPARENT | WANTPARENT | NOCACHE | FOLLOW | LOCKSHARED | SAVENAME | \
3621 SAVESTART | WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
3623 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3624 (ISDOTDOT | MAKEENTRY | ISLASTCN)
3626 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3627 "supported and internal flags overlap");
3630 cache_fpl_islastcn(struct nameidata *ndp)
3633 return (*ndp->ni_next == 0);
3637 cache_fpl_isdotdot(struct componentname *cnp)
3640 if (cnp->cn_namelen == 2 &&
3641 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3647 cache_can_fplookup(struct cache_fpl *fpl)
3649 struct nameidata *ndp;
3650 struct componentname *cnp;
3655 td = cnp->cn_thread;
3657 if (!cache_fast_lookup) {
3658 cache_fpl_aborted(fpl);
3662 if (mac_vnode_check_lookup_enabled()) {
3663 cache_fpl_aborted(fpl);
3667 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3668 cache_fpl_aborted(fpl);
3671 if (IN_CAPABILITY_MODE(td)) {
3672 cache_fpl_aborted(fpl);
3675 if (AUDITING_TD(td)) {
3676 cache_fpl_aborted(fpl);
3679 if (ndp->ni_startdir != NULL) {
3680 cache_fpl_aborted(fpl);
3687 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
3689 struct nameidata *ndp;
3694 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
3695 if (__predict_false(error != 0)) {
3696 cache_fpl_smr_exit(fpl);
3697 return (cache_fpl_aborted(fpl));
3699 fpl->fsearch = fsearch;
3704 cache_fplookup_vnode_supported(struct vnode *vp)
3707 return (vp->v_type != VLNK);
3710 static int __noinline
3711 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
3714 struct componentname *cnp;
3720 cache_fpl_smr_exit(fpl);
3721 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
3722 return (cache_fpl_handled(fpl, ENOENT));
3724 return (cache_fpl_aborted(fpl));
3728 * The target vnode is not supported, prepare for the slow path to take over.
3730 static int __noinline
3731 cache_fplookup_partial_setup(struct cache_fpl *fpl)
3733 struct nameidata *ndp;
3734 struct componentname *cnp;
3744 dvp_seqc = fpl->dvp_seqc;
3746 if (!pwd_hold_smr(pwd)) {
3747 cache_fpl_smr_exit(fpl);
3748 return (cache_fpl_aborted(fpl));
3751 dvs = vget_prep_smr(dvp);
3752 cache_fpl_smr_exit(fpl);
3753 if (__predict_false(dvs == VGET_NONE)) {
3755 return (cache_fpl_aborted(fpl));
3758 vget_finish_ref(dvp, dvs);
3759 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3762 return (cache_fpl_aborted(fpl));
3765 cache_fpl_restore(fpl, &fpl->snd);
3767 ndp->ni_startdir = dvp;
3768 cnp->cn_flags |= MAKEENTRY;
3769 if (cache_fpl_islastcn(ndp))
3770 cnp->cn_flags |= ISLASTCN;
3771 if (cache_fpl_isdotdot(cnp))
3772 cnp->cn_flags |= ISDOTDOT;
3778 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
3780 struct componentname *cnp;
3787 tvp_seqc = fpl->tvp_seqc;
3789 if ((cnp->cn_flags & LOCKLEAF) != 0) {
3790 lkflags = LK_SHARED;
3791 if ((cnp->cn_flags & LOCKSHARED) == 0)
3792 lkflags = LK_EXCLUSIVE;
3793 error = vget_finish(tvp, lkflags, tvs);
3794 if (__predict_false(error != 0)) {
3795 return (cache_fpl_aborted(fpl));
3798 vget_finish_ref(tvp, tvs);
3801 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
3802 if ((cnp->cn_flags & LOCKLEAF) != 0)
3806 return (cache_fpl_aborted(fpl));
3809 return (cache_fpl_handled(fpl, 0));
3813 * They want to possibly modify the state of the namecache.
3815 * Don't try to match the API contract, just leave.
3816 * TODO: this leaves scalability on the table
3819 cache_fplookup_final_modifying(struct cache_fpl *fpl)
3821 struct componentname *cnp;
3824 MPASS(cnp->cn_nameiop != LOOKUP);
3825 return (cache_fpl_partial(fpl));
3828 static int __noinline
3829 cache_fplookup_final_withparent(struct cache_fpl *fpl)
3831 struct componentname *cnp;
3832 enum vgetstate dvs, tvs;
3833 struct vnode *dvp, *tvp;
3839 dvp_seqc = fpl->dvp_seqc;
3842 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
3845 * This is less efficient than it can be for simplicity.
3847 dvs = vget_prep_smr(dvp);
3848 if (__predict_false(dvs == VGET_NONE)) {
3849 return (cache_fpl_aborted(fpl));
3851 tvs = vget_prep_smr(tvp);
3852 if (__predict_false(tvs == VGET_NONE)) {
3853 cache_fpl_smr_exit(fpl);
3854 vget_abort(dvp, dvs);
3855 return (cache_fpl_aborted(fpl));
3858 cache_fpl_smr_exit(fpl);
3860 if ((cnp->cn_flags & LOCKPARENT) != 0) {
3861 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
3862 if (__predict_false(error != 0)) {
3863 vget_abort(tvp, tvs);
3864 return (cache_fpl_aborted(fpl));
3867 vget_finish_ref(dvp, dvs);
3870 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3871 vget_abort(tvp, tvs);
3872 if ((cnp->cn_flags & LOCKPARENT) != 0)
3876 return (cache_fpl_aborted(fpl));
3879 error = cache_fplookup_final_child(fpl, tvs);
3880 if (__predict_false(error != 0)) {
3881 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
3882 if ((cnp->cn_flags & LOCKPARENT) != 0)
3889 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
3894 cache_fplookup_final(struct cache_fpl *fpl)
3896 struct componentname *cnp;
3898 struct vnode *dvp, *tvp;
3903 dvp_seqc = fpl->dvp_seqc;
3906 VNPASS(cache_fplookup_vnode_supported(dvp), dvp);
3908 if (cnp->cn_nameiop != LOOKUP) {
3909 return (cache_fplookup_final_modifying(fpl));
3912 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
3913 return (cache_fplookup_final_withparent(fpl));
3915 tvs = vget_prep_smr(tvp);
3916 if (__predict_false(tvs == VGET_NONE)) {
3917 return (cache_fpl_partial(fpl));
3920 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3921 cache_fpl_smr_exit(fpl);
3922 vget_abort(tvp, tvs);
3923 return (cache_fpl_aborted(fpl));
3926 cache_fpl_smr_exit(fpl);
3927 return (cache_fplookup_final_child(fpl, tvs));
3930 static int __noinline
3931 cache_fplookup_dot(struct cache_fpl *fpl)
3938 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3939 if (seqc_in_modify(fpl->tvp_seqc)) {
3940 return (cache_fpl_aborted(fpl));
3943 counter_u64_add(dothits, 1);
3944 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", dvp);
3949 static int __noinline
3950 cache_fplookup_dotdot(struct cache_fpl *fpl)
3952 struct nameidata *ndp;
3953 struct componentname *cnp;
3954 struct namecache *ncp;
3964 * XXX this is racy the same way regular lookup is
3966 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
3968 if (dvp == pr->pr_root)
3971 if (dvp == ndp->ni_rootdir ||
3972 dvp == ndp->ni_topdir ||
3976 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3977 if (seqc_in_modify(fpl->tvp_seqc)) {
3978 return (cache_fpl_aborted(fpl));
3983 if ((dvp->v_vflag & VV_ROOT) != 0) {
3986 * The opposite of climb mount is needed here.
3988 return (cache_fpl_aborted(fpl));
3991 ncp = atomic_load_ptr(&dvp->v_cache_dd);
3993 return (cache_fpl_aborted(fpl));
3996 nc_flag = atomic_load_char(&ncp->nc_flag);
3997 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3998 if ((nc_flag & NCF_NEGATIVE) != 0)
3999 return (cache_fpl_aborted(fpl));
4000 fpl->tvp = ncp->nc_vp;
4002 fpl->tvp = ncp->nc_dvp;
4005 if (__predict_false(!cache_ncp_canuse(ncp))) {
4006 return (cache_fpl_aborted(fpl));
4009 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
4010 if (seqc_in_modify(fpl->tvp_seqc)) {
4011 return (cache_fpl_partial(fpl));
4014 counter_u64_add(dotdothits, 1);
4018 static int __noinline
4019 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
4024 nc_flag = atomic_load_char(&ncp->nc_flag);
4025 MPASS((nc_flag & NCF_NEGATIVE) != 0);
4027 * If they want to create an entry we need to replace this one.
4029 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
4032 * This should call something similar to
4033 * cache_fplookup_final_modifying.
4035 return (cache_fpl_partial(fpl));
4037 neg_promote = cache_neg_hit_prep(ncp);
4038 if (__predict_false(!cache_ncp_canuse(ncp))) {
4039 cache_neg_hit_abort(ncp);
4040 return (cache_fpl_partial(fpl));
4042 if (__predict_false((nc_flag & NCF_WHITE) != 0)) {
4043 cache_neg_hit_abort(ncp);
4044 return (cache_fpl_partial(fpl));
4047 return (cache_fplookup_negative_promote(fpl, ncp, hash));
4049 cache_neg_hit_finish(ncp);
4050 cache_fpl_smr_exit(fpl);
4051 return (cache_fpl_handled(fpl, ENOENT));
4055 cache_fplookup_next(struct cache_fpl *fpl)
4057 struct componentname *cnp;
4058 struct namecache *ncp;
4059 struct vnode *dvp, *tvp;
4066 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.')) {
4067 return (cache_fplookup_dot(fpl));
4070 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
4072 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
4073 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
4074 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
4079 * If there is no entry we have to punt to the slow path to perform
4080 * actual lookup. Should there be nothing with this name a negative
4081 * entry will be created.
4083 if (__predict_false(ncp == NULL)) {
4084 return (cache_fpl_partial(fpl));
4087 tvp = atomic_load_ptr(&ncp->nc_vp);
4088 nc_flag = atomic_load_char(&ncp->nc_flag);
4089 if ((nc_flag & NCF_NEGATIVE) != 0) {
4090 return (cache_fplookup_neg(fpl, ncp, hash));
4093 if (__predict_false(!cache_ncp_canuse(ncp))) {
4094 return (cache_fpl_partial(fpl));
4098 fpl->tvp_seqc = vn_seqc_read_any(tvp);
4099 if (seqc_in_modify(fpl->tvp_seqc)) {
4100 return (cache_fpl_partial(fpl));
4103 if (!cache_fplookup_vnode_supported(tvp)) {
4104 return (cache_fpl_partial(fpl));
4107 counter_u64_add(numposhits, 1);
4108 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
4113 cache_fplookup_mp_supported(struct mount *mp)
4118 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4124 * Walk up the mount stack (if any).
4126 * Correctness is provided in the following ways:
4127 * - all vnodes are protected from freeing with SMR
4128 * - struct mount objects are type stable making them always safe to access
4129 * - stability of the particular mount is provided by busying it
4130 * - relationship between the vnode which is mounted on and the mount is
4131 * verified with the vnode sequence counter after busying
4132 * - association between root vnode of the mount and the mount is protected
4135 * From that point on we can read the sequence counter of the root vnode
4136 * and get the next mount on the stack (if any) using the same protection.
4138 * By the end of successful walk we are guaranteed the reached state was
4139 * indeed present at least at some point which matches the regular lookup.
4141 static int __noinline
4142 cache_fplookup_climb_mount(struct cache_fpl *fpl)
4144 struct mount *mp, *prev_mp;
4149 vp_seqc = fpl->tvp_seqc;
4151 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
4152 mp = atomic_load_ptr(&vp->v_mountedhere);
4158 if (!vfs_op_thread_enter_crit(mp)) {
4159 if (prev_mp != NULL)
4160 vfs_op_thread_exit_crit(prev_mp);
4161 return (cache_fpl_partial(fpl));
4163 if (prev_mp != NULL)
4164 vfs_op_thread_exit_crit(prev_mp);
4165 if (!vn_seqc_consistent(vp, vp_seqc)) {
4166 vfs_op_thread_exit_crit(mp);
4167 return (cache_fpl_partial(fpl));
4169 if (!cache_fplookup_mp_supported(mp)) {
4170 vfs_op_thread_exit_crit(mp);
4171 return (cache_fpl_partial(fpl));
4173 vp = atomic_load_ptr(&mp->mnt_rootvnode);
4174 if (vp == NULL || VN_IS_DOOMED(vp)) {
4175 vfs_op_thread_exit_crit(mp);
4176 return (cache_fpl_partial(fpl));
4178 vp_seqc = vn_seqc_read_any(vp);
4179 if (seqc_in_modify(vp_seqc)) {
4180 vfs_op_thread_exit_crit(mp);
4181 return (cache_fpl_partial(fpl));
4184 mp = atomic_load_ptr(&vp->v_mountedhere);
4189 vfs_op_thread_exit_crit(prev_mp);
4191 fpl->tvp_seqc = vp_seqc;
4196 cache_fplookup_need_climb_mount(struct cache_fpl *fpl)
4204 * Hack: while this is a union, the pointer tends to be NULL so save on
4207 mp = atomic_load_ptr(&vp->v_mountedhere);
4210 if (vp->v_type == VDIR)
4218 * The code was originally copy-pasted from regular lookup and despite
4219 * clean ups leaves performance on the table. Any modifications here
4220 * must take into account that in case off fallback the resulting
4221 * nameidata state has to be compatible with the original.
4224 cache_fplookup_parse(struct cache_fpl *fpl)
4226 struct nameidata *ndp;
4227 struct componentname *cnp;
4234 * Search a new directory.
4236 * The last component of the filename is left accessible via
4237 * cnp->cn_nameptr for callers that need the name. Callers needing
4238 * the name set the SAVENAME flag. When done, they assume
4239 * responsibility for freeing the pathname buffer.
4241 for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
4243 cnp->cn_namelen = cp - cnp->cn_nameptr;
4244 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4245 cache_fpl_smr_exit(fpl);
4246 return (cache_fpl_handled(fpl, ENAMETOOLONG));
4248 ndp->ni_pathlen -= cnp->cn_namelen;
4249 KASSERT(ndp->ni_pathlen <= PATH_MAX,
4250 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
4254 * Replace multiple slashes by a single slash and trailing slashes
4255 * by a null. This must be done before VOP_LOOKUP() because some
4256 * fs's don't know about trailing slashes. Remember if there were
4257 * trailing slashes to handle symlinks, existing non-directories
4258 * and non-existing files that won't be directories specially later.
4260 while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
4266 * Regular lookup performs the following:
4267 * *ndp->ni_next = '\0';
4268 * cnp->cn_flags |= TRAILINGSLASH;
4270 * Which is problematic since it modifies data read
4271 * from userspace. Then if fast path lookup was to
4272 * abort we would have to either restore it or convey
4273 * the flag. Since this is a corner case just ignore
4274 * it for simplicity.
4276 return (cache_fpl_partial(fpl));
4282 * Check for degenerate name (e.g. / or "")
4283 * which is a way of talking about a directory,
4284 * e.g. like "/." or ".".
4287 * Another corner case handled by the regular lookup
4289 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
4290 return (cache_fpl_partial(fpl));
4296 cache_fplookup_parse_advance(struct cache_fpl *fpl)
4298 struct nameidata *ndp;
4299 struct componentname *cnp;
4304 cnp->cn_nameptr = ndp->ni_next;
4305 while (*cnp->cn_nameptr == '/') {
4312 * See the API contract for VOP_FPLOOKUP_VEXEC.
4314 static int __noinline
4315 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
4317 struct componentname *cnp;
4323 dvp_seqc = fpl->dvp_seqc;
4326 * Hack: they may be looking up foo/bar, where foo is a
4327 * regular file. In such a case we need to turn ENOTDIR,
4328 * but we may happen to get here with a different error.
4330 if (dvp->v_type != VDIR) {
4332 * The check here is predominantly to catch
4333 * EOPNOTSUPP from dead_vnodeops. If the vnode
4334 * gets doomed past this point it is going to
4335 * fail seqc verification.
4337 if (VN_IS_DOOMED(dvp)) {
4338 return (cache_fpl_aborted(fpl));
4344 * Hack: handle O_SEARCH.
4346 * Open Group Base Specifications Issue 7, 2018 edition states:
4347 * If the access mode of the open file description associated with the
4348 * file descriptor is not O_SEARCH, the function shall check whether
4349 * directory searches are permitted using the current permissions of
4350 * the directory underlying the file descriptor. If the access mode is
4351 * O_SEARCH, the function shall not perform the check.
4353 * Regular lookup tests for the NOEXECCHECK flag for every path
4354 * component to decide whether to do the permission check. However,
4355 * since most lookups never have the flag (and when they do it is only
4356 * present for the first path component), lockless lookup only acts on
4357 * it if there is a permission problem. Here the flag is represented
4358 * with a boolean so that we don't have to clear it on the way out.
4360 * For simplicity this always aborts.
4361 * TODO: check if this is the first lookup and ignore the permission
4362 * problem. Note the flag has to survive fallback (if it happens to be
4366 return (cache_fpl_aborted(fpl));
4371 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4372 error = cache_fpl_aborted(fpl);
4374 cache_fpl_partial(fpl);
4378 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4379 error = cache_fpl_aborted(fpl);
4381 cache_fpl_smr_exit(fpl);
4382 cache_fpl_handled(fpl, error);
4390 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
4392 struct nameidata *ndp;
4393 struct componentname *cnp;
4397 error = CACHE_FPL_FAILED;
4401 cache_fpl_checkpoint(fpl, &fpl->snd);
4404 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
4405 if (seqc_in_modify(fpl->dvp_seqc)) {
4406 cache_fpl_aborted(fpl);
4409 mp = atomic_load_ptr(&fpl->dvp->v_mount);
4410 if (!cache_fplookup_mp_supported(mp)) {
4411 cache_fpl_aborted(fpl);
4415 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4418 error = cache_fplookup_parse(fpl);
4419 if (__predict_false(error != 0)) {
4423 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4425 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
4426 if (__predict_false(error != 0)) {
4427 error = cache_fplookup_failed_vexec(fpl, error);
4431 if (__predict_false(cache_fpl_isdotdot(cnp))) {
4432 error = cache_fplookup_dotdot(fpl);
4433 if (__predict_false(error != 0)) {
4437 error = cache_fplookup_next(fpl);
4438 if (__predict_false(error != 0)) {
4442 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4444 if (cache_fplookup_need_climb_mount(fpl)) {
4445 error = cache_fplookup_climb_mount(fpl);
4446 if (__predict_false(error != 0)) {
4452 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4454 if (cache_fpl_islastcn(ndp)) {
4455 error = cache_fplookup_final(fpl);
4459 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
4460 error = cache_fpl_aborted(fpl);
4464 fpl->dvp = fpl->tvp;
4465 fpl->dvp_seqc = fpl->tvp_seqc;
4467 cache_fplookup_parse_advance(fpl);
4468 cache_fpl_checkpoint(fpl, &fpl->snd);
4471 switch (fpl->status) {
4472 case CACHE_FPL_STATUS_UNSET:
4473 __assert_unreachable();
4475 case CACHE_FPL_STATUS_PARTIAL:
4476 cache_fpl_smr_assert_entered(fpl);
4477 return (cache_fplookup_partial_setup(fpl));
4478 case CACHE_FPL_STATUS_ABORTED:
4480 cache_fpl_smr_exit(fpl);
4481 return (CACHE_FPL_FAILED);
4482 case CACHE_FPL_STATUS_HANDLED:
4483 MPASS(error != CACHE_FPL_FAILED);
4484 cache_fpl_smr_assert_not_entered(fpl);
4485 if (__predict_false(error != 0)) {
4488 cache_fpl_cleanup_cnp(cnp);
4491 ndp->ni_dvp = fpl->dvp;
4492 ndp->ni_vp = fpl->tvp;
4493 if (cnp->cn_flags & SAVENAME)
4494 cnp->cn_flags |= HASBUF;
4496 cache_fpl_cleanup_cnp(cnp);
4502 * Fast path lookup protected with SMR and sequence counters.
4504 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
4506 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
4509 * Traditional vnode lookup conceptually looks like this:
4515 * vn_unlock(current);
4522 * Each jump to the next vnode is safe memory-wise and atomic with respect to
4523 * any modifications thanks to holding respective locks.
4525 * The same guarantee can be provided with a combination of safe memory
4526 * reclamation and sequence counters instead. If all operations which affect
4527 * the relationship between the current vnode and the one we are looking for
4528 * also modify the counter, we can verify whether all the conditions held as
4529 * we made the jump. This includes things like permissions, mount points etc.
4530 * Counter modification is provided by enclosing relevant places in
4531 * vn_seqc_write_begin()/end() calls.
4533 * Thus this translates to:
4536 * dvp_seqc = seqc_read_any(dvp);
4537 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
4541 * tvp_seqc = seqc_read_any(tvp);
4542 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
4544 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
4546 * dvp = tvp; // we know nothing of importance has changed
4547 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
4551 * vget(); // secure the vnode
4552 * if (!seqc_consistent(tvp, tvp_seqc) // final check
4554 * // at this point we know nothing has changed for any parent<->child pair
4555 * // as they were crossed during the lookup, meaning we matched the guarantee
4556 * // of the locked variant
4559 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
4560 * - they are called while within vfs_smr protection which they must never exit
4561 * - EAGAIN can be returned to denote checking could not be performed, it is
4562 * always valid to return it
4563 * - if the sequence counter has not changed the result must be valid
4564 * - if the sequence counter has changed both false positives and false negatives
4565 * are permitted (since the result will be rejected later)
4566 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
4568 * Caveats to watch out for:
4569 * - vnodes are passed unlocked and unreferenced with nothing stopping
4570 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
4571 * to use atomic_load_ptr to fetch it.
4572 * - the aforementioned object can also get freed, meaning absent other means it
4573 * should be protected with vfs_smr
4574 * - either safely checking permissions as they are modified or guaranteeing
4575 * their stability is left to the routine
4578 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
4581 struct cache_fpl fpl;
4584 struct componentname *cnp;
4585 struct nameidata_saved orig;
4588 MPASS(ndp->ni_lcf == 0);
4590 fpl.status = CACHE_FPL_STATUS_UNSET;
4592 fpl.cnp = &ndp->ni_cnd;
4593 MPASS(curthread == fpl.cnp->cn_thread);
4595 if ((fpl.cnp->cn_flags & SAVESTART) != 0)
4596 MPASS(fpl.cnp->cn_nameiop != LOOKUP);
4598 if (!cache_can_fplookup(&fpl)) {
4599 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4600 *status = fpl.status;
4601 return (EOPNOTSUPP);
4604 cache_fpl_checkpoint(&fpl, &orig);
4606 cache_fpl_smr_enter_initial(&fpl);
4607 fpl.fsearch = false;
4608 pwd = pwd_get_smr();
4610 ndp->ni_rootdir = pwd->pwd_rdir;
4611 ndp->ni_topdir = pwd->pwd_jdir;
4614 cnp->cn_nameptr = cnp->cn_pnbuf;
4615 if (cnp->cn_pnbuf[0] == '/') {
4616 cache_fpl_handle_root(ndp, &dvp);
4618 if (ndp->ni_dirfd == AT_FDCWD) {
4619 dvp = pwd->pwd_cdir;
4621 error = cache_fplookup_dirfd(&fpl, &dvp);
4622 if (__predict_false(error != 0)) {
4628 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
4630 error = cache_fplookup_impl(dvp, &fpl);
4632 cache_fpl_smr_assert_not_entered(&fpl);
4633 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4635 *status = fpl.status;
4636 switch (fpl.status) {
4637 case CACHE_FPL_STATUS_UNSET:
4638 __assert_unreachable();
4640 case CACHE_FPL_STATUS_HANDLED:
4641 SDT_PROBE3(vfs, namei, lookup, return, error,
4642 (error == 0 ? ndp->ni_vp : NULL), true);
4644 case CACHE_FPL_STATUS_PARTIAL:
4647 * Status restored by cache_fplookup_partial_setup.
4650 case CACHE_FPL_STATUS_ABORTED:
4651 cache_fpl_restore(&fpl, &orig);