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 cache_neg_hit_prep(struct namecache *ncp)
916 ns = NCP2NEGSTATE(ncp);
917 if ((ns->neg_flag & NEG_HOT) != 0)
923 * Nothing to do here but it is provided for completeness as some
924 * cache_neg_hit_prep callers may end up returning without even
927 #define cache_neg_hit_abort(ncp) do { } while (0)
930 cache_neg_hit_finish(struct namecache *ncp)
933 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
934 counter_u64_add(numneghits, 1);
938 * Move a negative entry to the hot list.
941 cache_neg_promote_locked(struct namecache *ncp)
946 ns = NCP2NEGSTATE(ncp);
947 nl = NCP2NEGLIST(ncp);
948 mtx_assert(&nl->nl_lock, MA_OWNED);
949 if ((ns->neg_flag & NEG_HOT) == 0) {
950 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
951 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
953 ns->neg_flag |= NEG_HOT;
958 * Move a hot negative entry to the cold list.
961 cache_neg_demote_locked(struct namecache *ncp)
966 ns = NCP2NEGSTATE(ncp);
967 nl = NCP2NEGLIST(ncp);
968 mtx_assert(&nl->nl_lock, MA_OWNED);
969 MPASS(ns->neg_flag & NEG_HOT);
970 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
971 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
973 ns->neg_flag &= ~NEG_HOT;
977 * Move a negative entry to the hot list if it matches the lookup.
979 * We have to take locks, but they may be contended and in the worst
980 * case we may need to go off CPU. We don't want to spin within the
981 * smr section and we can't block with it. Exiting the section means
982 * the found entry could have been evicted. We are going to look it
986 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
987 struct namecache *oncp, uint32_t hash)
989 struct namecache *ncp;
993 nl = NCP2NEGLIST(oncp);
995 mtx_lock(&nl->nl_lock);
997 * For hash iteration.
1002 * Avoid all surprises by only succeeding if we got the same entry and
1003 * bailing completely otherwise.
1004 * XXX There are no provisions to keep the vnode around, meaning we may
1005 * end up promoting a negative entry for a *new* vnode and returning
1006 * ENOENT on its account. This is the error we want to return anyway
1007 * and promotion is harmless.
1009 * In particular at this point there can be a new ncp which matches the
1010 * search but hashes to a different neglist.
1012 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1018 * No match to begin with.
1020 if (__predict_false(ncp == NULL)) {
1025 * The newly found entry may be something different...
1027 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1028 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1033 * ... and not even negative.
1035 nc_flag = atomic_load_char(&ncp->nc_flag);
1036 if ((nc_flag & NCF_NEGATIVE) == 0) {
1040 if (__predict_false(!cache_ncp_canuse(ncp))) {
1044 cache_neg_promote_locked(ncp);
1045 cache_neg_hit_finish(ncp);
1047 mtx_unlock(&nl->nl_lock);
1051 mtx_unlock(&nl->nl_lock);
1056 cache_neg_promote(struct namecache *ncp)
1060 nl = NCP2NEGLIST(ncp);
1061 mtx_lock(&nl->nl_lock);
1062 cache_neg_promote_locked(ncp);
1063 mtx_unlock(&nl->nl_lock);
1067 cache_neg_insert(struct namecache *ncp)
1071 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1072 cache_assert_bucket_locked(ncp);
1073 nl = NCP2NEGLIST(ncp);
1074 mtx_lock(&nl->nl_lock);
1075 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1076 mtx_unlock(&nl->nl_lock);
1077 atomic_add_long(&numneg, 1);
1081 cache_neg_remove(struct namecache *ncp)
1084 struct negstate *ns;
1086 cache_assert_bucket_locked(ncp);
1087 nl = NCP2NEGLIST(ncp);
1088 ns = NCP2NEGSTATE(ncp);
1089 mtx_lock(&nl->nl_lock);
1090 if ((ns->neg_flag & NEG_HOT) != 0) {
1091 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1094 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1096 mtx_unlock(&nl->nl_lock);
1097 atomic_subtract_long(&numneg, 1);
1100 static struct neglist *
1101 cache_neg_evict_select(void)
1106 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1107 nl = &neglists[c % numneglists];
1108 if (!mtx_trylock(&nl->nl_evict_lock)) {
1109 counter_u64_add(neg_evict_skipped_contended, 1);
1116 cache_neg_evict(void)
1118 struct namecache *ncp, *ncp2;
1120 struct negstate *ns;
1128 nl = cache_neg_evict_select();
1133 mtx_lock(&nl->nl_lock);
1134 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1136 cache_neg_demote_locked(ncp);
1138 ncp = TAILQ_FIRST(&nl->nl_list);
1140 counter_u64_add(neg_evict_skipped_empty, 1);
1141 mtx_unlock(&nl->nl_lock);
1142 mtx_unlock(&nl->nl_evict_lock);
1145 ns = NCP2NEGSTATE(ncp);
1146 nlen = ncp->nc_nlen;
1148 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1149 dvlp = VP2VNODELOCK(dvp);
1150 blp = HASH2BUCKETLOCK(hash);
1151 mtx_unlock(&nl->nl_lock);
1152 mtx_unlock(&nl->nl_evict_lock);
1156 * Note that since all locks were dropped above, the entry may be
1157 * gone or reallocated to be something else.
1159 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1160 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1161 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1165 counter_u64_add(neg_evict_skipped_missed, 1);
1169 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1170 MPASS(blp == NCP2BUCKETLOCK(ncp));
1171 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1173 cache_zap_locked(ncp);
1174 counter_u64_add(neg_evicted, 1);
1185 * Maybe evict a negative entry to create more room.
1187 * The ncnegfactor parameter limits what fraction of the total count
1188 * can comprise of negative entries. However, if the cache is just
1189 * warming up this leads to excessive evictions. As such, ncnegminpct
1190 * (recomputed to neg_min) dictates whether the above should be
1193 * Try evicting if the cache is close to full capacity regardless of
1194 * other considerations.
1197 cache_neg_evict_cond(u_long lnumcache)
1201 if (ncsize - 1000 < lnumcache)
1203 lnumneg = atomic_load_long(&numneg);
1204 if (lnumneg < neg_min)
1206 if (lnumneg * ncnegfactor < lnumcache)
1209 return (cache_neg_evict());
1213 * cache_zap_locked():
1215 * Removes a namecache entry from cache, whether it contains an actual
1216 * pointer to a vnode or if it is just a negative cache entry.
1219 cache_zap_locked(struct namecache *ncp)
1221 struct nchashhead *ncpp;
1223 if (!(ncp->nc_flag & NCF_NEGATIVE))
1224 cache_assert_vnode_locked(ncp->nc_vp);
1225 cache_assert_vnode_locked(ncp->nc_dvp);
1226 cache_assert_bucket_locked(ncp);
1228 cache_ncp_invalidate(ncp);
1230 ncpp = NCP2BUCKET(ncp);
1231 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1232 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1233 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
1234 ncp->nc_name, ncp->nc_vp);
1235 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
1236 if (ncp == ncp->nc_vp->v_cache_dd) {
1237 vn_seqc_write_begin_unheld(ncp->nc_vp);
1238 ncp->nc_vp->v_cache_dd = NULL;
1239 vn_seqc_write_end(ncp->nc_vp);
1242 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
1244 cache_neg_remove(ncp);
1246 if (ncp->nc_flag & NCF_ISDOTDOT) {
1247 if (ncp == ncp->nc_dvp->v_cache_dd) {
1248 vn_seqc_write_begin_unheld(ncp->nc_dvp);
1249 ncp->nc_dvp->v_cache_dd = NULL;
1250 vn_seqc_write_end(ncp->nc_dvp);
1253 LIST_REMOVE(ncp, nc_src);
1254 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
1255 ncp->nc_flag |= NCF_DVDROP;
1256 counter_u64_add(numcachehv, -1);
1259 atomic_subtract_long(&numcache, 1);
1263 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1267 MPASS(ncp->nc_dvp == vp);
1268 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1269 cache_assert_vnode_locked(vp);
1271 blp = NCP2BUCKETLOCK(ncp);
1273 cache_zap_locked(ncp);
1278 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1281 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1284 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1285 cache_assert_vnode_locked(vp);
1287 if (ncp->nc_flag & NCF_NEGATIVE) {
1288 if (*vlpp != NULL) {
1292 cache_zap_negative_locked_vnode_kl(ncp, vp);
1296 pvlp = VP2VNODELOCK(vp);
1297 blp = NCP2BUCKETLOCK(ncp);
1298 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1299 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1301 if (*vlpp == vlp1 || *vlpp == vlp2) {
1305 if (*vlpp != NULL) {
1309 cache_sort_vnodes(&vlp1, &vlp2);
1314 if (!mtx_trylock(vlp1))
1320 cache_zap_locked(ncp);
1322 if (to_unlock != NULL)
1323 mtx_unlock(to_unlock);
1330 MPASS(*vlpp == NULL);
1336 * If trylocking failed we can get here. We know enough to take all needed locks
1337 * in the right order and re-lookup the entry.
1340 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1341 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1344 struct namecache *rncp;
1346 cache_assert_bucket_unlocked(ncp);
1348 cache_sort_vnodes(&dvlp, &vlp);
1349 cache_lock_vnodes(dvlp, vlp);
1351 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1352 if (rncp == ncp && rncp->nc_dvp == dvp &&
1353 rncp->nc_nlen == cnp->cn_namelen &&
1354 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1358 cache_zap_locked(rncp);
1360 cache_unlock_vnodes(dvlp, vlp);
1361 counter_u64_add(zap_bucket_relock_success, 1);
1366 cache_unlock_vnodes(dvlp, vlp);
1370 static int __noinline
1371 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1372 uint32_t hash, struct mtx *blp)
1374 struct mtx *dvlp, *vlp;
1377 cache_assert_bucket_locked(ncp);
1379 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1381 if (!(ncp->nc_flag & NCF_NEGATIVE))
1382 vlp = VP2VNODELOCK(ncp->nc_vp);
1383 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1384 cache_zap_locked(ncp);
1386 cache_unlock_vnodes(dvlp, vlp);
1392 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1395 static __noinline int
1396 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1398 struct namecache *ncp;
1400 struct mtx *dvlp, *dvlp2;
1404 if (cnp->cn_namelen == 2 &&
1405 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1406 dvlp = VP2VNODELOCK(dvp);
1410 ncp = dvp->v_cache_dd;
1415 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1418 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1419 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1421 MPASS(dvp->v_cache_dd == NULL);
1427 vn_seqc_write_begin(dvp);
1428 dvp->v_cache_dd = NULL;
1429 vn_seqc_write_end(dvp);
1434 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1438 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1439 blp = HASH2BUCKETLOCK(hash);
1441 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1446 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1447 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1448 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1457 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1458 if (__predict_false(error != 0)) {
1462 counter_u64_add(numposzaps, 1);
1463 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1467 counter_u64_add(nummisszap, 1);
1468 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1472 static int __noinline
1473 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1474 struct timespec *tsp, int *ticksp)
1479 counter_u64_add(dothits, 1);
1480 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1487 * When we lookup "." we still can be asked to lock it
1490 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1491 if (ltype != VOP_ISLOCKED(*vpp)) {
1492 if (ltype == LK_EXCLUSIVE) {
1493 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1494 if (VN_IS_DOOMED((*vpp))) {
1495 /* forced unmount */
1501 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1506 static int __noinline
1507 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1508 struct timespec *tsp, int *ticksp)
1510 struct namecache_ts *ncp_ts;
1511 struct namecache *ncp;
1517 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1519 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1520 cache_remove_cnp(dvp, cnp);
1524 counter_u64_add(dotdothits, 1);
1526 dvlp = VP2VNODELOCK(dvp);
1528 ncp = dvp->v_cache_dd;
1530 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, "..", NULL);
1534 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1535 if (ncp->nc_flag & NCF_NEGATIVE)
1542 goto negative_success;
1543 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1544 cache_out_ts(ncp, tsp, ticksp);
1545 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1546 NCF_DTS && tsp != NULL) {
1547 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1548 *tsp = ncp_ts->nc_dotdottime;
1552 ltype = VOP_ISLOCKED(dvp);
1554 vs = vget_prep(*vpp);
1556 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1557 vn_lock(dvp, ltype | LK_RETRY);
1558 if (VN_IS_DOOMED(dvp)) {
1570 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1571 if (cnp->cn_flags & ISLASTCN) {
1572 counter_u64_add(numnegzaps, 1);
1573 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1580 whiteout = (ncp->nc_flag & NCF_WHITE);
1581 cache_out_ts(ncp, tsp, ticksp);
1582 if (cache_neg_hit_prep(ncp))
1583 cache_neg_promote(ncp);
1585 cache_neg_hit_finish(ncp);
1588 cnp->cn_flags |= ISWHITEOUT;
1593 * Lookup a name in the name cache
1597 * - dvp: Parent directory in which to search.
1598 * - vpp: Return argument. Will contain desired vnode on cache hit.
1599 * - cnp: Parameters of the name search. The most interesting bits of
1600 * the cn_flags field have the following meanings:
1601 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1603 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1604 * - tsp: Return storage for cache timestamp. On a successful (positive
1605 * or negative) lookup, tsp will be filled with any timespec that
1606 * was stored when this cache entry was created. However, it will
1607 * be clear for "." entries.
1608 * - ticks: Return storage for alternate cache timestamp. On a successful
1609 * (positive or negative) lookup, it will contain the ticks value
1610 * that was current when the cache entry was created, unless cnp
1613 * Either both tsp and ticks have to be provided or neither of them.
1617 * - -1: A positive cache hit. vpp will contain the desired vnode.
1618 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1619 * to a forced unmount. vpp will not be modified. If the entry
1620 * is a whiteout, then the ISWHITEOUT flag will be set in
1622 * - 0: A cache miss. vpp will not be modified.
1626 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1627 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1628 * lock is not recursively acquired.
1630 static int __noinline
1631 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1632 struct timespec *tsp, int *ticksp)
1634 struct namecache *ncp;
1641 MPASS((cnp->cn_flags & (MAKEENTRY | ISDOTDOT)) == MAKEENTRY);
1644 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1645 blp = HASH2BUCKETLOCK(hash);
1648 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1649 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1650 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1654 if (__predict_false(ncp == NULL)) {
1656 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1658 counter_u64_add(nummiss, 1);
1662 if (ncp->nc_flag & NCF_NEGATIVE)
1663 goto negative_success;
1665 counter_u64_add(numposhits, 1);
1667 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1668 cache_out_ts(ncp, tsp, ticksp);
1670 vs = vget_prep(*vpp);
1672 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1679 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1680 if (cnp->cn_flags & ISLASTCN) {
1681 counter_u64_add(numnegzaps, 1);
1682 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1683 if (__predict_false(error != 0)) {
1692 whiteout = (ncp->nc_flag & NCF_WHITE);
1693 cache_out_ts(ncp, tsp, ticksp);
1694 if (cache_neg_hit_prep(ncp))
1695 cache_neg_promote(ncp);
1697 cache_neg_hit_finish(ncp);
1700 cnp->cn_flags |= ISWHITEOUT;
1705 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1706 struct timespec *tsp, int *ticksp)
1708 struct namecache *ncp;
1712 bool whiteout, neg_promote;
1715 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
1718 if (__predict_false(!doingcache)) {
1719 cnp->cn_flags &= ~MAKEENTRY;
1724 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1725 if (cnp->cn_namelen == 1)
1726 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1727 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
1728 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
1731 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1733 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1734 cache_remove_cnp(dvp, cnp);
1738 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1741 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1742 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1743 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1747 if (__predict_false(ncp == NULL)) {
1749 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1751 counter_u64_add(nummiss, 1);
1755 nc_flag = atomic_load_char(&ncp->nc_flag);
1756 if (nc_flag & NCF_NEGATIVE)
1757 goto negative_success;
1759 counter_u64_add(numposhits, 1);
1761 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1762 cache_out_ts(ncp, tsp, ticksp);
1764 if (!cache_ncp_canuse(ncp)) {
1769 vs = vget_prep_smr(*vpp);
1771 if (__predict_false(vs == VGET_NONE)) {
1775 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1782 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1783 if (cnp->cn_flags & ISLASTCN) {
1789 cache_out_ts(ncp, tsp, ticksp);
1790 whiteout = (ncp->nc_flag & NCF_WHITE);
1791 neg_promote = cache_neg_hit_prep(ncp);
1792 if (__predict_false(!cache_ncp_canuse(ncp))) {
1793 cache_neg_hit_abort(ncp);
1799 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
1802 cache_neg_hit_finish(ncp);
1806 cnp->cn_flags |= ISWHITEOUT;
1809 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
1812 struct celockstate {
1816 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1817 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1820 cache_celockstate_init(struct celockstate *cel)
1823 bzero(cel, sizeof(*cel));
1827 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1830 struct mtx *vlp1, *vlp2;
1832 MPASS(cel->vlp[0] == NULL);
1833 MPASS(cel->vlp[1] == NULL);
1834 MPASS(cel->vlp[2] == NULL);
1836 MPASS(vp != NULL || dvp != NULL);
1838 vlp1 = VP2VNODELOCK(vp);
1839 vlp2 = VP2VNODELOCK(dvp);
1840 cache_sort_vnodes(&vlp1, &vlp2);
1851 cache_unlock_vnodes_cel(struct celockstate *cel)
1854 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
1856 if (cel->vlp[0] != NULL)
1857 mtx_unlock(cel->vlp[0]);
1858 if (cel->vlp[1] != NULL)
1859 mtx_unlock(cel->vlp[1]);
1860 if (cel->vlp[2] != NULL)
1861 mtx_unlock(cel->vlp[2]);
1865 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
1870 cache_assert_vlp_locked(cel->vlp[0]);
1871 cache_assert_vlp_locked(cel->vlp[1]);
1872 MPASS(cel->vlp[2] == NULL);
1875 vlp = VP2VNODELOCK(vp);
1878 if (vlp >= cel->vlp[1]) {
1881 if (mtx_trylock(vlp))
1883 cache_lock_vnodes_cel_3_failures++;
1884 cache_unlock_vnodes_cel(cel);
1885 if (vlp < cel->vlp[0]) {
1887 mtx_lock(cel->vlp[0]);
1888 mtx_lock(cel->vlp[1]);
1890 if (cel->vlp[0] != NULL)
1891 mtx_lock(cel->vlp[0]);
1893 mtx_lock(cel->vlp[1]);
1903 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
1907 MPASS(cel->blp[0] == NULL);
1908 MPASS(cel->blp[1] == NULL);
1910 cache_sort_vnodes(&blp1, &blp2);
1921 cache_unlock_buckets_cel(struct celockstate *cel)
1924 if (cel->blp[0] != NULL)
1925 mtx_unlock(cel->blp[0]);
1926 mtx_unlock(cel->blp[1]);
1930 * Lock part of the cache affected by the insertion.
1932 * This means vnodelocks for dvp, vp and the relevant bucketlock.
1933 * However, insertion can result in removal of an old entry. In this
1934 * case we have an additional vnode and bucketlock pair to lock.
1936 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
1937 * preserving the locking order (smaller address first).
1940 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1943 struct namecache *ncp;
1944 struct mtx *blps[2];
1946 blps[0] = HASH2BUCKETLOCK(hash);
1949 cache_lock_vnodes_cel(cel, dvp, vp);
1950 if (vp == NULL || vp->v_type != VDIR)
1952 ncp = vp->v_cache_dd;
1955 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1957 MPASS(ncp->nc_dvp == vp);
1958 blps[1] = NCP2BUCKETLOCK(ncp);
1959 if (ncp->nc_flag & NCF_NEGATIVE)
1961 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1964 * All vnodes got re-locked. Re-validate the state and if
1965 * nothing changed we are done. Otherwise restart.
1967 if (ncp == vp->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_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1984 struct namecache *ncp;
1985 struct mtx *blps[2];
1987 blps[0] = HASH2BUCKETLOCK(hash);
1990 cache_lock_vnodes_cel(cel, dvp, vp);
1991 ncp = dvp->v_cache_dd;
1994 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1996 MPASS(ncp->nc_dvp == dvp);
1997 blps[1] = NCP2BUCKETLOCK(ncp);
1998 if (ncp->nc_flag & NCF_NEGATIVE)
2000 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2002 if (ncp == dvp->v_cache_dd &&
2003 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2004 blps[1] == NCP2BUCKETLOCK(ncp) &&
2005 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2007 cache_unlock_vnodes_cel(cel);
2012 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2016 cache_enter_unlock(struct celockstate *cel)
2019 cache_unlock_buckets_cel(cel);
2020 cache_unlock_vnodes_cel(cel);
2023 static void __noinline
2024 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2025 struct componentname *cnp)
2027 struct celockstate cel;
2028 struct namecache *ncp;
2032 if (dvp->v_cache_dd == NULL)
2034 len = cnp->cn_namelen;
2035 cache_celockstate_init(&cel);
2036 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2037 cache_enter_lock_dd(&cel, dvp, vp, hash);
2038 vn_seqc_write_begin(dvp);
2039 ncp = dvp->v_cache_dd;
2040 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2041 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2042 cache_zap_locked(ncp);
2046 dvp->v_cache_dd = NULL;
2047 vn_seqc_write_end(dvp);
2048 cache_enter_unlock(&cel);
2054 * Add an entry to the cache.
2057 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2058 struct timespec *tsp, struct timespec *dtsp)
2060 struct celockstate cel;
2061 struct namecache *ncp, *n2, *ndd;
2062 struct namecache_ts *ncp_ts;
2063 struct nchashhead *ncpp;
2069 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2070 VNPASS(dvp->v_type != VNON, dvp);
2072 VNPASS(!VN_IS_DOOMED(vp), vp);
2073 VNPASS(vp->v_type != VNON, vp);
2077 if (__predict_false(!doingcache))
2082 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2083 if (cnp->cn_namelen == 1)
2085 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2086 cache_enter_dotdot_prep(dvp, vp, cnp);
2087 flag = NCF_ISDOTDOT;
2092 * Avoid blowout in namecache entries.
2095 * 1. filesystems may end up tryng to add an already existing entry
2096 * (for example this can happen after a cache miss during concurrent
2097 * lookup), in which case we will call cache_neg_evict despite not
2099 * 2. the routine may fail to free anything and no provisions are made
2100 * to make it try harder (see the inside for failure modes)
2101 * 3. it only ever looks at negative entries.
2103 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
2104 if (cache_neg_evict_cond(lnumcache)) {
2105 lnumcache = atomic_load_long(&numcache);
2107 if (__predict_false(lnumcache >= ncsize)) {
2108 atomic_subtract_long(&numcache, 1);
2109 counter_u64_add(numdrops, 1);
2113 cache_celockstate_init(&cel);
2118 * Calculate the hash key and setup as much of the new
2119 * namecache entry as possible before acquiring the lock.
2121 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2122 ncp->nc_flag = flag | NCF_WIP;
2125 cache_neg_init(ncp);
2128 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2129 ncp_ts->nc_time = *tsp;
2130 ncp_ts->nc_ticks = ticks;
2131 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2133 ncp_ts->nc_dotdottime = *dtsp;
2134 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2137 len = ncp->nc_nlen = cnp->cn_namelen;
2138 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2139 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2140 ncp->nc_name[len] = '\0';
2141 cache_enter_lock(&cel, dvp, vp, hash);
2144 * See if this vnode or negative entry is already in the cache
2145 * with this name. This can happen with concurrent lookups of
2146 * the same path name.
2148 ncpp = NCHHASH(hash);
2149 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2150 if (n2->nc_dvp == dvp &&
2151 n2->nc_nlen == cnp->cn_namelen &&
2152 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2153 MPASS(cache_ncp_canuse(n2));
2154 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2156 ("%s: found entry pointing to a different vnode (%p != %p)",
2157 __func__, NULL, vp));
2159 KASSERT(n2->nc_vp == vp,
2160 ("%s: found entry pointing to a different vnode (%p != %p)",
2161 __func__, n2->nc_vp, vp));
2163 * Entries are supposed to be immutable unless in the
2164 * process of getting destroyed. Accommodating for
2165 * changing timestamps is possible but not worth it.
2166 * This should be harmless in terms of correctness, in
2167 * the worst case resulting in an earlier expiration.
2168 * Alternatively, the found entry can be replaced
2171 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2174 KASSERT((n2->nc_flag & NCF_TS) != 0,
2176 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2177 n2_ts->nc_time = ncp_ts->nc_time;
2178 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2180 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2181 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2185 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2187 goto out_unlock_free;
2191 if (flag == NCF_ISDOTDOT) {
2193 * See if we are trying to add .. entry, but some other lookup
2194 * has populated v_cache_dd pointer already.
2196 if (dvp->v_cache_dd != NULL)
2197 goto out_unlock_free;
2198 KASSERT(vp == NULL || vp->v_type == VDIR,
2199 ("wrong vnode type %p", vp));
2200 vn_seqc_write_begin(dvp);
2201 dvp->v_cache_dd = ncp;
2202 vn_seqc_write_end(dvp);
2206 if (flag != NCF_ISDOTDOT) {
2208 * For this case, the cache entry maps both the
2209 * directory name in it and the name ".." for the
2210 * directory's parent.
2212 vn_seqc_write_begin(vp);
2213 if ((ndd = vp->v_cache_dd) != NULL) {
2214 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2215 cache_zap_locked(ndd);
2219 vp->v_cache_dd = ncp;
2220 vn_seqc_write_end(vp);
2221 } else if (vp->v_type != VDIR) {
2222 if (vp->v_cache_dd != NULL) {
2223 vn_seqc_write_begin(vp);
2224 vp->v_cache_dd = NULL;
2225 vn_seqc_write_end(vp);
2230 if (flag != NCF_ISDOTDOT) {
2231 if (LIST_EMPTY(&dvp->v_cache_src)) {
2233 counter_u64_add(numcachehv, 1);
2235 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2239 * If the entry is "negative", we place it into the
2240 * "negative" cache queue, otherwise, we place it into the
2241 * destination vnode's cache entries queue.
2244 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2245 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2248 if (cnp->cn_flags & ISWHITEOUT)
2249 ncp->nc_flag |= NCF_WHITE;
2250 cache_neg_insert(ncp);
2251 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2256 * Insert the new namecache entry into the appropriate chain
2257 * within the cache entries table.
2259 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2261 atomic_thread_fence_rel();
2263 * Mark the entry as fully constructed.
2264 * It is immutable past this point until its removal.
2266 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2268 cache_enter_unlock(&cel);
2273 cache_enter_unlock(&cel);
2274 atomic_subtract_long(&numcache, 1);
2280 cache_roundup_2(u_int val)
2284 for (res = 1; res <= val; res <<= 1)
2290 static struct nchashhead *
2291 nchinittbl(u_long elements, u_long *hashmask)
2293 struct nchashhead *hashtbl;
2296 hashsize = cache_roundup_2(elements) / 2;
2298 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2299 for (i = 0; i < hashsize; i++)
2300 CK_SLIST_INIT(&hashtbl[i]);
2301 *hashmask = hashsize - 1;
2306 ncfreetbl(struct nchashhead *hashtbl)
2309 free(hashtbl, M_VFSCACHE);
2313 * Name cache initialization, from vfs_init() when we are booting
2316 nchinit(void *dummy __unused)
2320 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2321 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2322 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2323 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2324 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2325 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2326 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2327 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2329 VFS_SMR_ZONE_SET(cache_zone_small);
2330 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2331 VFS_SMR_ZONE_SET(cache_zone_large);
2332 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2334 ncsize = desiredvnodes * ncsizefactor;
2335 cache_recalc_neg_min(ncnegminpct);
2336 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2337 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2338 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2340 if (ncbuckethash > nchash)
2341 ncbuckethash = nchash;
2342 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2344 for (i = 0; i < numbucketlocks; i++)
2345 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2346 ncvnodehash = ncbuckethash;
2347 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2349 for (i = 0; i < numvnodelocks; i++)
2350 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2352 for (i = 0; i < numneglists; i++) {
2353 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2354 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2355 TAILQ_INIT(&neglists[i].nl_list);
2356 TAILQ_INIT(&neglists[i].nl_hotlist);
2359 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2362 cache_vnode_init(struct vnode *vp)
2365 LIST_INIT(&vp->v_cache_src);
2366 TAILQ_INIT(&vp->v_cache_dst);
2367 vp->v_cache_dd = NULL;
2372 cache_changesize(u_long newmaxvnodes)
2374 struct nchashhead *new_nchashtbl, *old_nchashtbl;
2375 u_long new_nchash, old_nchash;
2376 struct namecache *ncp;
2381 newncsize = newmaxvnodes * ncsizefactor;
2382 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2383 if (newmaxvnodes < numbucketlocks)
2384 newmaxvnodes = numbucketlocks;
2386 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2387 /* If same hash table size, nothing to do */
2388 if (nchash == new_nchash) {
2389 ncfreetbl(new_nchashtbl);
2393 * Move everything from the old hash table to the new table.
2394 * None of the namecache entries in the table can be removed
2395 * because to do so, they have to be removed from the hash table.
2397 cache_lock_all_vnodes();
2398 cache_lock_all_buckets();
2399 old_nchashtbl = nchashtbl;
2400 old_nchash = nchash;
2401 nchashtbl = new_nchashtbl;
2402 nchash = new_nchash;
2403 for (i = 0; i <= old_nchash; i++) {
2404 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2405 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2407 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2408 CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2412 cache_recalc_neg_min(ncnegminpct);
2413 cache_unlock_all_buckets();
2414 cache_unlock_all_vnodes();
2415 ncfreetbl(old_nchashtbl);
2419 * Invalidate all entries from and to a particular vnode.
2422 cache_purge_impl(struct vnode *vp)
2424 TAILQ_HEAD(, namecache) ncps;
2425 struct namecache *ncp, *nnp;
2426 struct mtx *vlp, *vlp2;
2429 vlp = VP2VNODELOCK(vp);
2433 while (!LIST_EMPTY(&vp->v_cache_src)) {
2434 ncp = LIST_FIRST(&vp->v_cache_src);
2435 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2437 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2439 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2440 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2441 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2443 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2445 ncp = vp->v_cache_dd;
2447 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2448 ("lost dotdot link"));
2449 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2451 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2453 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2457 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2463 * Opportunistic check to see if there is anything to do.
2466 cache_has_entries(struct vnode *vp)
2469 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2470 vp->v_cache_dd == NULL)
2476 cache_purge(struct vnode *vp)
2479 SDT_PROBE1(vfs, namecache, purge, done, vp);
2480 if (!cache_has_entries(vp))
2482 cache_purge_impl(vp);
2486 * Only to be used by vgone.
2489 cache_purge_vgone(struct vnode *vp)
2493 VNPASS(VN_IS_DOOMED(vp), vp);
2494 if (cache_has_entries(vp)) {
2495 cache_purge_impl(vp);
2500 * Serialize against a potential thread doing cache_purge.
2502 vlp = VP2VNODELOCK(vp);
2503 mtx_wait_unlocked(vlp);
2504 if (cache_has_entries(vp)) {
2505 cache_purge_impl(vp);
2512 * Invalidate all negative entries for a particular directory vnode.
2515 cache_purge_negative(struct vnode *vp)
2517 TAILQ_HEAD(, namecache) ncps;
2518 struct namecache *ncp, *nnp;
2521 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2522 if (LIST_EMPTY(&vp->v_cache_src))
2525 vlp = VP2VNODELOCK(vp);
2527 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2528 if (!(ncp->nc_flag & NCF_NEGATIVE))
2530 cache_zap_negative_locked_vnode_kl(ncp, vp);
2531 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2534 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2540 cache_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2541 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2544 ASSERT_VOP_IN_SEQC(fdvp);
2545 ASSERT_VOP_IN_SEQC(fvp);
2546 ASSERT_VOP_IN_SEQC(tdvp);
2548 ASSERT_VOP_IN_SEQC(tvp);
2553 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2554 ("%s: lingering negative entry", __func__));
2556 cache_remove_cnp(tdvp, tcnp);
2561 * Flush all entries referencing a particular filesystem.
2564 cache_purgevfs(struct mount *mp)
2566 struct vnode *vp, *mvp;
2568 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2570 * Somewhat wasteful iteration over all vnodes. Would be better to
2571 * support filtering and avoid the interlock to begin with.
2573 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2574 if (!cache_has_entries(vp)) {
2586 * Perform canonical checks and cache lookup and pass on to filesystem
2587 * through the vop_cachedlookup only if needed.
2591 vfs_cache_lookup(struct vop_lookup_args *ap)
2595 struct vnode **vpp = ap->a_vpp;
2596 struct componentname *cnp = ap->a_cnp;
2597 int flags = cnp->cn_flags;
2602 if (dvp->v_type != VDIR)
2605 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2606 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2609 error = vn_dir_check_exec(dvp, cnp);
2613 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2615 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2621 /* Implementation of the getcwd syscall. */
2623 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2629 buflen = uap->buflen;
2630 if (__predict_false(buflen < 2))
2632 if (buflen > MAXPATHLEN)
2633 buflen = MAXPATHLEN;
2635 buf = uma_zalloc(namei_zone, M_WAITOK);
2636 error = vn_getcwd(buf, &retbuf, &buflen);
2638 error = copyout(retbuf, uap->buf, buflen);
2639 uma_zfree(namei_zone, buf);
2644 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
2650 pwd = pwd_get_smr();
2651 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
2653 VFS_SMR_ASSERT_NOT_ENTERED();
2655 pwd = pwd_hold(curthread);
2656 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
2662 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2669 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2670 size_t size, int flags, enum uio_seg pathseg)
2672 struct nameidata nd;
2673 char *retbuf, *freebuf;
2678 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2679 pathseg, path, fd, &cap_fstat_rights, td);
2680 if ((error = namei(&nd)) != 0)
2682 error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
2684 error = copyout(retbuf, buf, size);
2685 free(freebuf, M_TEMP);
2692 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2695 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2696 uap->flags, UIO_USERSPACE));
2700 * Retrieve the full filesystem path that correspond to a vnode from the name
2701 * cache (if available)
2704 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
2711 if (__predict_false(vp == NULL))
2714 buflen = MAXPATHLEN;
2715 buf = malloc(buflen, M_TEMP, M_WAITOK);
2717 pwd = pwd_get_smr();
2718 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, false, 0);
2719 VFS_SMR_ASSERT_NOT_ENTERED();
2721 pwd = pwd_hold(curthread);
2722 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
2733 * This function is similar to vn_fullpath, but it attempts to lookup the
2734 * pathname relative to the global root mount point. This is required for the
2735 * auditing sub-system, as audited pathnames must be absolute, relative to the
2736 * global root mount point.
2739 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
2745 if (__predict_false(vp == NULL))
2747 buflen = MAXPATHLEN;
2748 buf = malloc(buflen, M_TEMP, M_WAITOK);
2750 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, false, 0);
2751 VFS_SMR_ASSERT_NOT_ENTERED();
2753 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
2762 static struct namecache *
2763 vn_dd_from_dst(struct vnode *vp)
2765 struct namecache *ncp;
2767 cache_assert_vnode_locked(vp);
2768 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
2769 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2776 vn_vptocnp(struct vnode **vp, struct ucred *cred, char *buf, size_t *buflen)
2779 struct namecache *ncp;
2783 vlp = VP2VNODELOCK(*vp);
2785 ncp = (*vp)->v_cache_dd;
2786 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
2787 KASSERT(ncp == vn_dd_from_dst(*vp),
2788 ("%s: mismatch for dd entry (%p != %p)", __func__,
2789 ncp, vn_dd_from_dst(*vp)));
2791 ncp = vn_dd_from_dst(*vp);
2794 if (*buflen < ncp->nc_nlen) {
2797 counter_u64_add(numfullpathfail4, 1);
2799 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2803 *buflen -= ncp->nc_nlen;
2804 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2805 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2814 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2817 vn_lock(*vp, LK_SHARED | LK_RETRY);
2818 error = VOP_VPTOCNP(*vp, &dvp, cred, buf, buflen);
2821 counter_u64_add(numfullpathfail2, 1);
2822 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2827 if (VN_IS_DOOMED(dvp)) {
2828 /* forced unmount */
2831 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2835 * *vp has its use count incremented still.
2842 * Resolve a directory to a pathname.
2844 * The name of the directory can always be found in the namecache or fetched
2845 * from the filesystem. There is also guaranteed to be only one parent, meaning
2846 * we can just follow vnodes up until we find the root.
2848 * The vnode must be referenced.
2851 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
2852 size_t *len, bool slash_prefixed, size_t addend)
2854 #ifdef KDTRACE_HOOKS
2855 struct vnode *startvp = vp;
2861 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
2862 VNPASS(vp->v_usecount > 0, vp);
2866 if (!slash_prefixed) {
2874 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
2875 counter_u64_add(numfullpathcalls, 1);
2876 while (vp != rdir && vp != rootvnode) {
2878 * The vp vnode must be already fully constructed,
2879 * since it is either found in namecache or obtained
2880 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
2881 * without obtaining the vnode lock.
2883 if ((vp->v_vflag & VV_ROOT) != 0) {
2884 vn_lock(vp, LK_RETRY | LK_SHARED);
2887 * With the vnode locked, check for races with
2888 * unmount, forced or not. Note that we
2889 * already verified that vp is not equal to
2890 * the root vnode, which means that
2891 * mnt_vnodecovered can be NULL only for the
2894 if (VN_IS_DOOMED(vp) ||
2895 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
2896 vp1->v_mountedhere != vp->v_mount) {
2899 SDT_PROBE3(vfs, namecache, fullpath, return,
2909 if (vp->v_type != VDIR) {
2911 counter_u64_add(numfullpathfail1, 1);
2913 SDT_PROBE3(vfs, namecache, fullpath, return,
2917 error = vn_vptocnp(&vp, curthread->td_ucred, buf, &buflen);
2923 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2927 buf[--buflen] = '/';
2928 slash_prefixed = true;
2932 if (!slash_prefixed) {
2935 counter_u64_add(numfullpathfail4, 1);
2936 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
2940 buf[--buflen] = '/';
2942 counter_u64_add(numfullpathfound, 1);
2945 *retbuf = buf + buflen;
2946 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
2953 * Resolve an arbitrary vnode to a pathname.
2956 * - hardlinks are not tracked, thus if the vnode is not a directory this can
2957 * resolve to a different path than the one used to find it
2958 * - namecache is not mandatory, meaning names are not guaranteed to be added
2959 * (in which case resolving fails)
2961 static void __inline
2962 cache_rev_failed_impl(int *reason, int line)
2967 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
2970 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
2971 char **retbuf, size_t *buflen, bool slash_prefixed, size_t addend)
2973 #ifdef KDTRACE_HOOKS
2974 struct vnode *startvp = vp;
2978 struct namecache *ncp;
2982 #ifdef KDTRACE_HOOKS
2985 seqc_t vp_seqc, tvp_seqc;
2988 VFS_SMR_ASSERT_ENTERED();
2990 if (!cache_fast_revlookup) {
2995 orig_buflen = *buflen;
2997 if (!slash_prefixed) {
2998 MPASS(*buflen >= 2);
3000 buf[*buflen] = '\0';
3003 if (vp == rdir || vp == rootvnode) {
3004 if (!slash_prefixed) {
3011 #ifdef KDTRACE_HOOKS
3015 ncp = NULL; /* for sdt probe down below */
3016 vp_seqc = vn_seqc_read_any(vp);
3017 if (seqc_in_modify(vp_seqc)) {
3018 cache_rev_failed(&reason);
3023 #ifdef KDTRACE_HOOKS
3026 if ((vp->v_vflag & VV_ROOT) != 0) {
3027 mp = atomic_load_ptr(&vp->v_mount);
3029 cache_rev_failed(&reason);
3032 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3033 tvp_seqc = vn_seqc_read_any(tvp);
3034 if (seqc_in_modify(tvp_seqc)) {
3035 cache_rev_failed(&reason);
3038 if (!vn_seqc_consistent(vp, vp_seqc)) {
3039 cache_rev_failed(&reason);
3046 ncp = atomic_load_ptr(&vp->v_cache_dd);
3048 cache_rev_failed(&reason);
3051 nc_flag = atomic_load_char(&ncp->nc_flag);
3052 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3053 cache_rev_failed(&reason);
3056 if (!cache_ncp_canuse(ncp)) {
3057 cache_rev_failed(&reason);
3060 if (ncp->nc_nlen >= *buflen) {
3061 cache_rev_failed(&reason);
3065 *buflen -= ncp->nc_nlen;
3066 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3070 tvp_seqc = vn_seqc_read_any(tvp);
3071 if (seqc_in_modify(tvp_seqc)) {
3072 cache_rev_failed(&reason);
3075 if (!vn_seqc_consistent(vp, vp_seqc)) {
3076 cache_rev_failed(&reason);
3081 if (vp == rdir || vp == rootvnode)
3086 *retbuf = buf + *buflen;
3087 *buflen = orig_buflen - *buflen + addend;
3088 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3092 *buflen = orig_buflen;
3093 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3099 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3103 bool slash_prefixed;
3109 orig_buflen = *buflen;
3112 slash_prefixed = false;
3113 if (vp->v_type != VDIR) {
3115 buf[*buflen] = '\0';
3116 error = vn_vptocnp(&vp, curthread->td_ucred, buf, buflen);
3125 slash_prefixed = true;
3128 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, slash_prefixed,
3129 orig_buflen - *buflen));
3133 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3135 * Since the namecache does not track handlings, the caller is expected to first
3136 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3138 * Then we have 2 cases:
3139 * - if the found vnode is a directory, the path can be constructed just by
3140 * fullowing names up the chain
3141 * - otherwise we populate the buffer with the saved name and start resolving
3145 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3150 struct componentname *cnp;
3154 bool slash_prefixed;
3159 if (*buflen > MAXPATHLEN)
3160 *buflen = MAXPATHLEN;
3162 slash_prefixed = false;
3164 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3169 * Check for VBAD to work around the vp_crossmp bug in lookup().
3171 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3172 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3173 * If the type is VDIR (like in this very case) we can skip looking
3174 * at ni_dvp in the first place. However, since vnodes get passed here
3175 * unlocked the target may transition to doomed state (type == VBAD)
3176 * before we get to evaluate the condition. If this happens, we will
3177 * populate part of the buffer and descend to vn_fullpath_dir with
3178 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3180 * This should be atomic_load(&vp->v_type) but it is ilegal to take
3181 * an address of a bit field, even if said field is sized to char.
3182 * Work around the problem by reading the value into a full-sized enum
3183 * and then re-reading it with atomic_load which will still prevent
3184 * the compiler from re-reading down the road.
3187 type = atomic_load_int(&type);
3194 addend = cnp->cn_namelen + 2;
3195 if (*buflen < addend) {
3200 tmpbuf = buf + *buflen;
3202 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3203 tmpbuf[addend - 1] = '\0';
3204 slash_prefixed = true;
3209 pwd = pwd_get_smr();
3210 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3211 slash_prefixed, addend);
3212 VFS_SMR_ASSERT_NOT_ENTERED();
3214 pwd = pwd_hold(curthread);
3216 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3217 slash_prefixed, addend);
3232 vn_dir_dd_ino(struct vnode *vp)
3234 struct namecache *ncp;
3239 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3240 vlp = VP2VNODELOCK(vp);
3242 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3243 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3246 vs = vget_prep(ddvp);
3248 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3257 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3259 struct namecache *ncp;
3263 vlp = VP2VNODELOCK(vp);
3265 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3266 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3272 l = min(ncp->nc_nlen, buflen - 1);
3273 memcpy(buf, ncp->nc_name, l);
3280 * This function updates path string to vnode's full global path
3281 * and checks the size of the new path string against the pathlen argument.
3283 * Requires a locked, referenced vnode.
3284 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3286 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3287 * because it falls back to the ".." lookup if the namecache lookup fails.
3290 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3293 struct nameidata nd;
3298 ASSERT_VOP_ELOCKED(vp, __func__);
3300 /* Construct global filesystem path from vp. */
3302 error = vn_fullpath_global(vp, &rpath, &fbuf);
3309 if (strlen(rpath) >= pathlen) {
3311 error = ENAMETOOLONG;
3316 * Re-lookup the vnode by path to detect a possible rename.
3317 * As a side effect, the vnode is relocked.
3318 * If vnode was renamed, return ENOENT.
3320 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3321 UIO_SYSSPACE, path, td);
3327 NDFREE(&nd, NDF_ONLY_PNBUF);
3331 strcpy(path, rpath);
3344 db_print_vpath(struct vnode *vp)
3347 while (vp != NULL) {
3348 db_printf("%p: ", vp);
3349 if (vp == rootvnode) {
3353 if (vp->v_vflag & VV_ROOT) {
3354 db_printf("<mount point>");
3355 vp = vp->v_mount->mnt_vnodecovered;
3357 struct namecache *ncp;
3361 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3364 for (i = 0; i < ncp->nc_nlen; i++)
3365 db_printf("%c", *ncn++);
3378 DB_SHOW_COMMAND(vpath, db_show_vpath)
3383 db_printf("usage: show vpath <struct vnode *>\n");
3387 vp = (struct vnode *)addr;
3393 static bool __read_frequently cache_fast_lookup = true;
3394 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_lookup, CTLFLAG_RW,
3395 &cache_fast_lookup, 0, "");
3397 #define CACHE_FPL_FAILED -2020
3400 cache_fpl_cleanup_cnp(struct componentname *cnp)
3403 uma_zfree(namei_zone, cnp->cn_pnbuf);
3405 cnp->cn_pnbuf = NULL;
3406 cnp->cn_nameptr = NULL;
3411 cache_fpl_handle_root(struct nameidata *ndp, struct vnode **dpp)
3413 struct componentname *cnp;
3416 while (*(cnp->cn_nameptr) == '/') {
3421 *dpp = ndp->ni_rootdir;
3425 * Components of nameidata (or objects it can point to) which may
3426 * need restoring in case fast path lookup fails.
3428 struct nameidata_saved {
3436 struct nameidata *ndp;
3437 struct componentname *cnp;
3443 struct nameidata_saved snd;
3445 enum cache_fpl_status status:8;
3451 cache_fpl_checkpoint(struct cache_fpl *fpl, struct nameidata_saved *snd)
3454 snd->cn_flags = fpl->ndp->ni_cnd.cn_flags;
3455 snd->cn_namelen = fpl->ndp->ni_cnd.cn_namelen;
3456 snd->cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3457 snd->ni_pathlen = fpl->ndp->ni_pathlen;
3461 cache_fpl_restore(struct cache_fpl *fpl, struct nameidata_saved *snd)
3464 fpl->ndp->ni_cnd.cn_flags = snd->cn_flags;
3465 fpl->ndp->ni_cnd.cn_namelen = snd->cn_namelen;
3466 fpl->ndp->ni_cnd.cn_nameptr = snd->cn_nameptr;
3467 fpl->ndp->ni_pathlen = snd->ni_pathlen;
3471 #define cache_fpl_smr_assert_entered(fpl) ({ \
3472 struct cache_fpl *_fpl = (fpl); \
3473 MPASS(_fpl->in_smr == true); \
3474 VFS_SMR_ASSERT_ENTERED(); \
3476 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
3477 struct cache_fpl *_fpl = (fpl); \
3478 MPASS(_fpl->in_smr == false); \
3479 VFS_SMR_ASSERT_NOT_ENTERED(); \
3482 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3483 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3486 #define cache_fpl_smr_enter_initial(fpl) ({ \
3487 struct cache_fpl *_fpl = (fpl); \
3489 _fpl->in_smr = true; \
3492 #define cache_fpl_smr_enter(fpl) ({ \
3493 struct cache_fpl *_fpl = (fpl); \
3494 MPASS(_fpl->in_smr == false); \
3496 _fpl->in_smr = true; \
3499 #define cache_fpl_smr_exit(fpl) ({ \
3500 struct cache_fpl *_fpl = (fpl); \
3501 MPASS(_fpl->in_smr == true); \
3503 _fpl->in_smr = false; \
3507 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3510 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3511 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3512 ("%s: converting to abort from %d at %d, set at %d\n",
3513 __func__, fpl->status, line, fpl->line));
3515 fpl->status = CACHE_FPL_STATUS_ABORTED;
3517 return (CACHE_FPL_FAILED);
3520 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
3523 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3526 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3527 ("%s: setting to partial at %d, but already set to %d at %d\n",
3528 __func__, line, fpl->status, fpl->line));
3529 cache_fpl_smr_assert_entered(fpl);
3530 fpl->status = CACHE_FPL_STATUS_PARTIAL;
3532 return (CACHE_FPL_FAILED);
3535 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
3538 cache_fpl_handled_impl(struct cache_fpl *fpl, int error, int line)
3541 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3542 ("%s: setting to handled at %d, but already set to %d at %d\n",
3543 __func__, line, fpl->status, fpl->line));
3544 cache_fpl_smr_assert_not_entered(fpl);
3545 MPASS(error != CACHE_FPL_FAILED);
3546 fpl->status = CACHE_FPL_STATUS_HANDLED;
3551 #define cache_fpl_handled(x, e) cache_fpl_handled_impl((x), (e), __LINE__)
3553 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3554 (LOCKLEAF | LOCKPARENT | WANTPARENT | NOCACHE | FOLLOW | LOCKSHARED | SAVENAME | \
3555 SAVESTART | WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
3557 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3558 (ISDOTDOT | MAKEENTRY | ISLASTCN)
3560 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3561 "supported and internal flags overlap");
3564 cache_fpl_islastcn(struct nameidata *ndp)
3567 return (*ndp->ni_next == 0);
3571 cache_fpl_isdotdot(struct componentname *cnp)
3574 if (cnp->cn_namelen == 2 &&
3575 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3581 cache_can_fplookup(struct cache_fpl *fpl)
3583 struct nameidata *ndp;
3584 struct componentname *cnp;
3589 td = cnp->cn_thread;
3591 if (!cache_fast_lookup) {
3592 cache_fpl_aborted(fpl);
3596 if (mac_vnode_check_lookup_enabled()) {
3597 cache_fpl_aborted(fpl);
3601 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3602 cache_fpl_aborted(fpl);
3605 if (IN_CAPABILITY_MODE(td)) {
3606 cache_fpl_aborted(fpl);
3609 if (AUDITING_TD(td)) {
3610 cache_fpl_aborted(fpl);
3613 if (ndp->ni_startdir != NULL) {
3614 cache_fpl_aborted(fpl);
3621 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
3623 struct nameidata *ndp;
3628 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
3629 if (__predict_false(error != 0)) {
3630 cache_fpl_smr_exit(fpl);
3631 return (cache_fpl_aborted(fpl));
3633 fpl->fsearch = fsearch;
3638 cache_fplookup_vnode_supported(struct vnode *vp)
3641 return (vp->v_type != VLNK);
3644 static int __noinline
3645 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
3648 struct componentname *cnp;
3654 cache_fpl_smr_exit(fpl);
3655 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
3656 return (cache_fpl_handled(fpl, ENOENT));
3658 return (cache_fpl_aborted(fpl));
3662 * The target vnode is not supported, prepare for the slow path to take over.
3664 static int __noinline
3665 cache_fplookup_partial_setup(struct cache_fpl *fpl)
3667 struct nameidata *ndp;
3668 struct componentname *cnp;
3678 dvp_seqc = fpl->dvp_seqc;
3680 if (!pwd_hold_smr(pwd)) {
3681 cache_fpl_smr_exit(fpl);
3682 return (cache_fpl_aborted(fpl));
3685 dvs = vget_prep_smr(dvp);
3686 cache_fpl_smr_exit(fpl);
3687 if (__predict_false(dvs == VGET_NONE)) {
3689 return (cache_fpl_aborted(fpl));
3692 vget_finish_ref(dvp, dvs);
3693 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3696 return (cache_fpl_aborted(fpl));
3699 cache_fpl_restore(fpl, &fpl->snd);
3701 ndp->ni_startdir = dvp;
3702 cnp->cn_flags |= MAKEENTRY;
3703 if (cache_fpl_islastcn(ndp))
3704 cnp->cn_flags |= ISLASTCN;
3705 if (cache_fpl_isdotdot(cnp))
3706 cnp->cn_flags |= ISDOTDOT;
3712 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
3714 struct componentname *cnp;
3721 tvp_seqc = fpl->tvp_seqc;
3723 if ((cnp->cn_flags & LOCKLEAF) != 0) {
3724 lkflags = LK_SHARED;
3725 if ((cnp->cn_flags & LOCKSHARED) == 0)
3726 lkflags = LK_EXCLUSIVE;
3727 error = vget_finish(tvp, lkflags, tvs);
3728 if (__predict_false(error != 0)) {
3729 return (cache_fpl_aborted(fpl));
3732 vget_finish_ref(tvp, tvs);
3735 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
3736 if ((cnp->cn_flags & LOCKLEAF) != 0)
3740 return (cache_fpl_aborted(fpl));
3743 return (cache_fpl_handled(fpl, 0));
3747 * They want to possibly modify the state of the namecache.
3749 * Don't try to match the API contract, just leave.
3750 * TODO: this leaves scalability on the table
3753 cache_fplookup_final_modifying(struct cache_fpl *fpl)
3755 struct componentname *cnp;
3758 MPASS(cnp->cn_nameiop != LOOKUP);
3759 return (cache_fpl_partial(fpl));
3762 static int __noinline
3763 cache_fplookup_final_withparent(struct cache_fpl *fpl)
3765 struct componentname *cnp;
3766 enum vgetstate dvs, tvs;
3767 struct vnode *dvp, *tvp;
3773 dvp_seqc = fpl->dvp_seqc;
3776 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
3779 * This is less efficient than it can be for simplicity.
3781 dvs = vget_prep_smr(dvp);
3782 if (__predict_false(dvs == VGET_NONE)) {
3783 return (cache_fpl_aborted(fpl));
3785 tvs = vget_prep_smr(tvp);
3786 if (__predict_false(tvs == VGET_NONE)) {
3787 cache_fpl_smr_exit(fpl);
3788 vget_abort(dvp, dvs);
3789 return (cache_fpl_aborted(fpl));
3792 cache_fpl_smr_exit(fpl);
3794 if ((cnp->cn_flags & LOCKPARENT) != 0) {
3795 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
3796 if (__predict_false(error != 0)) {
3797 vget_abort(tvp, tvs);
3798 return (cache_fpl_aborted(fpl));
3801 vget_finish_ref(dvp, dvs);
3804 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3805 vget_abort(tvp, tvs);
3806 if ((cnp->cn_flags & LOCKPARENT) != 0)
3810 return (cache_fpl_aborted(fpl));
3813 error = cache_fplookup_final_child(fpl, tvs);
3814 if (__predict_false(error != 0)) {
3815 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
3816 if ((cnp->cn_flags & LOCKPARENT) != 0)
3823 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
3828 cache_fplookup_final(struct cache_fpl *fpl)
3830 struct componentname *cnp;
3832 struct vnode *dvp, *tvp;
3837 dvp_seqc = fpl->dvp_seqc;
3840 VNPASS(cache_fplookup_vnode_supported(dvp), dvp);
3842 if (cnp->cn_nameiop != LOOKUP) {
3843 return (cache_fplookup_final_modifying(fpl));
3846 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
3847 return (cache_fplookup_final_withparent(fpl));
3849 tvs = vget_prep_smr(tvp);
3850 if (__predict_false(tvs == VGET_NONE)) {
3851 return (cache_fpl_partial(fpl));
3854 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3855 cache_fpl_smr_exit(fpl);
3856 vget_abort(tvp, tvs);
3857 return (cache_fpl_aborted(fpl));
3860 cache_fpl_smr_exit(fpl);
3861 return (cache_fplookup_final_child(fpl, tvs));
3864 static int __noinline
3865 cache_fplookup_dot(struct cache_fpl *fpl)
3872 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3873 if (seqc_in_modify(fpl->tvp_seqc)) {
3874 return (cache_fpl_aborted(fpl));
3877 counter_u64_add(dothits, 1);
3878 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", dvp);
3883 static int __noinline
3884 cache_fplookup_dotdot(struct cache_fpl *fpl)
3886 struct nameidata *ndp;
3887 struct componentname *cnp;
3888 struct namecache *ncp;
3898 * XXX this is racy the same way regular lookup is
3900 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
3902 if (dvp == pr->pr_root)
3905 if (dvp == ndp->ni_rootdir ||
3906 dvp == ndp->ni_topdir ||
3910 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3911 if (seqc_in_modify(fpl->tvp_seqc)) {
3912 return (cache_fpl_aborted(fpl));
3917 if ((dvp->v_vflag & VV_ROOT) != 0) {
3920 * The opposite of climb mount is needed here.
3922 return (cache_fpl_aborted(fpl));
3925 ncp = atomic_load_ptr(&dvp->v_cache_dd);
3927 return (cache_fpl_aborted(fpl));
3930 nc_flag = atomic_load_char(&ncp->nc_flag);
3931 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3932 if ((nc_flag & NCF_NEGATIVE) != 0)
3933 return (cache_fpl_aborted(fpl));
3934 fpl->tvp = ncp->nc_vp;
3936 fpl->tvp = ncp->nc_dvp;
3939 if (__predict_false(!cache_ncp_canuse(ncp))) {
3940 return (cache_fpl_aborted(fpl));
3943 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
3944 if (seqc_in_modify(fpl->tvp_seqc)) {
3945 return (cache_fpl_partial(fpl));
3948 counter_u64_add(dotdothits, 1);
3952 static int __noinline
3953 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
3958 nc_flag = atomic_load_char(&ncp->nc_flag);
3959 MPASS((nc_flag & NCF_NEGATIVE) != 0);
3961 * If they want to create an entry we need to replace this one.
3963 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
3966 * This should call something similar to
3967 * cache_fplookup_final_modifying.
3969 return (cache_fpl_partial(fpl));
3971 neg_promote = cache_neg_hit_prep(ncp);
3972 if (__predict_false(!cache_ncp_canuse(ncp))) {
3973 cache_neg_hit_abort(ncp);
3974 return (cache_fpl_partial(fpl));
3976 if (__predict_false((nc_flag & NCF_WHITE) != 0)) {
3977 cache_neg_hit_abort(ncp);
3978 return (cache_fpl_partial(fpl));
3981 return (cache_fplookup_negative_promote(fpl, ncp, hash));
3983 cache_neg_hit_finish(ncp);
3984 cache_fpl_smr_exit(fpl);
3985 return (cache_fpl_handled(fpl, ENOENT));
3989 cache_fplookup_next(struct cache_fpl *fpl)
3991 struct componentname *cnp;
3992 struct namecache *ncp;
3993 struct vnode *dvp, *tvp;
4000 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.')) {
4001 return (cache_fplookup_dot(fpl));
4004 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
4006 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
4007 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
4008 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
4013 * If there is no entry we have to punt to the slow path to perform
4014 * actual lookup. Should there be nothing with this name a negative
4015 * entry will be created.
4017 if (__predict_false(ncp == NULL)) {
4018 return (cache_fpl_partial(fpl));
4021 tvp = atomic_load_ptr(&ncp->nc_vp);
4022 nc_flag = atomic_load_char(&ncp->nc_flag);
4023 if ((nc_flag & NCF_NEGATIVE) != 0) {
4024 return (cache_fplookup_neg(fpl, ncp, hash));
4027 if (__predict_false(!cache_ncp_canuse(ncp))) {
4028 return (cache_fpl_partial(fpl));
4032 fpl->tvp_seqc = vn_seqc_read_any(tvp);
4033 if (seqc_in_modify(fpl->tvp_seqc)) {
4034 return (cache_fpl_partial(fpl));
4037 if (!cache_fplookup_vnode_supported(tvp)) {
4038 return (cache_fpl_partial(fpl));
4041 counter_u64_add(numposhits, 1);
4042 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
4047 cache_fplookup_mp_supported(struct mount *mp)
4052 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4058 * Walk up the mount stack (if any).
4060 * Correctness is provided in the following ways:
4061 * - all vnodes are protected from freeing with SMR
4062 * - struct mount objects are type stable making them always safe to access
4063 * - stability of the particular mount is provided by busying it
4064 * - relationship between the vnode which is mounted on and the mount is
4065 * verified with the vnode sequence counter after busying
4066 * - association between root vnode of the mount and the mount is protected
4069 * From that point on we can read the sequence counter of the root vnode
4070 * and get the next mount on the stack (if any) using the same protection.
4072 * By the end of successful walk we are guaranteed the reached state was
4073 * indeed present at least at some point which matches the regular lookup.
4075 static int __noinline
4076 cache_fplookup_climb_mount(struct cache_fpl *fpl)
4078 struct mount *mp, *prev_mp;
4083 vp_seqc = fpl->tvp_seqc;
4085 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
4086 mp = atomic_load_ptr(&vp->v_mountedhere);
4092 if (!vfs_op_thread_enter_crit(mp)) {
4093 if (prev_mp != NULL)
4094 vfs_op_thread_exit_crit(prev_mp);
4095 return (cache_fpl_partial(fpl));
4097 if (prev_mp != NULL)
4098 vfs_op_thread_exit_crit(prev_mp);
4099 if (!vn_seqc_consistent(vp, vp_seqc)) {
4100 vfs_op_thread_exit_crit(mp);
4101 return (cache_fpl_partial(fpl));
4103 if (!cache_fplookup_mp_supported(mp)) {
4104 vfs_op_thread_exit_crit(mp);
4105 return (cache_fpl_partial(fpl));
4107 vp = atomic_load_ptr(&mp->mnt_rootvnode);
4108 if (vp == NULL || VN_IS_DOOMED(vp)) {
4109 vfs_op_thread_exit_crit(mp);
4110 return (cache_fpl_partial(fpl));
4112 vp_seqc = vn_seqc_read_any(vp);
4113 if (seqc_in_modify(vp_seqc)) {
4114 vfs_op_thread_exit_crit(mp);
4115 return (cache_fpl_partial(fpl));
4118 mp = atomic_load_ptr(&vp->v_mountedhere);
4123 vfs_op_thread_exit_crit(prev_mp);
4125 fpl->tvp_seqc = vp_seqc;
4130 cache_fplookup_need_climb_mount(struct cache_fpl *fpl)
4138 * Hack: while this is a union, the pointer tends to be NULL so save on
4141 mp = atomic_load_ptr(&vp->v_mountedhere);
4144 if (vp->v_type == VDIR)
4152 * The code was originally copy-pasted from regular lookup and despite
4153 * clean ups leaves performance on the table. Any modifications here
4154 * must take into account that in case off fallback the resulting
4155 * nameidata state has to be compatible with the original.
4158 cache_fplookup_parse(struct cache_fpl *fpl)
4160 struct nameidata *ndp;
4161 struct componentname *cnp;
4168 * Search a new directory.
4170 * The last component of the filename is left accessible via
4171 * cnp->cn_nameptr for callers that need the name. Callers needing
4172 * the name set the SAVENAME flag. When done, they assume
4173 * responsibility for freeing the pathname buffer.
4175 for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
4177 cnp->cn_namelen = cp - cnp->cn_nameptr;
4178 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4179 cache_fpl_smr_exit(fpl);
4180 return (cache_fpl_handled(fpl, ENAMETOOLONG));
4182 ndp->ni_pathlen -= cnp->cn_namelen;
4183 KASSERT(ndp->ni_pathlen <= PATH_MAX,
4184 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
4188 * Replace multiple slashes by a single slash and trailing slashes
4189 * by a null. This must be done before VOP_LOOKUP() because some
4190 * fs's don't know about trailing slashes. Remember if there were
4191 * trailing slashes to handle symlinks, existing non-directories
4192 * and non-existing files that won't be directories specially later.
4194 while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
4200 * Regular lookup performs the following:
4201 * *ndp->ni_next = '\0';
4202 * cnp->cn_flags |= TRAILINGSLASH;
4204 * Which is problematic since it modifies data read
4205 * from userspace. Then if fast path lookup was to
4206 * abort we would have to either restore it or convey
4207 * the flag. Since this is a corner case just ignore
4208 * it for simplicity.
4210 return (cache_fpl_partial(fpl));
4216 * Check for degenerate name (e.g. / or "")
4217 * which is a way of talking about a directory,
4218 * e.g. like "/." or ".".
4221 * Another corner case handled by the regular lookup
4223 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
4224 return (cache_fpl_partial(fpl));
4230 cache_fplookup_parse_advance(struct cache_fpl *fpl)
4232 struct nameidata *ndp;
4233 struct componentname *cnp;
4238 cnp->cn_nameptr = ndp->ni_next;
4239 while (*cnp->cn_nameptr == '/') {
4246 * See the API contract for VOP_FPLOOKUP_VEXEC.
4248 static int __noinline
4249 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
4251 struct componentname *cnp;
4257 dvp_seqc = fpl->dvp_seqc;
4260 * Hack: they may be looking up foo/bar, where foo is a
4261 * regular file. In such a case we need to turn ENOTDIR,
4262 * but we may happen to get here with a different error.
4264 if (dvp->v_type != VDIR) {
4266 * The check here is predominantly to catch
4267 * EOPNOTSUPP from dead_vnodeops. If the vnode
4268 * gets doomed past this point it is going to
4269 * fail seqc verification.
4271 if (VN_IS_DOOMED(dvp)) {
4272 return (cache_fpl_aborted(fpl));
4278 * Hack: handle O_SEARCH.
4280 * Open Group Base Specifications Issue 7, 2018 edition states:
4281 * If the access mode of the open file description associated with the
4282 * file descriptor is not O_SEARCH, the function shall check whether
4283 * directory searches are permitted using the current permissions of
4284 * the directory underlying the file descriptor. If the access mode is
4285 * O_SEARCH, the function shall not perform the check.
4287 * Regular lookup tests for the NOEXECCHECK flag for every path
4288 * component to decide whether to do the permission check. However,
4289 * since most lookups never have the flag (and when they do it is only
4290 * present for the first path component), lockless lookup only acts on
4291 * it if there is a permission problem. Here the flag is represented
4292 * with a boolean so that we don't have to clear it on the way out.
4294 * For simplicity this always aborts.
4295 * TODO: check if this is the first lookup and ignore the permission
4296 * problem. Note the flag has to survive fallback (if it happens to be
4300 return (cache_fpl_aborted(fpl));
4305 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4306 error = cache_fpl_aborted(fpl);
4308 cache_fpl_partial(fpl);
4312 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4313 error = cache_fpl_aborted(fpl);
4315 cache_fpl_smr_exit(fpl);
4316 cache_fpl_handled(fpl, error);
4324 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
4326 struct nameidata *ndp;
4327 struct componentname *cnp;
4331 error = CACHE_FPL_FAILED;
4335 cache_fpl_checkpoint(fpl, &fpl->snd);
4338 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
4339 if (seqc_in_modify(fpl->dvp_seqc)) {
4340 cache_fpl_aborted(fpl);
4343 mp = atomic_load_ptr(&fpl->dvp->v_mount);
4344 if (!cache_fplookup_mp_supported(mp)) {
4345 cache_fpl_aborted(fpl);
4349 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4352 error = cache_fplookup_parse(fpl);
4353 if (__predict_false(error != 0)) {
4357 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4359 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
4360 if (__predict_false(error != 0)) {
4361 error = cache_fplookup_failed_vexec(fpl, error);
4365 if (__predict_false(cache_fpl_isdotdot(cnp))) {
4366 error = cache_fplookup_dotdot(fpl);
4367 if (__predict_false(error != 0)) {
4371 error = cache_fplookup_next(fpl);
4372 if (__predict_false(error != 0)) {
4376 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4378 if (cache_fplookup_need_climb_mount(fpl)) {
4379 error = cache_fplookup_climb_mount(fpl);
4380 if (__predict_false(error != 0)) {
4386 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4388 if (cache_fpl_islastcn(ndp)) {
4389 error = cache_fplookup_final(fpl);
4393 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
4394 error = cache_fpl_aborted(fpl);
4398 fpl->dvp = fpl->tvp;
4399 fpl->dvp_seqc = fpl->tvp_seqc;
4401 cache_fplookup_parse_advance(fpl);
4402 cache_fpl_checkpoint(fpl, &fpl->snd);
4405 switch (fpl->status) {
4406 case CACHE_FPL_STATUS_UNSET:
4407 __assert_unreachable();
4409 case CACHE_FPL_STATUS_PARTIAL:
4410 cache_fpl_smr_assert_entered(fpl);
4411 return (cache_fplookup_partial_setup(fpl));
4412 case CACHE_FPL_STATUS_ABORTED:
4414 cache_fpl_smr_exit(fpl);
4415 return (CACHE_FPL_FAILED);
4416 case CACHE_FPL_STATUS_HANDLED:
4417 MPASS(error != CACHE_FPL_FAILED);
4418 cache_fpl_smr_assert_not_entered(fpl);
4419 if (__predict_false(error != 0)) {
4422 cache_fpl_cleanup_cnp(cnp);
4425 ndp->ni_dvp = fpl->dvp;
4426 ndp->ni_vp = fpl->tvp;
4427 if (cnp->cn_flags & SAVENAME)
4428 cnp->cn_flags |= HASBUF;
4430 cache_fpl_cleanup_cnp(cnp);
4436 * Fast path lookup protected with SMR and sequence counters.
4438 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
4440 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
4443 * Traditional vnode lookup conceptually looks like this:
4449 * vn_unlock(current);
4456 * Each jump to the next vnode is safe memory-wise and atomic with respect to
4457 * any modifications thanks to holding respective locks.
4459 * The same guarantee can be provided with a combination of safe memory
4460 * reclamation and sequence counters instead. If all operations which affect
4461 * the relationship between the current vnode and the one we are looking for
4462 * also modify the counter, we can verify whether all the conditions held as
4463 * we made the jump. This includes things like permissions, mount points etc.
4464 * Counter modification is provided by enclosing relevant places in
4465 * vn_seqc_write_begin()/end() calls.
4467 * Thus this translates to:
4470 * dvp_seqc = seqc_read_any(dvp);
4471 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
4475 * tvp_seqc = seqc_read_any(tvp);
4476 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
4478 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
4480 * dvp = tvp; // we know nothing of importance has changed
4481 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
4485 * vget(); // secure the vnode
4486 * if (!seqc_consistent(tvp, tvp_seqc) // final check
4488 * // at this point we know nothing has changed for any parent<->child pair
4489 * // as they were crossed during the lookup, meaning we matched the guarantee
4490 * // of the locked variant
4493 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
4494 * - they are called while within vfs_smr protection which they must never exit
4495 * - EAGAIN can be returned to denote checking could not be performed, it is
4496 * always valid to return it
4497 * - if the sequence counter has not changed the result must be valid
4498 * - if the sequence counter has changed both false positives and false negatives
4499 * are permitted (since the result will be rejected later)
4500 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
4502 * Caveats to watch out for:
4503 * - vnodes are passed unlocked and unreferenced with nothing stopping
4504 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
4505 * to use atomic_load_ptr to fetch it.
4506 * - the aforementioned object can also get freed, meaning absent other means it
4507 * should be protected with vfs_smr
4508 * - either safely checking permissions as they are modified or guaranteeing
4509 * their stability is left to the routine
4512 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
4515 struct cache_fpl fpl;
4518 struct componentname *cnp;
4519 struct nameidata_saved orig;
4522 MPASS(ndp->ni_lcf == 0);
4524 fpl.status = CACHE_FPL_STATUS_UNSET;
4526 fpl.cnp = &ndp->ni_cnd;
4527 MPASS(curthread == fpl.cnp->cn_thread);
4529 if ((fpl.cnp->cn_flags & SAVESTART) != 0)
4530 MPASS(fpl.cnp->cn_nameiop != LOOKUP);
4532 if (!cache_can_fplookup(&fpl)) {
4533 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4534 *status = fpl.status;
4535 return (EOPNOTSUPP);
4538 cache_fpl_checkpoint(&fpl, &orig);
4540 cache_fpl_smr_enter_initial(&fpl);
4541 fpl.fsearch = false;
4542 pwd = pwd_get_smr();
4544 ndp->ni_rootdir = pwd->pwd_rdir;
4545 ndp->ni_topdir = pwd->pwd_jdir;
4548 cnp->cn_nameptr = cnp->cn_pnbuf;
4549 if (cnp->cn_pnbuf[0] == '/') {
4550 cache_fpl_handle_root(ndp, &dvp);
4552 if (ndp->ni_dirfd == AT_FDCWD) {
4553 dvp = pwd->pwd_cdir;
4555 error = cache_fplookup_dirfd(&fpl, &dvp);
4556 if (__predict_false(error != 0)) {
4562 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
4564 error = cache_fplookup_impl(dvp, &fpl);
4566 cache_fpl_smr_assert_not_entered(&fpl);
4567 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4569 *status = fpl.status;
4570 switch (fpl.status) {
4571 case CACHE_FPL_STATUS_UNSET:
4572 __assert_unreachable();
4574 case CACHE_FPL_STATUS_HANDLED:
4575 SDT_PROBE3(vfs, namei, lookup, return, error,
4576 (error == 0 ? ndp->ni_vp : NULL), true);
4578 case CACHE_FPL_STATUS_PARTIAL:
4581 * Status restored by cache_fplookup_partial_setup.
4584 case CACHE_FPL_STATUS_ABORTED:
4585 cache_fpl_restore(&fpl, &orig);