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.
133 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
134 "the state must fit in a union with a pointer without growing it");
137 LIST_ENTRY(namecache) nc_src; /* source vnode list */
138 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
139 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
140 struct vnode *nc_dvp; /* vnode of parent of name */
142 struct vnode *nu_vp; /* vnode the name refers to */
143 struct negstate nu_neg;/* negative entry state */
145 u_char nc_flag; /* flag bits */
146 u_char nc_nlen; /* length of name */
147 char nc_name[0]; /* segment name + nul */
151 * struct namecache_ts repeats struct namecache layout up to the
153 * struct namecache_ts is used in place of struct namecache when time(s) need
154 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
155 * both a non-dotdot directory name plus dotdot for the directory's
158 * See below for alignment requirement.
160 struct namecache_ts {
161 struct timespec nc_time; /* timespec provided by fs */
162 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
163 int nc_ticks; /* ticks value when entry was added */
164 struct namecache nc_nc;
168 * At least mips n32 performs 64-bit accesses to timespec as found
169 * in namecache_ts and requires them to be aligned. Since others
170 * may be in the same spot suffer a little bit and enforce the
171 * alignment for everyone. Note this is a nop for 64-bit platforms.
173 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
174 #define CACHE_PATH_CUTOFF 39
176 #define CACHE_ZONE_SMALL_SIZE (sizeof(struct namecache) + CACHE_PATH_CUTOFF + 1)
177 #define CACHE_ZONE_SMALL_TS_SIZE (sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1)
178 #define CACHE_ZONE_LARGE_SIZE (sizeof(struct namecache) + NAME_MAX + 1)
179 #define CACHE_ZONE_LARGE_TS_SIZE (sizeof(struct namecache_ts) + NAME_MAX + 1)
181 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
182 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
183 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
184 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
186 #define nc_vp n_un.nu_vp
187 #define nc_neg n_un.nu_neg
190 * Flags in namecache.nc_flag
192 #define NCF_WHITE 0x01
193 #define NCF_ISDOTDOT 0x02
196 #define NCF_DVDROP 0x10
197 #define NCF_NEGATIVE 0x20
198 #define NCF_INVALID 0x40
202 * Flags in negstate.neg_flag
207 * Mark an entry as invalid.
209 * This is called before it starts getting deconstructed.
212 cache_ncp_invalidate(struct namecache *ncp)
215 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
216 ("%s: entry %p already invalid", __func__, ncp));
217 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
218 atomic_thread_fence_rel();
222 * Check whether the entry can be safely used.
224 * All places which elide locks are supposed to call this after they are
225 * done with reading from an entry.
228 cache_ncp_canuse(struct namecache *ncp)
231 atomic_thread_fence_acq();
232 return ((atomic_load_char(&ncp->nc_flag) & (NCF_INVALID | NCF_WIP)) == 0);
236 * Name caching works as follows:
238 * Names found by directory scans are retained in a cache
239 * for future reference. It is managed LRU, so frequently
240 * used names will hang around. Cache is indexed by hash value
241 * obtained from (dvp, name) where dvp refers to the directory
244 * If it is a "negative" entry, (i.e. for a name that is known NOT to
245 * exist) the vnode pointer will be NULL.
247 * Upon reaching the last segment of a path, if the reference
248 * is for DELETE, or NOCACHE is set (rewrite), and the
249 * name is located in the cache, it will be dropped.
251 * These locks are used (in the order in which they can be taken):
253 * vnodelock mtx vnode lists and v_cache_dd field protection
254 * bucketlock mtx for access to given set of hash buckets
255 * neglist mtx negative entry LRU management
257 * It is legal to take multiple vnodelock and bucketlock locks. The locking
258 * order is lower address first. Both are recursive.
260 * "." lookups are lockless.
262 * ".." and vnode -> name lookups require vnodelock.
264 * name -> vnode lookup requires the relevant bucketlock to be held for reading.
266 * Insertions and removals of entries require involved vnodes and bucketlocks
267 * to be locked to provide safe operation against other threads modifying the
270 * Some lookups result in removal of the found entry (e.g. getting rid of a
271 * negative entry with the intent to create a positive one), which poses a
272 * problem when multiple threads reach the state. Similarly, two different
273 * threads can purge two different vnodes and try to remove the same name.
275 * If the already held vnode lock is lower than the second required lock, we
276 * can just take the other lock. However, in the opposite case, this could
277 * deadlock. As such, this is resolved by trylocking and if that fails unlocking
278 * the first node, locking everything in order and revalidating the state.
283 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
284 "Name cache parameters");
286 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
287 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
288 "Total namecache capacity");
290 u_int ncsizefactor = 2;
291 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
292 "Size factor for namecache");
294 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
295 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
296 "Ratio of negative namecache entries");
299 * Negative entry % of namecahe capacity above which automatic eviction is allowed.
301 * Check cache_neg_evict_cond for details.
303 static u_int ncnegminpct = 3;
305 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
306 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
307 "Negative entry count above which automatic eviction is allowed");
310 * Structures associated with name caching.
312 #define NCHHASH(hash) \
313 (&nchashtbl[(hash) & nchash])
314 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
315 static u_long __read_mostly nchash; /* size of hash table */
316 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
317 "Size of namecache hash table");
318 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
319 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
321 struct nchstats nchstats; /* cache effectiveness statistics */
323 static bool __read_frequently cache_fast_revlookup = true;
324 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
325 &cache_fast_revlookup, 0, "");
327 static u_int __exclusive_cache_line neg_cycle;
330 #define numneglists (ncneghash + 1)
333 struct mtx nl_evict_lock;
334 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
335 TAILQ_HEAD(, namecache) nl_list;
336 TAILQ_HEAD(, namecache) nl_hotlist;
338 } __aligned(CACHE_LINE_SIZE);
340 static struct neglist neglists[numneglists];
342 static inline struct neglist *
343 NCP2NEGLIST(struct namecache *ncp)
346 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
349 static inline struct negstate *
350 NCP2NEGSTATE(struct namecache *ncp)
353 MPASS(ncp->nc_flag & NCF_NEGATIVE);
354 return (&ncp->nc_neg);
357 #define numbucketlocks (ncbuckethash + 1)
358 static u_int __read_mostly ncbuckethash;
359 static struct mtx_padalign __read_mostly *bucketlocks;
360 #define HASH2BUCKETLOCK(hash) \
361 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
363 #define numvnodelocks (ncvnodehash + 1)
364 static u_int __read_mostly ncvnodehash;
365 static struct mtx __read_mostly *vnodelocks;
366 static inline struct mtx *
367 VP2VNODELOCK(struct vnode *vp)
370 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
374 * UMA zones for the VFS cache.
376 * The small cache is used for entries with short names, which are the
377 * most common. The large cache is used for entries which are too big to
378 * fit in the small cache.
380 static uma_zone_t __read_mostly cache_zone_small;
381 static uma_zone_t __read_mostly cache_zone_small_ts;
382 static uma_zone_t __read_mostly cache_zone_large;
383 static uma_zone_t __read_mostly cache_zone_large_ts;
385 static struct namecache *
386 cache_alloc(int len, int ts)
388 struct namecache_ts *ncp_ts;
389 struct namecache *ncp;
391 if (__predict_false(ts)) {
392 if (len <= CACHE_PATH_CUTOFF)
393 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
395 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
396 ncp = &ncp_ts->nc_nc;
398 if (len <= CACHE_PATH_CUTOFF)
399 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
401 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
407 cache_free(struct namecache *ncp)
409 struct namecache_ts *ncp_ts;
412 if ((ncp->nc_flag & NCF_DVDROP) != 0)
414 if (__predict_false(ncp->nc_flag & NCF_TS)) {
415 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
416 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
417 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
419 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
421 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
422 uma_zfree_smr(cache_zone_small, ncp);
424 uma_zfree_smr(cache_zone_large, ncp);
429 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
431 struct namecache_ts *ncp_ts;
433 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
434 (tsp == NULL && ticksp == NULL),
440 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
441 *tsp = ncp_ts->nc_time;
442 *ticksp = ncp_ts->nc_ticks;
446 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
447 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
448 "VFS namecache enabled");
451 /* Export size information to userland */
452 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
453 sizeof(struct namecache), "sizeof(struct namecache)");
456 * The new name cache statistics
458 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
459 "Name cache statistics");
461 #define STATNODE_ULONG(name, varname, descr) \
462 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
463 #define STATNODE_COUNTER(name, varname, descr) \
464 static COUNTER_U64_DEFINE_EARLY(varname); \
465 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
467 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
468 STATNODE_ULONG(count, numcache, "Number of cache entries");
469 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
470 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
471 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
472 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
473 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
474 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
475 STATNODE_COUNTER(posszaps, numposzaps,
476 "Number of cache hits (positive) we do not want to cache");
477 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
478 STATNODE_COUNTER(negzaps, numnegzaps,
479 "Number of cache hits (negative) we do not want to cache");
480 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
481 /* These count for vn_getcwd(), too. */
482 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
483 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
484 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
485 "Number of fullpath search errors (VOP_VPTOCNP failures)");
486 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
487 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
490 * Debug or developer statistics.
492 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
493 "Name cache debugging");
494 #define DEBUGNODE_ULONG(name, varname, descr) \
495 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
496 #define DEBUGNODE_COUNTER(name, varname, descr) \
497 static COUNTER_U64_DEFINE_EARLY(varname); \
498 SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
500 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
501 "Number of successful removals after relocking");
502 static long zap_bucket_fail;
503 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
504 static long zap_bucket_fail2;
505 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
506 static long cache_lock_vnodes_cel_3_failures;
507 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
508 "Number of times 3-way vnode locking failed");
510 static void cache_zap_locked(struct namecache *ncp);
511 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
512 char **freebuf, size_t *buflen);
513 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
514 char **retbuf, size_t *buflen, bool slash_prefixed, size_t addend);
515 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
516 char **retbuf, size_t *buflen);
517 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
518 char **retbuf, size_t *len, bool slash_prefixed, size_t addend);
520 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
523 cache_assert_vlp_locked(struct mtx *vlp)
527 mtx_assert(vlp, MA_OWNED);
531 cache_assert_vnode_locked(struct vnode *vp)
535 vlp = VP2VNODELOCK(vp);
536 cache_assert_vlp_locked(vlp);
540 * TODO: With the value stored we can do better than computing the hash based
541 * on the address. The choice of FNV should also be revisited.
544 cache_prehash(struct vnode *vp)
547 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
551 cache_get_hash(char *name, u_char len, struct vnode *dvp)
554 return (fnv_32_buf(name, len, dvp->v_nchash));
557 static inline struct nchashhead *
558 NCP2BUCKET(struct namecache *ncp)
562 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
563 return (NCHHASH(hash));
566 static inline struct mtx *
567 NCP2BUCKETLOCK(struct namecache *ncp)
571 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
572 return (HASH2BUCKETLOCK(hash));
577 cache_assert_bucket_locked(struct namecache *ncp)
581 blp = NCP2BUCKETLOCK(ncp);
582 mtx_assert(blp, MA_OWNED);
586 cache_assert_bucket_unlocked(struct namecache *ncp)
590 blp = NCP2BUCKETLOCK(ncp);
591 mtx_assert(blp, MA_NOTOWNED);
594 #define cache_assert_bucket_locked(x) do { } while (0)
595 #define cache_assert_bucket_unlocked(x) do { } while (0)
598 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
600 _cache_sort_vnodes(void **p1, void **p2)
604 MPASS(*p1 != NULL || *p2 != NULL);
614 cache_lock_all_buckets(void)
618 for (i = 0; i < numbucketlocks; i++)
619 mtx_lock(&bucketlocks[i]);
623 cache_unlock_all_buckets(void)
627 for (i = 0; i < numbucketlocks; i++)
628 mtx_unlock(&bucketlocks[i]);
632 cache_lock_all_vnodes(void)
636 for (i = 0; i < numvnodelocks; i++)
637 mtx_lock(&vnodelocks[i]);
641 cache_unlock_all_vnodes(void)
645 for (i = 0; i < numvnodelocks; i++)
646 mtx_unlock(&vnodelocks[i]);
650 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
653 cache_sort_vnodes(&vlp1, &vlp2);
656 if (!mtx_trylock(vlp1))
659 if (!mtx_trylock(vlp2)) {
669 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
672 MPASS(vlp1 != NULL || vlp2 != NULL);
682 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
685 MPASS(vlp1 != NULL || vlp2 != NULL);
694 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
696 struct nchstats snap;
698 if (req->oldptr == NULL)
699 return (SYSCTL_OUT(req, 0, sizeof(snap)));
702 snap.ncs_goodhits = counter_u64_fetch(numposhits);
703 snap.ncs_neghits = counter_u64_fetch(numneghits);
704 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
705 counter_u64_fetch(numnegzaps);
706 snap.ncs_miss = counter_u64_fetch(nummisszap) +
707 counter_u64_fetch(nummiss);
709 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
711 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
712 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
713 "VFS cache effectiveness statistics");
716 cache_recalc_neg_min(u_int val)
719 neg_min = (ncsize * val) / 100;
723 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
729 error = sysctl_handle_int(oidp, &val, 0, req);
730 if (error != 0 || req->newptr == NULL)
733 if (val == ncnegminpct)
735 if (val < 0 || val > 99)
738 cache_recalc_neg_min(val);
742 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
743 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
744 "I", "Negative entry \% of namecahe capacity above which automatic eviction is allowed");
748 * Grab an atomic snapshot of the name cache hash chain lengths
750 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
751 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
755 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
757 struct nchashhead *ncpp;
758 struct namecache *ncp;
759 int i, error, n_nchash, *cntbuf;
762 n_nchash = nchash + 1; /* nchash is max index, not count */
763 if (req->oldptr == NULL)
764 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
765 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
766 cache_lock_all_buckets();
767 if (n_nchash != nchash + 1) {
768 cache_unlock_all_buckets();
769 free(cntbuf, M_TEMP);
772 /* Scan hash tables counting entries */
773 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
774 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
776 cache_unlock_all_buckets();
777 for (error = 0, i = 0; i < n_nchash; i++)
778 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
780 free(cntbuf, M_TEMP);
783 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
784 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
785 "nchash chain lengths");
788 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
791 struct nchashhead *ncpp;
792 struct namecache *ncp;
794 int count, maxlength, used, pct;
797 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
799 cache_lock_all_buckets();
800 n_nchash = nchash + 1; /* nchash is max index, not count */
804 /* Scan hash tables for applicable entries */
805 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
807 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
812 if (maxlength < count)
815 n_nchash = nchash + 1;
816 cache_unlock_all_buckets();
817 pct = (used * 100) / (n_nchash / 100);
818 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
821 error = SYSCTL_OUT(req, &used, sizeof(used));
824 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
827 error = SYSCTL_OUT(req, &pct, sizeof(pct));
832 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
833 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
834 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
838 * Negative entries management
840 * Various workloads create plenty of negative entries and barely use them
841 * afterwards. Moreover malicious users can keep performing bogus lookups
842 * adding even more entries. For example "make tinderbox" as of writing this
843 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
846 * As such, a rather aggressive eviction method is needed. The currently
847 * employed method is a placeholder.
849 * Entries are split over numneglists separate lists, each of which is further
850 * split into hot and cold entries. Entries get promoted after getting a hit.
851 * Eviction happens on addition of new entry.
853 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
854 "Name cache negative entry statistics");
856 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
857 "Number of negative cache entries");
859 static COUNTER_U64_DEFINE_EARLY(neg_created);
860 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
861 "Number of created negative entries");
863 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
864 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
865 "Number of evicted negative entries");
867 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
868 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
869 &neg_evict_skipped_empty,
870 "Number of times evicting failed due to lack of entries");
872 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
873 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
874 &neg_evict_skipped_missed,
875 "Number of times evicting failed due to target entry disappearing");
877 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
878 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
879 &neg_evict_skipped_contended,
880 "Number of times evicting failed due to contention");
882 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
883 "Number of cache hits (negative)");
886 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
891 for (i = 0; i < numneglists; i++)
892 out += neglists[i].nl_hotnum;
894 return (SYSCTL_OUT(req, &out, sizeof(out)));
896 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
897 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
898 "Number of hot negative entries");
901 cache_neg_init(struct namecache *ncp)
905 ncp->nc_flag |= NCF_NEGATIVE;
906 ns = NCP2NEGSTATE(ncp);
908 counter_u64_add(neg_created, 1);
912 * Move a negative entry to the hot list.
915 cache_neg_promote(struct namecache *ncp)
920 ns = NCP2NEGSTATE(ncp);
921 nl = NCP2NEGLIST(ncp);
922 mtx_assert(&nl->nl_lock, MA_OWNED);
923 if ((ns->neg_flag & NEG_HOT) == 0) {
924 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
925 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
927 ns->neg_flag |= NEG_HOT;
932 * Move a negative entry to the hot list if it matches the lookup.
934 * We have to take locks, but they may be contended and in the worst
935 * case we may need to go off CPU. We don't want to spin within the
936 * smr section and we can't block with it. Exiting the section means
937 * the found entry could have been evicted. We are going to look it
941 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
942 struct namecache *oncp, uint32_t hash)
944 struct namecache *ncp;
948 nl = NCP2NEGLIST(oncp);
950 mtx_lock(&nl->nl_lock);
952 * For hash iteration.
957 * Avoid all surprises by only succeeding if we got the same entry and
958 * bailing completely otherwise.
959 * XXX There are no provisions to keep the vnode around, meaning we may
960 * end up promoting a negative entry for a *new* vnode and returning
961 * ENOENT on its account. This is the error we want to return anyway
962 * and promotion is harmless.
964 * In particular at this point there can be a new ncp which matches the
965 * search but hashes to a different neglist.
967 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
973 * No match to begin with.
975 if (__predict_false(ncp == NULL)) {
980 * The newly found entry may be something different...
982 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
983 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
988 * ... and not even negative.
990 nc_flag = atomic_load_char(&ncp->nc_flag);
991 if ((nc_flag & NCF_NEGATIVE) == 0) {
995 if (__predict_false(!cache_ncp_canuse(ncp))) {
999 cache_neg_promote(ncp);
1001 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1002 counter_u64_add(numneghits, 1);
1004 mtx_unlock(&nl->nl_lock);
1008 mtx_unlock(&nl->nl_lock);
1013 cache_neg_hit(struct namecache *ncp)
1016 struct negstate *ns;
1018 ns = NCP2NEGSTATE(ncp);
1019 if ((ns->neg_flag & NEG_HOT) != 0)
1021 nl = NCP2NEGLIST(ncp);
1022 mtx_lock(&nl->nl_lock);
1023 cache_neg_promote(ncp);
1024 mtx_unlock(&nl->nl_lock);
1028 cache_neg_insert(struct namecache *ncp)
1032 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1033 cache_assert_bucket_locked(ncp);
1034 nl = NCP2NEGLIST(ncp);
1035 mtx_lock(&nl->nl_lock);
1036 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1037 mtx_unlock(&nl->nl_lock);
1038 atomic_add_long(&numneg, 1);
1042 cache_neg_remove(struct namecache *ncp)
1045 struct negstate *ns;
1047 cache_assert_bucket_locked(ncp);
1048 nl = NCP2NEGLIST(ncp);
1049 ns = NCP2NEGSTATE(ncp);
1050 mtx_lock(&nl->nl_lock);
1051 if ((ns->neg_flag & NEG_HOT) != 0) {
1052 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1055 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1057 mtx_unlock(&nl->nl_lock);
1058 atomic_subtract_long(&numneg, 1);
1061 static struct neglist *
1062 cache_neg_evict_select(void)
1067 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1068 nl = &neglists[c % numneglists];
1069 if (!mtx_trylock(&nl->nl_evict_lock)) {
1070 counter_u64_add(neg_evict_skipped_contended, 1);
1077 cache_neg_evict(void)
1079 struct namecache *ncp, *ncp2;
1081 struct negstate *ns;
1089 nl = cache_neg_evict_select();
1094 mtx_lock(&nl->nl_lock);
1095 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1097 ns = NCP2NEGSTATE(ncp);
1098 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1099 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1101 ns->neg_flag &= ~NEG_HOT;
1103 ncp = TAILQ_FIRST(&nl->nl_list);
1105 counter_u64_add(neg_evict_skipped_empty, 1);
1106 mtx_unlock(&nl->nl_lock);
1107 mtx_unlock(&nl->nl_evict_lock);
1110 ns = NCP2NEGSTATE(ncp);
1111 nlen = ncp->nc_nlen;
1113 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1114 dvlp = VP2VNODELOCK(dvp);
1115 blp = HASH2BUCKETLOCK(hash);
1116 mtx_unlock(&nl->nl_lock);
1117 mtx_unlock(&nl->nl_evict_lock);
1121 * Note that since all locks were dropped above, the entry may be
1122 * gone or reallocated to be something else.
1124 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1125 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1126 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1130 counter_u64_add(neg_evict_skipped_missed, 1);
1134 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1135 MPASS(blp == NCP2BUCKETLOCK(ncp));
1136 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1138 cache_zap_locked(ncp);
1139 counter_u64_add(neg_evicted, 1);
1150 * Maybe evict a negative entry to create more room.
1152 * The ncnegfactor parameter limits what fraction of the total count
1153 * can comprise of negative entries. However, if the cache is just
1154 * warming up this leads to excessive evictions. As such, ncnegminpct
1155 * (recomputed to neg_min) dictates whether the above should be
1158 * Try evicting if the cache is close to full capacity regardless of
1159 * other considerations.
1162 cache_neg_evict_cond(u_long lnumcache)
1166 if (ncsize - 1000 < lnumcache)
1168 lnumneg = atomic_load_long(&numneg);
1169 if (lnumneg < neg_min)
1171 if (lnumneg * ncnegfactor < lnumcache)
1174 return (cache_neg_evict());
1178 * cache_zap_locked():
1180 * Removes a namecache entry from cache, whether it contains an actual
1181 * pointer to a vnode or if it is just a negative cache entry.
1184 cache_zap_locked(struct namecache *ncp)
1186 struct nchashhead *ncpp;
1188 if (!(ncp->nc_flag & NCF_NEGATIVE))
1189 cache_assert_vnode_locked(ncp->nc_vp);
1190 cache_assert_vnode_locked(ncp->nc_dvp);
1191 cache_assert_bucket_locked(ncp);
1193 cache_ncp_invalidate(ncp);
1195 ncpp = NCP2BUCKET(ncp);
1196 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1197 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1198 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
1199 ncp->nc_name, ncp->nc_vp);
1200 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
1201 if (ncp == ncp->nc_vp->v_cache_dd) {
1202 vn_seqc_write_begin_unheld(ncp->nc_vp);
1203 ncp->nc_vp->v_cache_dd = NULL;
1204 vn_seqc_write_end(ncp->nc_vp);
1207 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
1209 cache_neg_remove(ncp);
1211 if (ncp->nc_flag & NCF_ISDOTDOT) {
1212 if (ncp == ncp->nc_dvp->v_cache_dd) {
1213 vn_seqc_write_begin_unheld(ncp->nc_dvp);
1214 ncp->nc_dvp->v_cache_dd = NULL;
1215 vn_seqc_write_end(ncp->nc_dvp);
1218 LIST_REMOVE(ncp, nc_src);
1219 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
1220 ncp->nc_flag |= NCF_DVDROP;
1221 counter_u64_add(numcachehv, -1);
1224 atomic_subtract_long(&numcache, 1);
1228 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1232 MPASS(ncp->nc_dvp == vp);
1233 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1234 cache_assert_vnode_locked(vp);
1236 blp = NCP2BUCKETLOCK(ncp);
1238 cache_zap_locked(ncp);
1243 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1246 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1249 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1250 cache_assert_vnode_locked(vp);
1252 if (ncp->nc_flag & NCF_NEGATIVE) {
1253 if (*vlpp != NULL) {
1257 cache_zap_negative_locked_vnode_kl(ncp, vp);
1261 pvlp = VP2VNODELOCK(vp);
1262 blp = NCP2BUCKETLOCK(ncp);
1263 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1264 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1266 if (*vlpp == vlp1 || *vlpp == vlp2) {
1270 if (*vlpp != NULL) {
1274 cache_sort_vnodes(&vlp1, &vlp2);
1279 if (!mtx_trylock(vlp1))
1285 cache_zap_locked(ncp);
1287 if (to_unlock != NULL)
1288 mtx_unlock(to_unlock);
1295 MPASS(*vlpp == NULL);
1301 * If trylocking failed we can get here. We know enough to take all needed locks
1302 * in the right order and re-lookup the entry.
1305 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1306 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1309 struct namecache *rncp;
1311 cache_assert_bucket_unlocked(ncp);
1313 cache_sort_vnodes(&dvlp, &vlp);
1314 cache_lock_vnodes(dvlp, vlp);
1316 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1317 if (rncp == ncp && rncp->nc_dvp == dvp &&
1318 rncp->nc_nlen == cnp->cn_namelen &&
1319 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1323 cache_zap_locked(rncp);
1325 cache_unlock_vnodes(dvlp, vlp);
1326 counter_u64_add(zap_bucket_relock_success, 1);
1331 cache_unlock_vnodes(dvlp, vlp);
1335 static int __noinline
1336 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1337 uint32_t hash, struct mtx *blp)
1339 struct mtx *dvlp, *vlp;
1342 cache_assert_bucket_locked(ncp);
1344 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1346 if (!(ncp->nc_flag & NCF_NEGATIVE))
1347 vlp = VP2VNODELOCK(ncp->nc_vp);
1348 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1349 cache_zap_locked(ncp);
1351 cache_unlock_vnodes(dvlp, vlp);
1357 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1360 static __noinline int
1361 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1363 struct namecache *ncp;
1365 struct mtx *dvlp, *dvlp2;
1369 if (cnp->cn_namelen == 2 &&
1370 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1371 dvlp = VP2VNODELOCK(dvp);
1375 ncp = dvp->v_cache_dd;
1380 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1383 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1384 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1386 MPASS(dvp->v_cache_dd == NULL);
1392 vn_seqc_write_begin(dvp);
1393 dvp->v_cache_dd = NULL;
1394 vn_seqc_write_end(dvp);
1399 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1403 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1404 blp = HASH2BUCKETLOCK(hash);
1406 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1411 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1412 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1413 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1422 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1423 if (__predict_false(error != 0)) {
1427 counter_u64_add(numposzaps, 1);
1428 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1432 counter_u64_add(nummisszap, 1);
1433 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1437 static int __noinline
1438 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1439 struct timespec *tsp, int *ticksp)
1444 counter_u64_add(dothits, 1);
1445 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1452 * When we lookup "." we still can be asked to lock it
1455 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1456 if (ltype != VOP_ISLOCKED(*vpp)) {
1457 if (ltype == LK_EXCLUSIVE) {
1458 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1459 if (VN_IS_DOOMED((*vpp))) {
1460 /* forced unmount */
1466 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1471 static int __noinline
1472 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1473 struct timespec *tsp, int *ticksp)
1475 struct namecache_ts *ncp_ts;
1476 struct namecache *ncp;
1482 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1484 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1485 cache_remove_cnp(dvp, cnp);
1489 counter_u64_add(dotdothits, 1);
1491 dvlp = VP2VNODELOCK(dvp);
1493 ncp = dvp->v_cache_dd;
1495 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, "..", NULL);
1499 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1500 if (ncp->nc_flag & NCF_NEGATIVE)
1507 goto negative_success;
1508 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1509 cache_out_ts(ncp, tsp, ticksp);
1510 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1511 NCF_DTS && tsp != NULL) {
1512 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1513 *tsp = ncp_ts->nc_dotdottime;
1517 ltype = VOP_ISLOCKED(dvp);
1519 vs = vget_prep(*vpp);
1521 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1522 vn_lock(dvp, ltype | LK_RETRY);
1523 if (VN_IS_DOOMED(dvp)) {
1535 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1536 if (cnp->cn_flags & ISLASTCN) {
1537 counter_u64_add(numnegzaps, 1);
1538 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1545 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1546 cache_out_ts(ncp, tsp, ticksp);
1547 counter_u64_add(numneghits, 1);
1548 whiteout = (ncp->nc_flag & NCF_WHITE);
1552 cnp->cn_flags |= ISWHITEOUT;
1557 * Lookup a name in the name cache
1561 * - dvp: Parent directory in which to search.
1562 * - vpp: Return argument. Will contain desired vnode on cache hit.
1563 * - cnp: Parameters of the name search. The most interesting bits of
1564 * the cn_flags field have the following meanings:
1565 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1567 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1568 * - tsp: Return storage for cache timestamp. On a successful (positive
1569 * or negative) lookup, tsp will be filled with any timespec that
1570 * was stored when this cache entry was created. However, it will
1571 * be clear for "." entries.
1572 * - ticks: Return storage for alternate cache timestamp. On a successful
1573 * (positive or negative) lookup, it will contain the ticks value
1574 * that was current when the cache entry was created, unless cnp
1577 * Either both tsp and ticks have to be provided or neither of them.
1581 * - -1: A positive cache hit. vpp will contain the desired vnode.
1582 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1583 * to a forced unmount. vpp will not be modified. If the entry
1584 * is a whiteout, then the ISWHITEOUT flag will be set in
1586 * - 0: A cache miss. vpp will not be modified.
1590 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1591 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1592 * lock is not recursively acquired.
1594 static int __noinline
1595 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1596 struct timespec *tsp, int *ticksp)
1598 struct namecache *ncp;
1605 MPASS((cnp->cn_flags & (MAKEENTRY | ISDOTDOT)) == MAKEENTRY);
1608 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1609 blp = HASH2BUCKETLOCK(hash);
1612 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1613 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1614 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1618 if (__predict_false(ncp == NULL)) {
1620 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1622 counter_u64_add(nummiss, 1);
1626 if (ncp->nc_flag & NCF_NEGATIVE)
1627 goto negative_success;
1629 counter_u64_add(numposhits, 1);
1631 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1632 cache_out_ts(ncp, tsp, ticksp);
1634 vs = vget_prep(*vpp);
1636 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1643 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1644 if (cnp->cn_flags & ISLASTCN) {
1645 counter_u64_add(numnegzaps, 1);
1646 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1647 if (__predict_false(error != 0)) {
1656 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1657 cache_out_ts(ncp, tsp, ticksp);
1658 counter_u64_add(numneghits, 1);
1659 whiteout = (ncp->nc_flag & NCF_WHITE);
1663 cnp->cn_flags |= ISWHITEOUT;
1668 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1669 struct timespec *tsp, int *ticksp)
1671 struct namecache *ncp;
1672 struct negstate *ns;
1676 bool whiteout, neg_hot;
1679 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
1682 if (__predict_false(!doingcache)) {
1683 cnp->cn_flags &= ~MAKEENTRY;
1688 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1689 if (cnp->cn_namelen == 1)
1690 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1691 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
1692 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
1695 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1697 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1698 cache_remove_cnp(dvp, cnp);
1702 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1705 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1706 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1707 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1711 if (__predict_false(ncp == NULL)) {
1713 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1715 counter_u64_add(nummiss, 1);
1719 nc_flag = atomic_load_char(&ncp->nc_flag);
1720 if (nc_flag & NCF_NEGATIVE)
1721 goto negative_success;
1723 counter_u64_add(numposhits, 1);
1725 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1726 cache_out_ts(ncp, tsp, ticksp);
1728 if (!cache_ncp_canuse(ncp)) {
1733 vs = vget_prep_smr(*vpp);
1735 if (__predict_false(vs == VGET_NONE)) {
1739 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1746 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1747 if (cnp->cn_flags & ISLASTCN) {
1753 cache_out_ts(ncp, tsp, ticksp);
1754 whiteout = (ncp->nc_flag & NCF_WHITE);
1755 ns = NCP2NEGSTATE(ncp);
1756 neg_hot = ((ns->neg_flag & NEG_HOT) != 0);
1757 if (__predict_false(!cache_ncp_canuse(ncp))) {
1763 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
1766 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1767 counter_u64_add(numneghits, 1);
1771 cnp->cn_flags |= ISWHITEOUT;
1774 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
1777 struct celockstate {
1781 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1782 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1785 cache_celockstate_init(struct celockstate *cel)
1788 bzero(cel, sizeof(*cel));
1792 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1795 struct mtx *vlp1, *vlp2;
1797 MPASS(cel->vlp[0] == NULL);
1798 MPASS(cel->vlp[1] == NULL);
1799 MPASS(cel->vlp[2] == NULL);
1801 MPASS(vp != NULL || dvp != NULL);
1803 vlp1 = VP2VNODELOCK(vp);
1804 vlp2 = VP2VNODELOCK(dvp);
1805 cache_sort_vnodes(&vlp1, &vlp2);
1816 cache_unlock_vnodes_cel(struct celockstate *cel)
1819 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
1821 if (cel->vlp[0] != NULL)
1822 mtx_unlock(cel->vlp[0]);
1823 if (cel->vlp[1] != NULL)
1824 mtx_unlock(cel->vlp[1]);
1825 if (cel->vlp[2] != NULL)
1826 mtx_unlock(cel->vlp[2]);
1830 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
1835 cache_assert_vlp_locked(cel->vlp[0]);
1836 cache_assert_vlp_locked(cel->vlp[1]);
1837 MPASS(cel->vlp[2] == NULL);
1840 vlp = VP2VNODELOCK(vp);
1843 if (vlp >= cel->vlp[1]) {
1846 if (mtx_trylock(vlp))
1848 cache_lock_vnodes_cel_3_failures++;
1849 cache_unlock_vnodes_cel(cel);
1850 if (vlp < cel->vlp[0]) {
1852 mtx_lock(cel->vlp[0]);
1853 mtx_lock(cel->vlp[1]);
1855 if (cel->vlp[0] != NULL)
1856 mtx_lock(cel->vlp[0]);
1858 mtx_lock(cel->vlp[1]);
1868 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
1872 MPASS(cel->blp[0] == NULL);
1873 MPASS(cel->blp[1] == NULL);
1875 cache_sort_vnodes(&blp1, &blp2);
1886 cache_unlock_buckets_cel(struct celockstate *cel)
1889 if (cel->blp[0] != NULL)
1890 mtx_unlock(cel->blp[0]);
1891 mtx_unlock(cel->blp[1]);
1895 * Lock part of the cache affected by the insertion.
1897 * This means vnodelocks for dvp, vp and the relevant bucketlock.
1898 * However, insertion can result in removal of an old entry. In this
1899 * case we have an additional vnode and bucketlock pair to lock.
1901 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
1902 * preserving the locking order (smaller address first).
1905 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1908 struct namecache *ncp;
1909 struct mtx *blps[2];
1911 blps[0] = HASH2BUCKETLOCK(hash);
1914 cache_lock_vnodes_cel(cel, dvp, vp);
1915 if (vp == NULL || vp->v_type != VDIR)
1917 ncp = vp->v_cache_dd;
1920 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1922 MPASS(ncp->nc_dvp == vp);
1923 blps[1] = NCP2BUCKETLOCK(ncp);
1924 if (ncp->nc_flag & NCF_NEGATIVE)
1926 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1929 * All vnodes got re-locked. Re-validate the state and if
1930 * nothing changed we are done. Otherwise restart.
1932 if (ncp == vp->v_cache_dd &&
1933 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1934 blps[1] == NCP2BUCKETLOCK(ncp) &&
1935 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1937 cache_unlock_vnodes_cel(cel);
1942 cache_lock_buckets_cel(cel, blps[0], blps[1]);
1946 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1949 struct namecache *ncp;
1950 struct mtx *blps[2];
1952 blps[0] = HASH2BUCKETLOCK(hash);
1955 cache_lock_vnodes_cel(cel, dvp, vp);
1956 ncp = dvp->v_cache_dd;
1959 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1961 MPASS(ncp->nc_dvp == dvp);
1962 blps[1] = NCP2BUCKETLOCK(ncp);
1963 if (ncp->nc_flag & NCF_NEGATIVE)
1965 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1967 if (ncp == dvp->v_cache_dd &&
1968 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1969 blps[1] == NCP2BUCKETLOCK(ncp) &&
1970 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1972 cache_unlock_vnodes_cel(cel);
1977 cache_lock_buckets_cel(cel, blps[0], blps[1]);
1981 cache_enter_unlock(struct celockstate *cel)
1984 cache_unlock_buckets_cel(cel);
1985 cache_unlock_vnodes_cel(cel);
1988 static void __noinline
1989 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
1990 struct componentname *cnp)
1992 struct celockstate cel;
1993 struct namecache *ncp;
1997 if (dvp->v_cache_dd == NULL)
1999 len = cnp->cn_namelen;
2000 cache_celockstate_init(&cel);
2001 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2002 cache_enter_lock_dd(&cel, dvp, vp, hash);
2003 vn_seqc_write_begin(dvp);
2004 ncp = dvp->v_cache_dd;
2005 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2006 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2007 cache_zap_locked(ncp);
2011 dvp->v_cache_dd = NULL;
2012 vn_seqc_write_end(dvp);
2013 cache_enter_unlock(&cel);
2019 * Add an entry to the cache.
2022 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2023 struct timespec *tsp, struct timespec *dtsp)
2025 struct celockstate cel;
2026 struct namecache *ncp, *n2, *ndd;
2027 struct namecache_ts *ncp_ts;
2028 struct nchashhead *ncpp;
2034 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2035 VNPASS(dvp->v_type != VNON, dvp);
2037 VNPASS(!VN_IS_DOOMED(vp), vp);
2038 VNPASS(vp->v_type != VNON, vp);
2042 if (__predict_false(!doingcache))
2047 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2048 if (cnp->cn_namelen == 1)
2050 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2051 cache_enter_dotdot_prep(dvp, vp, cnp);
2052 flag = NCF_ISDOTDOT;
2057 * Avoid blowout in namecache entries.
2060 * 1. filesystems may end up tryng to add an already existing entry
2061 * (for example this can happen after a cache miss during concurrent
2062 * lookup), in which case we will call cache_neg_evict despite not
2064 * 2. the routine may fail to free anything and no provisions are made
2065 * to make it try harder (see the inside for failure modes)
2066 * 3. it only ever looks at negative entries.
2068 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
2069 if (cache_neg_evict_cond(lnumcache)) {
2070 lnumcache = atomic_load_long(&numcache);
2072 if (__predict_false(lnumcache >= ncsize)) {
2073 atomic_subtract_long(&numcache, 1);
2074 counter_u64_add(numdrops, 1);
2078 cache_celockstate_init(&cel);
2083 * Calculate the hash key and setup as much of the new
2084 * namecache entry as possible before acquiring the lock.
2086 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2087 ncp->nc_flag = flag | NCF_WIP;
2090 cache_neg_init(ncp);
2093 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2094 ncp_ts->nc_time = *tsp;
2095 ncp_ts->nc_ticks = ticks;
2096 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2098 ncp_ts->nc_dotdottime = *dtsp;
2099 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2102 len = ncp->nc_nlen = cnp->cn_namelen;
2103 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2104 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2105 ncp->nc_name[len] = '\0';
2106 cache_enter_lock(&cel, dvp, vp, hash);
2109 * See if this vnode or negative entry is already in the cache
2110 * with this name. This can happen with concurrent lookups of
2111 * the same path name.
2113 ncpp = NCHHASH(hash);
2114 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2115 if (n2->nc_dvp == dvp &&
2116 n2->nc_nlen == cnp->cn_namelen &&
2117 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2118 MPASS(cache_ncp_canuse(n2));
2119 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2121 ("%s: found entry pointing to a different vnode (%p != %p)",
2122 __func__, NULL, vp));
2124 KASSERT(n2->nc_vp == vp,
2125 ("%s: found entry pointing to a different vnode (%p != %p)",
2126 __func__, n2->nc_vp, vp));
2128 * Entries are supposed to be immutable unless in the
2129 * process of getting destroyed. Accommodating for
2130 * changing timestamps is possible but not worth it.
2131 * This should be harmless in terms of correctness, in
2132 * the worst case resulting in an earlier expiration.
2133 * Alternatively, the found entry can be replaced
2136 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2139 KASSERT((n2->nc_flag & NCF_TS) != 0,
2141 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2142 n2_ts->nc_time = ncp_ts->nc_time;
2143 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2145 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2146 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2150 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2152 goto out_unlock_free;
2156 if (flag == NCF_ISDOTDOT) {
2158 * See if we are trying to add .. entry, but some other lookup
2159 * has populated v_cache_dd pointer already.
2161 if (dvp->v_cache_dd != NULL)
2162 goto out_unlock_free;
2163 KASSERT(vp == NULL || vp->v_type == VDIR,
2164 ("wrong vnode type %p", vp));
2165 vn_seqc_write_begin(dvp);
2166 dvp->v_cache_dd = ncp;
2167 vn_seqc_write_end(dvp);
2171 if (flag != NCF_ISDOTDOT) {
2173 * For this case, the cache entry maps both the
2174 * directory name in it and the name ".." for the
2175 * directory's parent.
2177 vn_seqc_write_begin(vp);
2178 if ((ndd = vp->v_cache_dd) != NULL) {
2179 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2180 cache_zap_locked(ndd);
2184 vp->v_cache_dd = ncp;
2185 vn_seqc_write_end(vp);
2186 } else if (vp->v_type != VDIR) {
2187 if (vp->v_cache_dd != NULL) {
2188 vn_seqc_write_begin(vp);
2189 vp->v_cache_dd = NULL;
2190 vn_seqc_write_end(vp);
2195 if (flag != NCF_ISDOTDOT) {
2196 if (LIST_EMPTY(&dvp->v_cache_src)) {
2198 counter_u64_add(numcachehv, 1);
2200 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2204 * If the entry is "negative", we place it into the
2205 * "negative" cache queue, otherwise, we place it into the
2206 * destination vnode's cache entries queue.
2209 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2210 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2213 if (cnp->cn_flags & ISWHITEOUT)
2214 ncp->nc_flag |= NCF_WHITE;
2215 cache_neg_insert(ncp);
2216 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2221 * Insert the new namecache entry into the appropriate chain
2222 * within the cache entries table.
2224 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2226 atomic_thread_fence_rel();
2228 * Mark the entry as fully constructed.
2229 * It is immutable past this point until its removal.
2231 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2233 cache_enter_unlock(&cel);
2238 cache_enter_unlock(&cel);
2239 atomic_subtract_long(&numcache, 1);
2245 cache_roundup_2(u_int val)
2249 for (res = 1; res <= val; res <<= 1)
2255 static struct nchashhead *
2256 nchinittbl(u_long elements, u_long *hashmask)
2258 struct nchashhead *hashtbl;
2261 hashsize = cache_roundup_2(elements) / 2;
2263 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2264 for (i = 0; i < hashsize; i++)
2265 CK_SLIST_INIT(&hashtbl[i]);
2266 *hashmask = hashsize - 1;
2271 ncfreetbl(struct nchashhead *hashtbl)
2274 free(hashtbl, M_VFSCACHE);
2278 * Name cache initialization, from vfs_init() when we are booting
2281 nchinit(void *dummy __unused)
2285 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2286 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2287 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2288 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2289 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2290 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2291 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2292 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2294 VFS_SMR_ZONE_SET(cache_zone_small);
2295 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2296 VFS_SMR_ZONE_SET(cache_zone_large);
2297 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2299 ncsize = desiredvnodes * ncsizefactor;
2300 cache_recalc_neg_min(ncnegminpct);
2301 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2302 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2303 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2305 if (ncbuckethash > nchash)
2306 ncbuckethash = nchash;
2307 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2309 for (i = 0; i < numbucketlocks; i++)
2310 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2311 ncvnodehash = ncbuckethash;
2312 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2314 for (i = 0; i < numvnodelocks; i++)
2315 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2317 for (i = 0; i < numneglists; i++) {
2318 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2319 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2320 TAILQ_INIT(&neglists[i].nl_list);
2321 TAILQ_INIT(&neglists[i].nl_hotlist);
2324 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2327 cache_vnode_init(struct vnode *vp)
2330 LIST_INIT(&vp->v_cache_src);
2331 TAILQ_INIT(&vp->v_cache_dst);
2332 vp->v_cache_dd = NULL;
2337 cache_changesize(u_long newmaxvnodes)
2339 struct nchashhead *new_nchashtbl, *old_nchashtbl;
2340 u_long new_nchash, old_nchash;
2341 struct namecache *ncp;
2346 newncsize = newmaxvnodes * ncsizefactor;
2347 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2348 if (newmaxvnodes < numbucketlocks)
2349 newmaxvnodes = numbucketlocks;
2351 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2352 /* If same hash table size, nothing to do */
2353 if (nchash == new_nchash) {
2354 ncfreetbl(new_nchashtbl);
2358 * Move everything from the old hash table to the new table.
2359 * None of the namecache entries in the table can be removed
2360 * because to do so, they have to be removed from the hash table.
2362 cache_lock_all_vnodes();
2363 cache_lock_all_buckets();
2364 old_nchashtbl = nchashtbl;
2365 old_nchash = nchash;
2366 nchashtbl = new_nchashtbl;
2367 nchash = new_nchash;
2368 for (i = 0; i <= old_nchash; i++) {
2369 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2370 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2372 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2373 CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2377 cache_recalc_neg_min(ncnegminpct);
2378 cache_unlock_all_buckets();
2379 cache_unlock_all_vnodes();
2380 ncfreetbl(old_nchashtbl);
2384 * Invalidate all entries from and to a particular vnode.
2387 cache_purge_impl(struct vnode *vp)
2389 TAILQ_HEAD(, namecache) ncps;
2390 struct namecache *ncp, *nnp;
2391 struct mtx *vlp, *vlp2;
2394 vlp = VP2VNODELOCK(vp);
2398 while (!LIST_EMPTY(&vp->v_cache_src)) {
2399 ncp = LIST_FIRST(&vp->v_cache_src);
2400 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2402 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2404 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2405 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2406 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2408 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2410 ncp = vp->v_cache_dd;
2412 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2413 ("lost dotdot link"));
2414 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2416 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2418 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2422 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2428 * Opportunistic check to see if there is anything to do.
2431 cache_has_entries(struct vnode *vp)
2434 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2435 vp->v_cache_dd == NULL)
2441 cache_purge(struct vnode *vp)
2444 SDT_PROBE1(vfs, namecache, purge, done, vp);
2445 if (!cache_has_entries(vp))
2447 cache_purge_impl(vp);
2451 * Only to be used by vgone.
2454 cache_purge_vgone(struct vnode *vp)
2458 VNPASS(VN_IS_DOOMED(vp), vp);
2459 if (cache_has_entries(vp)) {
2460 cache_purge_impl(vp);
2465 * Serialize against a potential thread doing cache_purge.
2467 vlp = VP2VNODELOCK(vp);
2468 mtx_wait_unlocked(vlp);
2469 if (cache_has_entries(vp)) {
2470 cache_purge_impl(vp);
2477 * Invalidate all negative entries for a particular directory vnode.
2480 cache_purge_negative(struct vnode *vp)
2482 TAILQ_HEAD(, namecache) ncps;
2483 struct namecache *ncp, *nnp;
2486 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2487 if (LIST_EMPTY(&vp->v_cache_src))
2490 vlp = VP2VNODELOCK(vp);
2492 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2493 if (!(ncp->nc_flag & NCF_NEGATIVE))
2495 cache_zap_negative_locked_vnode_kl(ncp, vp);
2496 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2499 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2505 cache_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2506 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2509 ASSERT_VOP_IN_SEQC(fdvp);
2510 ASSERT_VOP_IN_SEQC(fvp);
2511 ASSERT_VOP_IN_SEQC(tdvp);
2513 ASSERT_VOP_IN_SEQC(tvp);
2518 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2519 ("%s: lingering negative entry", __func__));
2521 cache_remove_cnp(tdvp, tcnp);
2526 * Flush all entries referencing a particular filesystem.
2529 cache_purgevfs(struct mount *mp)
2531 struct vnode *vp, *mvp;
2533 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2535 * Somewhat wasteful iteration over all vnodes. Would be better to
2536 * support filtering and avoid the interlock to begin with.
2538 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2539 if (!cache_has_entries(vp)) {
2551 * Perform canonical checks and cache lookup and pass on to filesystem
2552 * through the vop_cachedlookup only if needed.
2556 vfs_cache_lookup(struct vop_lookup_args *ap)
2560 struct vnode **vpp = ap->a_vpp;
2561 struct componentname *cnp = ap->a_cnp;
2562 int flags = cnp->cn_flags;
2567 if (dvp->v_type != VDIR)
2570 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2571 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2574 error = vn_dir_check_exec(dvp, cnp);
2578 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2580 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2586 /* Implementation of the getcwd syscall. */
2588 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2594 buflen = uap->buflen;
2595 if (__predict_false(buflen < 2))
2597 if (buflen > MAXPATHLEN)
2598 buflen = MAXPATHLEN;
2600 buf = uma_zalloc(namei_zone, M_WAITOK);
2601 error = vn_getcwd(buf, &retbuf, &buflen);
2603 error = copyout(retbuf, uap->buf, buflen);
2604 uma_zfree(namei_zone, buf);
2609 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
2615 pwd = pwd_get_smr();
2616 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
2618 VFS_SMR_ASSERT_NOT_ENTERED();
2620 pwd = pwd_hold(curthread);
2621 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
2627 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2634 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2635 size_t size, int flags, enum uio_seg pathseg)
2637 struct nameidata nd;
2638 char *retbuf, *freebuf;
2643 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2644 pathseg, path, fd, &cap_fstat_rights, td);
2645 if ((error = namei(&nd)) != 0)
2647 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
2649 error = copyout(retbuf, buf, size);
2650 free(freebuf, M_TEMP);
2657 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2660 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2661 uap->flags, UIO_USERSPACE));
2665 * Retrieve the full filesystem path that correspond to a vnode from the name
2666 * cache (if available)
2669 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
2676 if (__predict_false(vp == NULL))
2679 buflen = MAXPATHLEN;
2680 buf = malloc(buflen, M_TEMP, M_WAITOK);
2682 pwd = pwd_get_smr();
2683 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, false, 0);
2684 VFS_SMR_ASSERT_NOT_ENTERED();
2686 pwd = pwd_hold(curthread);
2687 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
2698 * This function is similar to vn_fullpath, but it attempts to lookup the
2699 * pathname relative to the global root mount point. This is required for the
2700 * auditing sub-system, as audited pathnames must be absolute, relative to the
2701 * global root mount point.
2704 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
2710 if (__predict_false(vp == NULL))
2712 buflen = MAXPATHLEN;
2713 buf = malloc(buflen, M_TEMP, M_WAITOK);
2715 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, false, 0);
2716 VFS_SMR_ASSERT_NOT_ENTERED();
2718 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
2727 static struct namecache *
2728 vn_dd_from_dst(struct vnode *vp)
2730 struct namecache *ncp;
2732 cache_assert_vnode_locked(vp);
2733 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
2734 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2741 vn_vptocnp(struct vnode **vp, struct ucred *cred, char *buf, size_t *buflen)
2744 struct namecache *ncp;
2748 vlp = VP2VNODELOCK(*vp);
2750 ncp = (*vp)->v_cache_dd;
2751 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
2752 KASSERT(ncp == vn_dd_from_dst(*vp),
2753 ("%s: mismatch for dd entry (%p != %p)", __func__,
2754 ncp, vn_dd_from_dst(*vp)));
2756 ncp = vn_dd_from_dst(*vp);
2759 if (*buflen < ncp->nc_nlen) {
2762 counter_u64_add(numfullpathfail4, 1);
2764 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2768 *buflen -= ncp->nc_nlen;
2769 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2770 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2779 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2782 vn_lock(*vp, LK_SHARED | LK_RETRY);
2783 error = VOP_VPTOCNP(*vp, &dvp, cred, buf, buflen);
2786 counter_u64_add(numfullpathfail2, 1);
2787 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2792 if (VN_IS_DOOMED(dvp)) {
2793 /* forced unmount */
2796 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2800 * *vp has its use count incremented still.
2807 * Resolve a directory to a pathname.
2809 * The name of the directory can always be found in the namecache or fetched
2810 * from the filesystem. There is also guaranteed to be only one parent, meaning
2811 * we can just follow vnodes up until we find the root.
2813 * The vnode must be referenced.
2816 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
2817 size_t *len, bool slash_prefixed, size_t addend)
2819 #ifdef KDTRACE_HOOKS
2820 struct vnode *startvp = vp;
2826 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
2827 VNPASS(vp->v_usecount > 0, vp);
2831 if (!slash_prefixed) {
2839 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
2840 counter_u64_add(numfullpathcalls, 1);
2841 while (vp != rdir && vp != rootvnode) {
2843 * The vp vnode must be already fully constructed,
2844 * since it is either found in namecache or obtained
2845 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
2846 * without obtaining the vnode lock.
2848 if ((vp->v_vflag & VV_ROOT) != 0) {
2849 vn_lock(vp, LK_RETRY | LK_SHARED);
2852 * With the vnode locked, check for races with
2853 * unmount, forced or not. Note that we
2854 * already verified that vp is not equal to
2855 * the root vnode, which means that
2856 * mnt_vnodecovered can be NULL only for the
2859 if (VN_IS_DOOMED(vp) ||
2860 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
2861 vp1->v_mountedhere != vp->v_mount) {
2864 SDT_PROBE3(vfs, namecache, fullpath, return,
2874 if (vp->v_type != VDIR) {
2876 counter_u64_add(numfullpathfail1, 1);
2878 SDT_PROBE3(vfs, namecache, fullpath, return,
2882 error = vn_vptocnp(&vp, curthread->td_ucred, buf, &buflen);
2888 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2892 buf[--buflen] = '/';
2893 slash_prefixed = true;
2897 if (!slash_prefixed) {
2900 counter_u64_add(numfullpathfail4, 1);
2901 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
2905 buf[--buflen] = '/';
2907 counter_u64_add(numfullpathfound, 1);
2910 *retbuf = buf + buflen;
2911 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
2918 * Resolve an arbitrary vnode to a pathname.
2921 * - hardlinks are not tracked, thus if the vnode is not a directory this can
2922 * resolve to a different path than the one used to find it
2923 * - namecache is not mandatory, meaning names are not guaranteed to be added
2924 * (in which case resolving fails)
2926 static void __inline
2927 cache_rev_failed_impl(int *reason, int line)
2932 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
2935 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
2936 char **retbuf, size_t *buflen, bool slash_prefixed, size_t addend)
2938 #ifdef KDTRACE_HOOKS
2939 struct vnode *startvp = vp;
2943 struct namecache *ncp;
2947 #ifdef KDTRACE_HOOKS
2950 seqc_t vp_seqc, tvp_seqc;
2953 VFS_SMR_ASSERT_ENTERED();
2955 if (!cache_fast_revlookup) {
2960 orig_buflen = *buflen;
2962 if (!slash_prefixed) {
2963 MPASS(*buflen >= 2);
2965 buf[*buflen] = '\0';
2968 if (vp == rdir || vp == rootvnode) {
2969 if (!slash_prefixed) {
2976 #ifdef KDTRACE_HOOKS
2980 ncp = NULL; /* for sdt probe down below */
2981 vp_seqc = vn_seqc_read_any(vp);
2982 if (seqc_in_modify(vp_seqc)) {
2983 cache_rev_failed(&reason);
2988 #ifdef KDTRACE_HOOKS
2991 if ((vp->v_vflag & VV_ROOT) != 0) {
2992 mp = atomic_load_ptr(&vp->v_mount);
2994 cache_rev_failed(&reason);
2997 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
2998 tvp_seqc = vn_seqc_read_any(tvp);
2999 if (seqc_in_modify(tvp_seqc)) {
3000 cache_rev_failed(&reason);
3003 if (!vn_seqc_consistent(vp, vp_seqc)) {
3004 cache_rev_failed(&reason);
3011 ncp = atomic_load_ptr(&vp->v_cache_dd);
3013 cache_rev_failed(&reason);
3016 nc_flag = atomic_load_char(&ncp->nc_flag);
3017 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3018 cache_rev_failed(&reason);
3021 if (!cache_ncp_canuse(ncp)) {
3022 cache_rev_failed(&reason);
3025 if (ncp->nc_nlen >= *buflen) {
3026 cache_rev_failed(&reason);
3030 *buflen -= ncp->nc_nlen;
3031 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3035 tvp_seqc = vn_seqc_read_any(tvp);
3036 if (seqc_in_modify(tvp_seqc)) {
3037 cache_rev_failed(&reason);
3040 if (!vn_seqc_consistent(vp, vp_seqc)) {
3041 cache_rev_failed(&reason);
3046 if (vp == rdir || vp == rootvnode)
3051 *retbuf = buf + *buflen;
3052 *buflen = orig_buflen - *buflen + addend;
3053 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3057 *buflen = orig_buflen;
3058 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3064 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3068 bool slash_prefixed;
3074 orig_buflen = *buflen;
3077 slash_prefixed = false;
3078 if (vp->v_type != VDIR) {
3080 buf[*buflen] = '\0';
3081 error = vn_vptocnp(&vp, curthread->td_ucred, buf, buflen);
3090 slash_prefixed = true;
3093 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, slash_prefixed,
3094 orig_buflen - *buflen));
3098 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3100 * Since the namecache does not track handlings, the caller is expected to first
3101 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3103 * Then we have 2 cases:
3104 * - if the found vnode is a directory, the path can be constructed just by
3105 * fullowing names up the chain
3106 * - otherwise we populate the buffer with the saved name and start resolving
3110 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3115 struct componentname *cnp;
3119 bool slash_prefixed;
3124 if (*buflen > MAXPATHLEN)
3125 *buflen = MAXPATHLEN;
3127 slash_prefixed = false;
3129 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3134 * Check for VBAD to work around the vp_crossmp bug in lookup().
3136 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3137 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3138 * If the type is VDIR (like in this very case) we can skip looking
3139 * at ni_dvp in the first place. However, since vnodes get passed here
3140 * unlocked the target may transition to doomed state (type == VBAD)
3141 * before we get to evaluate the condition. If this happens, we will
3142 * populate part of the buffer and descend to vn_fullpath_dir with
3143 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3145 * This should be atomic_load(&vp->v_type) but it is ilegal to take
3146 * an address of a bit field, even if said field is sized to char.
3147 * Work around the problem by reading the value into a full-sized enum
3148 * and then re-reading it with atomic_load which will still prevent
3149 * the compiler from re-reading down the road.
3152 type = atomic_load_int(&type);
3159 addend = cnp->cn_namelen + 2;
3160 if (*buflen < addend) {
3165 tmpbuf = buf + *buflen;
3167 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3168 tmpbuf[addend - 1] = '\0';
3169 slash_prefixed = true;
3174 pwd = pwd_get_smr();
3175 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3176 slash_prefixed, addend);
3177 VFS_SMR_ASSERT_NOT_ENTERED();
3179 pwd = pwd_hold(curthread);
3181 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3182 slash_prefixed, addend);
3197 vn_dir_dd_ino(struct vnode *vp)
3199 struct namecache *ncp;
3204 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3205 vlp = VP2VNODELOCK(vp);
3207 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3208 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3211 vs = vget_prep(ddvp);
3213 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3222 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3224 struct namecache *ncp;
3228 vlp = VP2VNODELOCK(vp);
3230 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3231 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3237 l = min(ncp->nc_nlen, buflen - 1);
3238 memcpy(buf, ncp->nc_name, l);
3245 * This function updates path string to vnode's full global path
3246 * and checks the size of the new path string against the pathlen argument.
3248 * Requires a locked, referenced vnode.
3249 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3251 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3252 * because it falls back to the ".." lookup if the namecache lookup fails.
3255 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3258 struct nameidata nd;
3263 ASSERT_VOP_ELOCKED(vp, __func__);
3265 /* Construct global filesystem path from vp. */
3267 error = vn_fullpath_global(vp, &rpath, &fbuf);
3274 if (strlen(rpath) >= pathlen) {
3276 error = ENAMETOOLONG;
3281 * Re-lookup the vnode by path to detect a possible rename.
3282 * As a side effect, the vnode is relocked.
3283 * If vnode was renamed, return ENOENT.
3285 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3286 UIO_SYSSPACE, path, td);
3292 NDFREE(&nd, NDF_ONLY_PNBUF);
3296 strcpy(path, rpath);
3309 db_print_vpath(struct vnode *vp)
3312 while (vp != NULL) {
3313 db_printf("%p: ", vp);
3314 if (vp == rootvnode) {
3318 if (vp->v_vflag & VV_ROOT) {
3319 db_printf("<mount point>");
3320 vp = vp->v_mount->mnt_vnodecovered;
3322 struct namecache *ncp;
3326 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3329 for (i = 0; i < ncp->nc_nlen; i++)
3330 db_printf("%c", *ncn++);
3343 DB_SHOW_COMMAND(vpath, db_show_vpath)
3348 db_printf("usage: show vpath <struct vnode *>\n");
3352 vp = (struct vnode *)addr;
3358 static bool __read_frequently cache_fast_lookup = true;
3359 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_lookup, CTLFLAG_RW,
3360 &cache_fast_lookup, 0, "");
3362 #define CACHE_FPL_FAILED -2020
3365 cache_fpl_cleanup_cnp(struct componentname *cnp)
3368 uma_zfree(namei_zone, cnp->cn_pnbuf);
3370 cnp->cn_pnbuf = NULL;
3371 cnp->cn_nameptr = NULL;
3376 cache_fpl_handle_root(struct nameidata *ndp, struct vnode **dpp)
3378 struct componentname *cnp;
3381 while (*(cnp->cn_nameptr) == '/') {
3386 *dpp = ndp->ni_rootdir;
3390 * Components of nameidata (or objects it can point to) which may
3391 * need restoring in case fast path lookup fails.
3393 struct nameidata_saved {
3401 struct nameidata *ndp;
3402 struct componentname *cnp;
3408 struct nameidata_saved snd;
3410 enum cache_fpl_status status:8;
3416 cache_fpl_checkpoint(struct cache_fpl *fpl, struct nameidata_saved *snd)
3419 snd->cn_flags = fpl->ndp->ni_cnd.cn_flags;
3420 snd->cn_namelen = fpl->ndp->ni_cnd.cn_namelen;
3421 snd->cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3422 snd->ni_pathlen = fpl->ndp->ni_pathlen;
3426 cache_fpl_restore(struct cache_fpl *fpl, struct nameidata_saved *snd)
3429 fpl->ndp->ni_cnd.cn_flags = snd->cn_flags;
3430 fpl->ndp->ni_cnd.cn_namelen = snd->cn_namelen;
3431 fpl->ndp->ni_cnd.cn_nameptr = snd->cn_nameptr;
3432 fpl->ndp->ni_pathlen = snd->ni_pathlen;
3436 #define cache_fpl_smr_assert_entered(fpl) ({ \
3437 struct cache_fpl *_fpl = (fpl); \
3438 MPASS(_fpl->in_smr == true); \
3439 VFS_SMR_ASSERT_ENTERED(); \
3441 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
3442 struct cache_fpl *_fpl = (fpl); \
3443 MPASS(_fpl->in_smr == false); \
3444 VFS_SMR_ASSERT_NOT_ENTERED(); \
3447 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3448 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3451 #define cache_fpl_smr_enter_initial(fpl) ({ \
3452 struct cache_fpl *_fpl = (fpl); \
3454 _fpl->in_smr = true; \
3457 #define cache_fpl_smr_enter(fpl) ({ \
3458 struct cache_fpl *_fpl = (fpl); \
3459 MPASS(_fpl->in_smr == false); \
3461 _fpl->in_smr = true; \
3464 #define cache_fpl_smr_exit(fpl) ({ \
3465 struct cache_fpl *_fpl = (fpl); \
3466 MPASS(_fpl->in_smr == true); \
3468 _fpl->in_smr = false; \
3472 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3475 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3476 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3477 ("%s: converting to abort from %d at %d, set at %d\n",
3478 __func__, fpl->status, line, fpl->line));
3480 fpl->status = CACHE_FPL_STATUS_ABORTED;
3482 return (CACHE_FPL_FAILED);
3485 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
3488 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3491 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3492 ("%s: setting to partial at %d, but already set to %d at %d\n",
3493 __func__, line, fpl->status, fpl->line));
3494 cache_fpl_smr_assert_entered(fpl);
3495 fpl->status = CACHE_FPL_STATUS_PARTIAL;
3497 return (CACHE_FPL_FAILED);
3500 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
3503 cache_fpl_handled_impl(struct cache_fpl *fpl, int error, int line)
3506 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3507 ("%s: setting to handled at %d, but already set to %d at %d\n",
3508 __func__, line, fpl->status, fpl->line));
3509 cache_fpl_smr_assert_not_entered(fpl);
3510 MPASS(error != CACHE_FPL_FAILED);
3511 fpl->status = CACHE_FPL_STATUS_HANDLED;
3516 #define cache_fpl_handled(x, e) cache_fpl_handled_impl((x), (e), __LINE__)
3518 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3519 (LOCKLEAF | LOCKPARENT | WANTPARENT | NOCACHE | FOLLOW | LOCKSHARED | SAVENAME | \
3520 SAVESTART | WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
3522 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3523 (ISDOTDOT | MAKEENTRY | ISLASTCN)
3525 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3526 "supported and internal flags overlap");
3529 cache_fpl_islastcn(struct nameidata *ndp)
3532 return (*ndp->ni_next == 0);
3536 cache_fpl_isdotdot(struct componentname *cnp)
3539 if (cnp->cn_namelen == 2 &&
3540 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3546 cache_can_fplookup(struct cache_fpl *fpl)
3548 struct nameidata *ndp;
3549 struct componentname *cnp;
3554 td = cnp->cn_thread;
3556 if (!cache_fast_lookup) {
3557 cache_fpl_aborted(fpl);
3561 if (mac_vnode_check_lookup_enabled()) {
3562 cache_fpl_aborted(fpl);
3566 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3567 cache_fpl_aborted(fpl);
3570 if (IN_CAPABILITY_MODE(td)) {
3571 cache_fpl_aborted(fpl);
3574 if (AUDITING_TD(td)) {
3575 cache_fpl_aborted(fpl);
3578 if (ndp->ni_startdir != NULL) {
3579 cache_fpl_aborted(fpl);
3586 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
3588 struct nameidata *ndp;
3593 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
3594 if (__predict_false(error != 0)) {
3595 cache_fpl_smr_exit(fpl);
3596 return (cache_fpl_aborted(fpl));
3598 fpl->fsearch = fsearch;
3603 cache_fplookup_vnode_supported(struct vnode *vp)
3606 return (vp->v_type != VLNK);
3609 static int __noinline
3610 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
3613 struct componentname *cnp;
3619 cache_fpl_smr_exit(fpl);
3620 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
3621 return (cache_fpl_handled(fpl, ENOENT));
3623 return (cache_fpl_aborted(fpl));
3627 * The target vnode is not supported, prepare for the slow path to take over.
3629 static int __noinline
3630 cache_fplookup_partial_setup(struct cache_fpl *fpl)
3632 struct nameidata *ndp;
3633 struct componentname *cnp;
3643 dvp_seqc = fpl->dvp_seqc;
3645 if (!pwd_hold_smr(pwd)) {
3646 cache_fpl_smr_exit(fpl);
3647 return (cache_fpl_aborted(fpl));
3650 dvs = vget_prep_smr(dvp);
3651 cache_fpl_smr_exit(fpl);
3652 if (__predict_false(dvs == VGET_NONE)) {
3654 return (cache_fpl_aborted(fpl));
3657 vget_finish_ref(dvp, dvs);
3658 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3661 return (cache_fpl_aborted(fpl));
3664 cache_fpl_restore(fpl, &fpl->snd);
3666 ndp->ni_startdir = dvp;
3667 cnp->cn_flags |= MAKEENTRY;
3668 if (cache_fpl_islastcn(ndp))
3669 cnp->cn_flags |= ISLASTCN;
3670 if (cache_fpl_isdotdot(cnp))
3671 cnp->cn_flags |= ISDOTDOT;
3677 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
3679 struct componentname *cnp;
3686 tvp_seqc = fpl->tvp_seqc;
3688 if ((cnp->cn_flags & LOCKLEAF) != 0) {
3689 lkflags = LK_SHARED;
3690 if ((cnp->cn_flags & LOCKSHARED) == 0)
3691 lkflags = LK_EXCLUSIVE;
3692 error = vget_finish(tvp, lkflags, tvs);
3693 if (__predict_false(error != 0)) {
3694 return (cache_fpl_aborted(fpl));
3697 vget_finish_ref(tvp, tvs);
3700 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
3701 if ((cnp->cn_flags & LOCKLEAF) != 0)
3705 return (cache_fpl_aborted(fpl));
3708 return (cache_fpl_handled(fpl, 0));
3712 * They want to possibly modify the state of the namecache.
3714 * Don't try to match the API contract, just leave.
3715 * TODO: this leaves scalability on the table
3718 cache_fplookup_final_modifying(struct cache_fpl *fpl)
3720 struct componentname *cnp;
3723 MPASS(cnp->cn_nameiop != LOOKUP);
3724 return (cache_fpl_partial(fpl));
3727 static int __noinline
3728 cache_fplookup_final_withparent(struct cache_fpl *fpl)
3730 struct componentname *cnp;
3731 enum vgetstate dvs, tvs;
3732 struct vnode *dvp, *tvp;
3738 dvp_seqc = fpl->dvp_seqc;
3741 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
3744 * This is less efficient than it can be for simplicity.
3746 dvs = vget_prep_smr(dvp);
3747 if (__predict_false(dvs == VGET_NONE)) {
3748 return (cache_fpl_aborted(fpl));
3750 tvs = vget_prep_smr(tvp);
3751 if (__predict_false(tvs == VGET_NONE)) {
3752 cache_fpl_smr_exit(fpl);
3753 vget_abort(dvp, dvs);
3754 return (cache_fpl_aborted(fpl));
3757 cache_fpl_smr_exit(fpl);
3759 if ((cnp->cn_flags & LOCKPARENT) != 0) {
3760 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
3761 if (__predict_false(error != 0)) {
3762 vget_abort(tvp, tvs);
3763 return (cache_fpl_aborted(fpl));
3766 vget_finish_ref(dvp, dvs);
3769 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3770 vget_abort(tvp, tvs);
3771 if ((cnp->cn_flags & LOCKPARENT) != 0)
3775 return (cache_fpl_aborted(fpl));
3778 error = cache_fplookup_final_child(fpl, tvs);
3779 if (__predict_false(error != 0)) {
3780 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
3781 if ((cnp->cn_flags & LOCKPARENT) != 0)
3788 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
3793 cache_fplookup_final(struct cache_fpl *fpl)
3795 struct componentname *cnp;
3797 struct vnode *dvp, *tvp;
3802 dvp_seqc = fpl->dvp_seqc;
3805 VNPASS(cache_fplookup_vnode_supported(dvp), dvp);
3807 if (cnp->cn_nameiop != LOOKUP) {
3808 return (cache_fplookup_final_modifying(fpl));
3811 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
3812 return (cache_fplookup_final_withparent(fpl));
3814 tvs = vget_prep_smr(tvp);
3815 if (__predict_false(tvs == VGET_NONE)) {
3816 return (cache_fpl_partial(fpl));
3819 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3820 cache_fpl_smr_exit(fpl);
3821 vget_abort(tvp, tvs);
3822 return (cache_fpl_aborted(fpl));
3825 cache_fpl_smr_exit(fpl);
3826 return (cache_fplookup_final_child(fpl, tvs));
3829 static int __noinline
3830 cache_fplookup_dot(struct cache_fpl *fpl)
3837 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3838 if (seqc_in_modify(fpl->tvp_seqc)) {
3839 return (cache_fpl_aborted(fpl));
3842 counter_u64_add(dothits, 1);
3843 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", dvp);
3848 static int __noinline
3849 cache_fplookup_dotdot(struct cache_fpl *fpl)
3851 struct nameidata *ndp;
3852 struct componentname *cnp;
3853 struct namecache *ncp;
3863 * XXX this is racy the same way regular lookup is
3865 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
3867 if (dvp == pr->pr_root)
3870 if (dvp == ndp->ni_rootdir ||
3871 dvp == ndp->ni_topdir ||
3875 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3876 if (seqc_in_modify(fpl->tvp_seqc)) {
3877 return (cache_fpl_aborted(fpl));
3882 if ((dvp->v_vflag & VV_ROOT) != 0) {
3885 * The opposite of climb mount is needed here.
3887 return (cache_fpl_aborted(fpl));
3890 ncp = atomic_load_ptr(&dvp->v_cache_dd);
3892 return (cache_fpl_aborted(fpl));
3895 nc_flag = atomic_load_char(&ncp->nc_flag);
3896 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3897 if ((nc_flag & NCF_NEGATIVE) != 0)
3898 return (cache_fpl_aborted(fpl));
3899 fpl->tvp = ncp->nc_vp;
3901 fpl->tvp = ncp->nc_dvp;
3904 if (__predict_false(!cache_ncp_canuse(ncp))) {
3905 return (cache_fpl_aborted(fpl));
3908 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
3909 if (seqc_in_modify(fpl->tvp_seqc)) {
3910 return (cache_fpl_partial(fpl));
3913 counter_u64_add(dotdothits, 1);
3917 static int __noinline
3918 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
3920 struct negstate *ns;
3926 nc_flag = atomic_load_char(&ncp->nc_flag);
3927 MPASS((nc_flag & NCF_NEGATIVE) != 0);
3929 * If they want to create an entry we need to replace this one.
3931 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
3934 * This should call something similar to
3935 * cache_fplookup_final_modifying.
3937 return (cache_fpl_partial(fpl));
3939 ns = NCP2NEGSTATE(ncp);
3940 neg_hot = ((ns->neg_flag & NEG_HOT) != 0);
3941 if (__predict_false(!cache_ncp_canuse(ncp))) {
3942 return (cache_fpl_partial(fpl));
3944 if (__predict_false((nc_flag & NCF_WHITE) != 0)) {
3945 return (cache_fpl_partial(fpl));
3948 return (cache_fplookup_negative_promote(fpl, ncp, hash));
3950 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
3951 counter_u64_add(numneghits, 1);
3952 cache_fpl_smr_exit(fpl);
3953 return (cache_fpl_handled(fpl, ENOENT));
3957 cache_fplookup_next(struct cache_fpl *fpl)
3959 struct componentname *cnp;
3960 struct namecache *ncp;
3961 struct vnode *dvp, *tvp;
3968 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.')) {
3969 return (cache_fplookup_dot(fpl));
3972 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
3974 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3975 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3976 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
3981 * If there is no entry we have to punt to the slow path to perform
3982 * actual lookup. Should there be nothing with this name a negative
3983 * entry will be created.
3985 if (__predict_false(ncp == NULL)) {
3986 return (cache_fpl_partial(fpl));
3989 tvp = atomic_load_ptr(&ncp->nc_vp);
3990 nc_flag = atomic_load_char(&ncp->nc_flag);
3991 if ((nc_flag & NCF_NEGATIVE) != 0) {
3992 return (cache_fplookup_neg(fpl, ncp, hash));
3995 if (__predict_false(!cache_ncp_canuse(ncp))) {
3996 return (cache_fpl_partial(fpl));
4000 fpl->tvp_seqc = vn_seqc_read_any(tvp);
4001 if (seqc_in_modify(fpl->tvp_seqc)) {
4002 return (cache_fpl_partial(fpl));
4005 if (!cache_fplookup_vnode_supported(tvp)) {
4006 return (cache_fpl_partial(fpl));
4009 counter_u64_add(numposhits, 1);
4010 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
4015 cache_fplookup_mp_supported(struct mount *mp)
4020 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4026 * Walk up the mount stack (if any).
4028 * Correctness is provided in the following ways:
4029 * - all vnodes are protected from freeing with SMR
4030 * - struct mount objects are type stable making them always safe to access
4031 * - stability of the particular mount is provided by busying it
4032 * - relationship between the vnode which is mounted on and the mount is
4033 * verified with the vnode sequence counter after busying
4034 * - association between root vnode of the mount and the mount is protected
4037 * From that point on we can read the sequence counter of the root vnode
4038 * and get the next mount on the stack (if any) using the same protection.
4040 * By the end of successful walk we are guaranteed the reached state was
4041 * indeed present at least at some point which matches the regular lookup.
4043 static int __noinline
4044 cache_fplookup_climb_mount(struct cache_fpl *fpl)
4046 struct mount *mp, *prev_mp;
4051 vp_seqc = fpl->tvp_seqc;
4053 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
4054 mp = atomic_load_ptr(&vp->v_mountedhere);
4060 if (!vfs_op_thread_enter_crit(mp)) {
4061 if (prev_mp != NULL)
4062 vfs_op_thread_exit_crit(prev_mp);
4063 return (cache_fpl_partial(fpl));
4065 if (prev_mp != NULL)
4066 vfs_op_thread_exit_crit(prev_mp);
4067 if (!vn_seqc_consistent(vp, vp_seqc)) {
4068 vfs_op_thread_exit_crit(mp);
4069 return (cache_fpl_partial(fpl));
4071 if (!cache_fplookup_mp_supported(mp)) {
4072 vfs_op_thread_exit_crit(mp);
4073 return (cache_fpl_partial(fpl));
4075 vp = atomic_load_ptr(&mp->mnt_rootvnode);
4076 if (vp == NULL || VN_IS_DOOMED(vp)) {
4077 vfs_op_thread_exit_crit(mp);
4078 return (cache_fpl_partial(fpl));
4080 vp_seqc = vn_seqc_read_any(vp);
4081 if (seqc_in_modify(vp_seqc)) {
4082 vfs_op_thread_exit_crit(mp);
4083 return (cache_fpl_partial(fpl));
4086 mp = atomic_load_ptr(&vp->v_mountedhere);
4091 vfs_op_thread_exit_crit(prev_mp);
4093 fpl->tvp_seqc = vp_seqc;
4098 cache_fplookup_need_climb_mount(struct cache_fpl *fpl)
4106 * Hack: while this is a union, the pointer tends to be NULL so save on
4109 mp = atomic_load_ptr(&vp->v_mountedhere);
4112 if (vp->v_type == VDIR)
4120 * The code was originally copy-pasted from regular lookup and despite
4121 * clean ups leaves performance on the table. Any modifications here
4122 * must take into account that in case off fallback the resulting
4123 * nameidata state has to be compatible with the original.
4126 cache_fplookup_parse(struct cache_fpl *fpl)
4128 struct nameidata *ndp;
4129 struct componentname *cnp;
4136 * Search a new directory.
4138 * The last component of the filename is left accessible via
4139 * cnp->cn_nameptr for callers that need the name. Callers needing
4140 * the name set the SAVENAME flag. When done, they assume
4141 * responsibility for freeing the pathname buffer.
4143 for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
4145 cnp->cn_namelen = cp - cnp->cn_nameptr;
4146 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4147 cache_fpl_smr_exit(fpl);
4148 return (cache_fpl_handled(fpl, ENAMETOOLONG));
4150 ndp->ni_pathlen -= cnp->cn_namelen;
4151 KASSERT(ndp->ni_pathlen <= PATH_MAX,
4152 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
4156 * Replace multiple slashes by a single slash and trailing slashes
4157 * by a null. This must be done before VOP_LOOKUP() because some
4158 * fs's don't know about trailing slashes. Remember if there were
4159 * trailing slashes to handle symlinks, existing non-directories
4160 * and non-existing files that won't be directories specially later.
4162 while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
4168 * Regular lookup performs the following:
4169 * *ndp->ni_next = '\0';
4170 * cnp->cn_flags |= TRAILINGSLASH;
4172 * Which is problematic since it modifies data read
4173 * from userspace. Then if fast path lookup was to
4174 * abort we would have to either restore it or convey
4175 * the flag. Since this is a corner case just ignore
4176 * it for simplicity.
4178 return (cache_fpl_partial(fpl));
4184 * Check for degenerate name (e.g. / or "")
4185 * which is a way of talking about a directory,
4186 * e.g. like "/." or ".".
4189 * Another corner case handled by the regular lookup
4191 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
4192 return (cache_fpl_partial(fpl));
4198 cache_fplookup_parse_advance(struct cache_fpl *fpl)
4200 struct nameidata *ndp;
4201 struct componentname *cnp;
4206 cnp->cn_nameptr = ndp->ni_next;
4207 while (*cnp->cn_nameptr == '/') {
4214 * See the API contract for VOP_FPLOOKUP_VEXEC.
4216 static int __noinline
4217 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
4219 struct componentname *cnp;
4225 dvp_seqc = fpl->dvp_seqc;
4228 * Hack: they may be looking up foo/bar, where foo is a
4229 * regular file. In such a case we need to turn ENOTDIR,
4230 * but we may happen to get here with a different error.
4232 if (dvp->v_type != VDIR) {
4234 * The check here is predominantly to catch
4235 * EOPNOTSUPP from dead_vnodeops. If the vnode
4236 * gets doomed past this point it is going to
4237 * fail seqc verification.
4239 if (VN_IS_DOOMED(dvp)) {
4240 return (cache_fpl_aborted(fpl));
4246 * Hack: handle O_SEARCH.
4248 * Open Group Base Specifications Issue 7, 2018 edition states:
4249 * If the access mode of the open file description associated with the
4250 * file descriptor is not O_SEARCH, the function shall check whether
4251 * directory searches are permitted using the current permissions of
4252 * the directory underlying the file descriptor. If the access mode is
4253 * O_SEARCH, the function shall not perform the check.
4255 * Regular lookup tests for the NOEXECCHECK flag for every path
4256 * component to decide whether to do the permission check. However,
4257 * since most lookups never have the flag (and when they do it is only
4258 * present for the first path component), lockless lookup only acts on
4259 * it if there is a permission problem. Here the flag is represented
4260 * with a boolean so that we don't have to clear it on the way out.
4262 * For simplicity this always aborts.
4263 * TODO: check if this is the first lookup and ignore the permission
4264 * problem. Note the flag has to survive fallback (if it happens to be
4268 return (cache_fpl_aborted(fpl));
4273 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4274 error = cache_fpl_aborted(fpl);
4276 cache_fpl_partial(fpl);
4280 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4281 error = cache_fpl_aborted(fpl);
4283 cache_fpl_smr_exit(fpl);
4284 cache_fpl_handled(fpl, error);
4292 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
4294 struct nameidata *ndp;
4295 struct componentname *cnp;
4299 error = CACHE_FPL_FAILED;
4303 cache_fpl_checkpoint(fpl, &fpl->snd);
4306 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
4307 if (seqc_in_modify(fpl->dvp_seqc)) {
4308 cache_fpl_aborted(fpl);
4311 mp = atomic_load_ptr(&fpl->dvp->v_mount);
4312 if (!cache_fplookup_mp_supported(mp)) {
4313 cache_fpl_aborted(fpl);
4317 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4320 error = cache_fplookup_parse(fpl);
4321 if (__predict_false(error != 0)) {
4325 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4327 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
4328 if (__predict_false(error != 0)) {
4329 error = cache_fplookup_failed_vexec(fpl, error);
4333 if (__predict_false(cache_fpl_isdotdot(cnp))) {
4334 error = cache_fplookup_dotdot(fpl);
4335 if (__predict_false(error != 0)) {
4339 error = cache_fplookup_next(fpl);
4340 if (__predict_false(error != 0)) {
4344 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4346 if (cache_fplookup_need_climb_mount(fpl)) {
4347 error = cache_fplookup_climb_mount(fpl);
4348 if (__predict_false(error != 0)) {
4354 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4356 if (cache_fpl_islastcn(ndp)) {
4357 error = cache_fplookup_final(fpl);
4361 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
4362 error = cache_fpl_aborted(fpl);
4366 fpl->dvp = fpl->tvp;
4367 fpl->dvp_seqc = fpl->tvp_seqc;
4369 cache_fplookup_parse_advance(fpl);
4370 cache_fpl_checkpoint(fpl, &fpl->snd);
4373 switch (fpl->status) {
4374 case CACHE_FPL_STATUS_UNSET:
4375 __assert_unreachable();
4377 case CACHE_FPL_STATUS_PARTIAL:
4378 cache_fpl_smr_assert_entered(fpl);
4379 return (cache_fplookup_partial_setup(fpl));
4380 case CACHE_FPL_STATUS_ABORTED:
4382 cache_fpl_smr_exit(fpl);
4383 return (CACHE_FPL_FAILED);
4384 case CACHE_FPL_STATUS_HANDLED:
4385 MPASS(error != CACHE_FPL_FAILED);
4386 cache_fpl_smr_assert_not_entered(fpl);
4387 if (__predict_false(error != 0)) {
4390 cache_fpl_cleanup_cnp(cnp);
4393 ndp->ni_dvp = fpl->dvp;
4394 ndp->ni_vp = fpl->tvp;
4395 if (cnp->cn_flags & SAVENAME)
4396 cnp->cn_flags |= HASBUF;
4398 cache_fpl_cleanup_cnp(cnp);
4404 * Fast path lookup protected with SMR and sequence counters.
4406 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
4408 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
4411 * Traditional vnode lookup conceptually looks like this:
4417 * vn_unlock(current);
4424 * Each jump to the next vnode is safe memory-wise and atomic with respect to
4425 * any modifications thanks to holding respective locks.
4427 * The same guarantee can be provided with a combination of safe memory
4428 * reclamation and sequence counters instead. If all operations which affect
4429 * the relationship between the current vnode and the one we are looking for
4430 * also modify the counter, we can verify whether all the conditions held as
4431 * we made the jump. This includes things like permissions, mount points etc.
4432 * Counter modification is provided by enclosing relevant places in
4433 * vn_seqc_write_begin()/end() calls.
4435 * Thus this translates to:
4438 * dvp_seqc = seqc_read_any(dvp);
4439 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
4443 * tvp_seqc = seqc_read_any(tvp);
4444 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
4446 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
4448 * dvp = tvp; // we know nothing of importance has changed
4449 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
4453 * vget(); // secure the vnode
4454 * if (!seqc_consistent(tvp, tvp_seqc) // final check
4456 * // at this point we know nothing has changed for any parent<->child pair
4457 * // as they were crossed during the lookup, meaning we matched the guarantee
4458 * // of the locked variant
4461 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
4462 * - they are called while within vfs_smr protection which they must never exit
4463 * - EAGAIN can be returned to denote checking could not be performed, it is
4464 * always valid to return it
4465 * - if the sequence counter has not changed the result must be valid
4466 * - if the sequence counter has changed both false positives and false negatives
4467 * are permitted (since the result will be rejected later)
4468 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
4470 * Caveats to watch out for:
4471 * - vnodes are passed unlocked and unreferenced with nothing stopping
4472 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
4473 * to use atomic_load_ptr to fetch it.
4474 * - the aforementioned object can also get freed, meaning absent other means it
4475 * should be protected with vfs_smr
4476 * - either safely checking permissions as they are modified or guaranteeing
4477 * their stability is left to the routine
4480 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
4483 struct cache_fpl fpl;
4486 struct componentname *cnp;
4487 struct nameidata_saved orig;
4490 MPASS(ndp->ni_lcf == 0);
4492 fpl.status = CACHE_FPL_STATUS_UNSET;
4494 fpl.cnp = &ndp->ni_cnd;
4495 MPASS(curthread == fpl.cnp->cn_thread);
4497 if ((fpl.cnp->cn_flags & SAVESTART) != 0)
4498 MPASS(fpl.cnp->cn_nameiop != LOOKUP);
4500 if (!cache_can_fplookup(&fpl)) {
4501 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4502 *status = fpl.status;
4503 return (EOPNOTSUPP);
4506 cache_fpl_checkpoint(&fpl, &orig);
4508 cache_fpl_smr_enter_initial(&fpl);
4509 fpl.fsearch = false;
4510 pwd = pwd_get_smr();
4512 ndp->ni_rootdir = pwd->pwd_rdir;
4513 ndp->ni_topdir = pwd->pwd_jdir;
4516 cnp->cn_nameptr = cnp->cn_pnbuf;
4517 if (cnp->cn_pnbuf[0] == '/') {
4518 cache_fpl_handle_root(ndp, &dvp);
4520 if (ndp->ni_dirfd == AT_FDCWD) {
4521 dvp = pwd->pwd_cdir;
4523 error = cache_fplookup_dirfd(&fpl, &dvp);
4524 if (__predict_false(error != 0)) {
4530 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
4532 error = cache_fplookup_impl(dvp, &fpl);
4534 cache_fpl_smr_assert_not_entered(&fpl);
4535 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4537 *status = fpl.status;
4538 switch (fpl.status) {
4539 case CACHE_FPL_STATUS_UNSET:
4540 __assert_unreachable();
4542 case CACHE_FPL_STATUS_HANDLED:
4543 SDT_PROBE3(vfs, namei, lookup, return, error,
4544 (error == 0 ? ndp->ni_vp : NULL), true);
4546 case CACHE_FPL_STATUS_PARTIAL:
4549 * Status restored by cache_fplookup_partial_setup.
4552 case CACHE_FPL_STATUS_ABORTED:
4553 cache_fpl_restore(&fpl, &orig);