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>
58 #include <sys/rwlock.h>
63 #include <sys/syscallsubr.h>
64 #include <sys/sysctl.h>
65 #include <sys/sysproto.h>
66 #include <sys/vnode.h>
69 #include <sys/ktrace.h>
72 #include <sys/capsicum.h>
74 #include <security/audit/audit.h>
75 #include <security/mac/mac_framework.h>
83 SDT_PROVIDER_DECLARE(vfs);
84 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
86 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
88 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
89 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
90 "char *", "struct vnode *");
91 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
92 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
93 "struct vnode *", "char *");
94 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
96 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
97 "struct vnode *", "char *");
98 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
100 SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
101 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
102 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
103 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
105 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
107 SDT_PROBE_DEFINE2(vfs, namecache, shrink_negative, done, "struct vnode *",
110 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
111 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
112 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
115 * This structure describes the elements in the cache of recent
116 * names looked up by namei.
121 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
122 "the state must fit in a union with a pointer without growing it");
125 LIST_ENTRY(namecache) nc_src; /* source vnode list */
126 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
127 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
128 struct vnode *nc_dvp; /* vnode of parent of name */
130 struct vnode *nu_vp; /* vnode the name refers to */
131 struct negstate nu_neg;/* negative entry state */
133 u_char nc_flag; /* flag bits */
134 u_char nc_nlen; /* length of name */
135 char nc_name[0]; /* segment name + nul */
139 * struct namecache_ts repeats struct namecache layout up to the
141 * struct namecache_ts is used in place of struct namecache when time(s) need
142 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
143 * both a non-dotdot directory name plus dotdot for the directory's
146 * See below for alignment requirement.
148 struct namecache_ts {
149 struct timespec nc_time; /* timespec provided by fs */
150 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
151 int nc_ticks; /* ticks value when entry was added */
152 struct namecache nc_nc;
156 * At least mips n32 performs 64-bit accesses to timespec as found
157 * in namecache_ts and requires them to be aligned. Since others
158 * may be in the same spot suffer a little bit and enforce the
159 * alignment for everyone. Note this is a nop for 64-bit platforms.
161 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
162 #define CACHE_PATH_CUTOFF 39
164 #define CACHE_ZONE_SMALL_SIZE (sizeof(struct namecache) + CACHE_PATH_CUTOFF + 1)
165 #define CACHE_ZONE_SMALL_TS_SIZE (sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1)
166 #define CACHE_ZONE_LARGE_SIZE (sizeof(struct namecache) + NAME_MAX + 1)
167 #define CACHE_ZONE_LARGE_TS_SIZE (sizeof(struct namecache_ts) + NAME_MAX + 1)
169 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
170 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
171 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
172 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
174 #define nc_vp n_un.nu_vp
175 #define nc_neg n_un.nu_neg
178 * Flags in namecache.nc_flag
180 #define NCF_WHITE 0x01
181 #define NCF_ISDOTDOT 0x02
184 #define NCF_DVDROP 0x10
185 #define NCF_NEGATIVE 0x20
186 #define NCF_INVALID 0x40
190 * Flags in negstate.neg_flag
195 * Mark an entry as invalid.
197 * This is called before it starts getting deconstructed.
200 cache_ncp_invalidate(struct namecache *ncp)
203 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
204 ("%s: entry %p already invalid", __func__, ncp));
205 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
206 atomic_thread_fence_rel();
210 * Check whether the entry can be safely used.
212 * All places which elide locks are supposed to call this after they are
213 * done with reading from an entry.
216 cache_ncp_canuse(struct namecache *ncp)
219 atomic_thread_fence_acq();
220 return ((atomic_load_char(&ncp->nc_flag) & (NCF_INVALID | NCF_WIP)) == 0);
224 * Name caching works as follows:
226 * Names found by directory scans are retained in a cache
227 * for future reference. It is managed LRU, so frequently
228 * used names will hang around. Cache is indexed by hash value
229 * obtained from (dvp, name) where dvp refers to the directory
232 * If it is a "negative" entry, (i.e. for a name that is known NOT to
233 * exist) the vnode pointer will be NULL.
235 * Upon reaching the last segment of a path, if the reference
236 * is for DELETE, or NOCACHE is set (rewrite), and the
237 * name is located in the cache, it will be dropped.
239 * These locks are used (in the order in which they can be taken):
241 * vnodelock mtx vnode lists and v_cache_dd field protection
242 * bucketlock rwlock for access to given set of hash buckets
243 * neglist mtx negative entry LRU management
245 * Additionally, ncneg_shrink_lock mtx is used to have at most one thread
246 * shrinking the LRU list.
248 * It is legal to take multiple vnodelock and bucketlock locks. The locking
249 * order is lower address first. Both are recursive.
251 * "." lookups are lockless.
253 * ".." and vnode -> name lookups require vnodelock.
255 * name -> vnode lookup requires the relevant bucketlock to be held for reading.
257 * Insertions and removals of entries require involved vnodes and bucketlocks
258 * to be write-locked to prevent other threads from seeing the entry.
260 * Some lookups result in removal of the found entry (e.g. getting rid of a
261 * negative entry with the intent to create a positive one), which poses a
262 * problem when multiple threads reach the state. Similarly, two different
263 * threads can purge two different vnodes and try to remove the same name.
265 * If the already held vnode lock is lower than the second required lock, we
266 * can just take the other lock. However, in the opposite case, this could
267 * deadlock. As such, this is resolved by trylocking and if that fails unlocking
268 * the first node, locking everything in order and revalidating the state.
274 * Structures associated with name caching.
276 #define NCHHASH(hash) \
277 (&nchashtbl[(hash) & nchash])
278 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
279 static u_long __read_mostly nchash; /* size of hash table */
280 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
281 "Size of namecache hash table");
282 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
283 SYSCTL_ULONG(_vfs, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
284 "Ratio of negative namecache entries");
285 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
286 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
287 u_int ncsizefactor = 2;
288 SYSCTL_UINT(_vfs, OID_AUTO, ncsizefactor, CTLFLAG_RW, &ncsizefactor, 0,
289 "Size factor for namecache");
290 static u_int __read_mostly ncpurgeminvnodes;
291 SYSCTL_UINT(_vfs, OID_AUTO, ncpurgeminvnodes, CTLFLAG_RW, &ncpurgeminvnodes, 0,
292 "Number of vnodes below which purgevfs ignores the request");
293 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
295 struct nchstats nchstats; /* cache effectiveness statistics */
297 static struct mtx __exclusive_cache_line ncneg_shrink_lock;
301 TAILQ_HEAD(, namecache) nl_list;
302 } __aligned(CACHE_LINE_SIZE);
304 static struct neglist __read_mostly *neglists;
305 static struct neglist ncneg_hot;
306 static u_long numhotneg;
309 #define numneglists (ncneghash + 1)
310 static inline struct neglist *
311 NCP2NEGLIST(struct namecache *ncp)
314 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
317 static inline struct negstate *
318 NCP2NEGSTATE(struct namecache *ncp)
321 MPASS(ncp->nc_flag & NCF_NEGATIVE);
322 return (&ncp->nc_neg);
325 #define numbucketlocks (ncbuckethash + 1)
326 static u_int __read_mostly ncbuckethash;
327 static struct rwlock_padalign __read_mostly *bucketlocks;
328 #define HASH2BUCKETLOCK(hash) \
329 ((struct rwlock *)(&bucketlocks[((hash) & ncbuckethash)]))
331 #define numvnodelocks (ncvnodehash + 1)
332 static u_int __read_mostly ncvnodehash;
333 static struct mtx __read_mostly *vnodelocks;
334 static inline struct mtx *
335 VP2VNODELOCK(struct vnode *vp)
338 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
342 * UMA zones for the VFS cache.
344 * The small cache is used for entries with short names, which are the
345 * most common. The large cache is used for entries which are too big to
346 * fit in the small cache.
348 static uma_zone_t __read_mostly cache_zone_small;
349 static uma_zone_t __read_mostly cache_zone_small_ts;
350 static uma_zone_t __read_mostly cache_zone_large;
351 static uma_zone_t __read_mostly cache_zone_large_ts;
353 static struct namecache *
354 cache_alloc(int len, int ts)
356 struct namecache_ts *ncp_ts;
357 struct namecache *ncp;
359 if (__predict_false(ts)) {
360 if (len <= CACHE_PATH_CUTOFF)
361 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
363 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
364 ncp = &ncp_ts->nc_nc;
366 if (len <= CACHE_PATH_CUTOFF)
367 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
369 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
375 cache_free(struct namecache *ncp)
377 struct namecache_ts *ncp_ts;
381 if ((ncp->nc_flag & NCF_DVDROP) != 0)
383 if (__predict_false(ncp->nc_flag & NCF_TS)) {
384 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
385 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
386 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
388 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
390 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
391 uma_zfree_smr(cache_zone_small, ncp);
393 uma_zfree_smr(cache_zone_large, ncp);
398 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
400 struct namecache_ts *ncp_ts;
402 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
403 (tsp == NULL && ticksp == NULL),
406 if (tsp == NULL && ticksp == NULL)
409 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
411 *tsp = ncp_ts->nc_time;
413 *ticksp = ncp_ts->nc_ticks;
417 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
418 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
419 "VFS namecache enabled");
422 /* Export size information to userland */
423 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
424 sizeof(struct namecache), "sizeof(struct namecache)");
427 * The new name cache statistics
429 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
430 "Name cache statistics");
431 #define STATNODE_ULONG(name, descr) \
432 SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, descr);
433 #define STATNODE_COUNTER(name, descr) \
434 static COUNTER_U64_DEFINE_EARLY(name); \
435 SYSCTL_COUNTER_U64(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, \
437 STATNODE_ULONG(numneg, "Number of negative cache entries");
438 STATNODE_ULONG(numcache, "Number of cache entries");
439 STATNODE_COUNTER(numcachehv, "Number of namecache entries with vnodes held");
440 STATNODE_COUNTER(numdrops, "Number of dropped entries due to reaching the limit");
441 STATNODE_COUNTER(dothits, "Number of '.' hits");
442 STATNODE_COUNTER(dotdothits, "Number of '..' hits");
443 STATNODE_COUNTER(nummiss, "Number of cache misses");
444 STATNODE_COUNTER(nummisszap, "Number of cache misses we do not want to cache");
445 STATNODE_COUNTER(numposzaps,
446 "Number of cache hits (positive) we do not want to cache");
447 STATNODE_COUNTER(numposhits, "Number of cache hits (positive)");
448 STATNODE_COUNTER(numnegzaps,
449 "Number of cache hits (negative) we do not want to cache");
450 STATNODE_COUNTER(numneghits, "Number of cache hits (negative)");
451 /* These count for vn_getcwd(), too. */
452 STATNODE_COUNTER(numfullpathcalls, "Number of fullpath search calls");
453 STATNODE_COUNTER(numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
454 STATNODE_COUNTER(numfullpathfail2,
455 "Number of fullpath search errors (VOP_VPTOCNP failures)");
456 STATNODE_COUNTER(numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
457 STATNODE_COUNTER(numfullpathfound, "Number of successful fullpath calls");
458 STATNODE_COUNTER(zap_and_exit_bucket_relock_success,
459 "Number of successful removals after relocking");
460 static long zap_and_exit_bucket_fail; STATNODE_ULONG(zap_and_exit_bucket_fail,
461 "Number of times zap_and_exit failed to lock");
462 static long zap_and_exit_bucket_fail2; STATNODE_ULONG(zap_and_exit_bucket_fail2,
463 "Number of times zap_and_exit failed to lock");
464 static long cache_lock_vnodes_cel_3_failures;
465 STATNODE_ULONG(cache_lock_vnodes_cel_3_failures,
466 "Number of times 3-way vnode locking failed");
467 STATNODE_ULONG(numhotneg, "Number of hot negative entries");
468 STATNODE_COUNTER(numneg_evicted,
469 "Number of negative entries evicted when adding a new entry");
470 STATNODE_COUNTER(shrinking_skipped,
471 "Number of times shrinking was already in progress");
473 static void cache_zap_locked(struct namecache *ncp);
474 static int vn_fullpath_hardlink(struct thread *td, struct nameidata *ndp, char **retbuf,
475 char **freebuf, size_t *buflen);
476 static int vn_fullpath_any(struct thread *td, struct vnode *vp, struct vnode *rdir,
477 char *buf, char **retbuf, size_t *buflen);
478 static int vn_fullpath_dir(struct thread *td, struct vnode *vp, struct vnode *rdir,
479 char *buf, char **retbuf, size_t *len, bool slash_prefixed, size_t addend);
481 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
483 static int cache_yield;
484 SYSCTL_INT(_vfs_cache, OID_AUTO, yield, CTLFLAG_RD, &cache_yield, 0,
485 "Number of times cache called yield");
487 static void __noinline
488 cache_maybe_yield(void)
491 if (should_yield()) {
493 kern_yield(PRI_USER);
498 cache_assert_vlp_locked(struct mtx *vlp)
502 mtx_assert(vlp, MA_OWNED);
506 cache_assert_vnode_locked(struct vnode *vp)
510 vlp = VP2VNODELOCK(vp);
511 cache_assert_vlp_locked(vlp);
515 * TODO: With the value stored we can do better than computing the hash based
516 * on the address and the choice of FNV should also be revisisted.
519 cache_prehash(struct vnode *vp)
522 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
526 cache_get_hash(char *name, u_char len, struct vnode *dvp)
529 return (fnv_32_buf(name, len, dvp->v_nchash));
532 static inline struct nchashhead *
533 NCP2BUCKET(struct namecache *ncp)
537 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
538 return (NCHHASH(hash));
541 static inline struct rwlock *
542 NCP2BUCKETLOCK(struct namecache *ncp)
546 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
547 return (HASH2BUCKETLOCK(hash));
552 cache_assert_bucket_locked(struct namecache *ncp, int mode)
556 blp = NCP2BUCKETLOCK(ncp);
557 rw_assert(blp, mode);
560 #define cache_assert_bucket_locked(x, y) do { } while (0)
563 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
565 _cache_sort_vnodes(void **p1, void **p2)
569 MPASS(*p1 != NULL || *p2 != NULL);
579 cache_lock_all_buckets(void)
583 for (i = 0; i < numbucketlocks; i++)
584 rw_wlock(&bucketlocks[i]);
588 cache_unlock_all_buckets(void)
592 for (i = 0; i < numbucketlocks; i++)
593 rw_wunlock(&bucketlocks[i]);
597 cache_lock_all_vnodes(void)
601 for (i = 0; i < numvnodelocks; i++)
602 mtx_lock(&vnodelocks[i]);
606 cache_unlock_all_vnodes(void)
610 for (i = 0; i < numvnodelocks; i++)
611 mtx_unlock(&vnodelocks[i]);
615 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
618 cache_sort_vnodes(&vlp1, &vlp2);
621 if (!mtx_trylock(vlp1))
624 if (!mtx_trylock(vlp2)) {
634 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
637 MPASS(vlp1 != NULL || vlp2 != NULL);
647 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
650 MPASS(vlp1 != NULL || vlp2 != NULL);
659 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
661 struct nchstats snap;
663 if (req->oldptr == NULL)
664 return (SYSCTL_OUT(req, 0, sizeof(snap)));
667 snap.ncs_goodhits = counter_u64_fetch(numposhits);
668 snap.ncs_neghits = counter_u64_fetch(numneghits);
669 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
670 counter_u64_fetch(numnegzaps);
671 snap.ncs_miss = counter_u64_fetch(nummisszap) +
672 counter_u64_fetch(nummiss);
674 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
676 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
677 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
678 "VFS cache effectiveness statistics");
682 * Grab an atomic snapshot of the name cache hash chain lengths
684 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
685 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
689 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
691 struct nchashhead *ncpp;
692 struct namecache *ncp;
693 int i, error, n_nchash, *cntbuf;
696 n_nchash = nchash + 1; /* nchash is max index, not count */
697 if (req->oldptr == NULL)
698 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
699 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
700 cache_lock_all_buckets();
701 if (n_nchash != nchash + 1) {
702 cache_unlock_all_buckets();
703 free(cntbuf, M_TEMP);
706 /* Scan hash tables counting entries */
707 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
708 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
710 cache_unlock_all_buckets();
711 for (error = 0, i = 0; i < n_nchash; i++)
712 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
714 free(cntbuf, M_TEMP);
717 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
718 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
719 "nchash chain lengths");
722 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
725 struct nchashhead *ncpp;
726 struct namecache *ncp;
728 int count, maxlength, used, pct;
731 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
733 cache_lock_all_buckets();
734 n_nchash = nchash + 1; /* nchash is max index, not count */
738 /* Scan hash tables for applicable entries */
739 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
741 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
746 if (maxlength < count)
749 n_nchash = nchash + 1;
750 cache_unlock_all_buckets();
751 pct = (used * 100) / (n_nchash / 100);
752 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
755 error = SYSCTL_OUT(req, &used, sizeof(used));
758 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
761 error = SYSCTL_OUT(req, &pct, sizeof(pct));
766 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
767 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
768 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
772 * Negative entries management
774 * A variation of LRU scheme is used. New entries are hashed into one of
775 * numneglists cold lists. Entries get promoted to the hot list on first hit.
777 * The shrinker will demote hot list head and evict from the cold list in a
778 * round-robin manner.
781 cache_negative_init(struct namecache *ncp)
783 struct negstate *negstate;
785 ncp->nc_flag |= NCF_NEGATIVE;
786 negstate = NCP2NEGSTATE(ncp);
787 negstate->neg_flag = 0;
791 cache_negative_hit(struct namecache *ncp)
793 struct neglist *neglist;
794 struct negstate *negstate;
796 negstate = NCP2NEGSTATE(ncp);
797 if ((negstate->neg_flag & NEG_HOT) != 0)
799 neglist = NCP2NEGLIST(ncp);
800 mtx_lock(&ncneg_hot.nl_lock);
801 mtx_lock(&neglist->nl_lock);
802 if ((negstate->neg_flag & NEG_HOT) == 0) {
804 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
805 TAILQ_INSERT_TAIL(&ncneg_hot.nl_list, ncp, nc_dst);
806 negstate->neg_flag |= NEG_HOT;
808 mtx_unlock(&neglist->nl_lock);
809 mtx_unlock(&ncneg_hot.nl_lock);
813 cache_negative_insert(struct namecache *ncp)
815 struct neglist *neglist;
817 MPASS(ncp->nc_flag & NCF_NEGATIVE);
818 cache_assert_bucket_locked(ncp, RA_WLOCKED);
819 neglist = NCP2NEGLIST(ncp);
820 mtx_lock(&neglist->nl_lock);
821 TAILQ_INSERT_TAIL(&neglist->nl_list, ncp, nc_dst);
822 mtx_unlock(&neglist->nl_lock);
823 atomic_add_rel_long(&numneg, 1);
827 cache_negative_remove(struct namecache *ncp)
829 struct neglist *neglist;
830 struct negstate *negstate;
831 bool hot_locked = false;
832 bool list_locked = false;
834 cache_assert_bucket_locked(ncp, RA_WLOCKED);
835 neglist = NCP2NEGLIST(ncp);
836 negstate = NCP2NEGSTATE(ncp);
837 if ((negstate->neg_flag & NEG_HOT) != 0) {
839 mtx_lock(&ncneg_hot.nl_lock);
840 if ((negstate->neg_flag & NEG_HOT) == 0) {
842 mtx_lock(&neglist->nl_lock);
846 mtx_lock(&neglist->nl_lock);
848 * We may be racing against promotion in lockless lookup.
850 if ((negstate->neg_flag & NEG_HOT) != 0) {
851 mtx_unlock(&neglist->nl_lock);
853 mtx_lock(&ncneg_hot.nl_lock);
854 mtx_lock(&neglist->nl_lock);
857 if ((negstate->neg_flag & NEG_HOT) != 0) {
858 mtx_assert(&ncneg_hot.nl_lock, MA_OWNED);
859 TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
862 mtx_assert(&neglist->nl_lock, MA_OWNED);
863 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
866 mtx_unlock(&neglist->nl_lock);
868 mtx_unlock(&ncneg_hot.nl_lock);
869 atomic_subtract_rel_long(&numneg, 1);
873 cache_negative_shrink_select(struct namecache **ncpp,
874 struct neglist **neglistpp)
876 struct neglist *neglist;
877 struct namecache *ncp;
883 for (i = 0; i < numneglists; i++) {
884 neglist = &neglists[(cycle + i) % numneglists];
885 if (TAILQ_FIRST(&neglist->nl_list) == NULL)
887 mtx_lock(&neglist->nl_lock);
888 ncp = TAILQ_FIRST(&neglist->nl_list);
891 mtx_unlock(&neglist->nl_lock);
894 *neglistpp = neglist;
900 cache_negative_zap_one(void)
902 struct namecache *ncp, *ncp2;
903 struct neglist *neglist;
904 struct negstate *negstate;
908 if (mtx_owner(&ncneg_shrink_lock) != NULL ||
909 !mtx_trylock(&ncneg_shrink_lock)) {
910 counter_u64_add(shrinking_skipped, 1);
914 mtx_lock(&ncneg_hot.nl_lock);
915 ncp = TAILQ_FIRST(&ncneg_hot.nl_list);
917 neglist = NCP2NEGLIST(ncp);
918 negstate = NCP2NEGSTATE(ncp);
919 mtx_lock(&neglist->nl_lock);
920 MPASS((negstate->neg_flag & NEG_HOT) != 0);
921 TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
922 TAILQ_INSERT_TAIL(&neglist->nl_list, ncp, nc_dst);
923 negstate->neg_flag &= ~NEG_HOT;
925 mtx_unlock(&neglist->nl_lock);
927 mtx_unlock(&ncneg_hot.nl_lock);
929 cache_negative_shrink_select(&ncp, &neglist);
931 mtx_unlock(&ncneg_shrink_lock);
935 MPASS(ncp->nc_flag & NCF_NEGATIVE);
936 dvlp = VP2VNODELOCK(ncp->nc_dvp);
937 blp = NCP2BUCKETLOCK(ncp);
938 mtx_unlock(&neglist->nl_lock);
942 * Enter SMR to safely check the negative list.
943 * Even if the found pointer matches, the entry may now be reallocated
944 * and used by a different vnode.
947 ncp2 = TAILQ_FIRST(&neglist->nl_list);
948 if (ncp != ncp2 || dvlp != VP2VNODELOCK(ncp2->nc_dvp) ||
949 blp != NCP2BUCKETLOCK(ncp2)) {
954 SDT_PROBE2(vfs, namecache, shrink_negative, done, ncp->nc_dvp,
956 cache_zap_locked(ncp);
957 counter_u64_add(numneg_evicted, 1);
965 * cache_zap_locked():
967 * Removes a namecache entry from cache, whether it contains an actual
968 * pointer to a vnode or if it is just a negative cache entry.
971 cache_zap_locked(struct namecache *ncp)
973 struct nchashhead *ncpp;
975 if (!(ncp->nc_flag & NCF_NEGATIVE))
976 cache_assert_vnode_locked(ncp->nc_vp);
977 cache_assert_vnode_locked(ncp->nc_dvp);
978 cache_assert_bucket_locked(ncp, RA_WLOCKED);
980 CTR2(KTR_VFS, "cache_zap(%p) vp %p", ncp,
981 (ncp->nc_flag & NCF_NEGATIVE) ? NULL : ncp->nc_vp);
983 cache_ncp_invalidate(ncp);
985 ncpp = NCP2BUCKET(ncp);
986 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
987 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
988 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
989 ncp->nc_name, ncp->nc_vp);
990 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
991 if (ncp == ncp->nc_vp->v_cache_dd) {
992 vn_seqc_write_begin_unheld(ncp->nc_vp);
993 ncp->nc_vp->v_cache_dd = NULL;
994 vn_seqc_write_end(ncp->nc_vp);
997 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
999 cache_negative_remove(ncp);
1001 if (ncp->nc_flag & NCF_ISDOTDOT) {
1002 if (ncp == ncp->nc_dvp->v_cache_dd) {
1003 vn_seqc_write_begin_unheld(ncp->nc_dvp);
1004 ncp->nc_dvp->v_cache_dd = NULL;
1005 vn_seqc_write_end(ncp->nc_dvp);
1008 LIST_REMOVE(ncp, nc_src);
1009 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
1010 ncp->nc_flag |= NCF_DVDROP;
1011 counter_u64_add(numcachehv, -1);
1014 atomic_subtract_rel_long(&numcache, 1);
1018 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1022 MPASS(ncp->nc_dvp == vp);
1023 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1024 cache_assert_vnode_locked(vp);
1026 blp = NCP2BUCKETLOCK(ncp);
1028 cache_zap_locked(ncp);
1033 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1036 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1039 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1040 cache_assert_vnode_locked(vp);
1042 if (ncp->nc_flag & NCF_NEGATIVE) {
1043 if (*vlpp != NULL) {
1047 cache_zap_negative_locked_vnode_kl(ncp, vp);
1051 pvlp = VP2VNODELOCK(vp);
1052 blp = NCP2BUCKETLOCK(ncp);
1053 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1054 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1056 if (*vlpp == vlp1 || *vlpp == vlp2) {
1060 if (*vlpp != NULL) {
1064 cache_sort_vnodes(&vlp1, &vlp2);
1069 if (!mtx_trylock(vlp1))
1075 cache_zap_locked(ncp);
1077 if (to_unlock != NULL)
1078 mtx_unlock(to_unlock);
1085 MPASS(*vlpp == NULL);
1090 static int __noinline
1091 cache_zap_locked_vnode(struct namecache *ncp, struct vnode *vp)
1093 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1097 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1098 cache_assert_vnode_locked(vp);
1100 pvlp = VP2VNODELOCK(vp);
1101 if (ncp->nc_flag & NCF_NEGATIVE) {
1102 cache_zap_negative_locked_vnode_kl(ncp, vp);
1106 blp = NCP2BUCKETLOCK(ncp);
1107 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1108 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1109 cache_sort_vnodes(&vlp1, &vlp2);
1114 if (!mtx_trylock(vlp1)) {
1121 cache_zap_locked(ncp);
1123 mtx_unlock(to_unlock);
1130 * If trylocking failed we can get here. We know enough to take all needed locks
1131 * in the right order and re-lookup the entry.
1134 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1135 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1138 struct namecache *rncp;
1140 cache_assert_bucket_locked(ncp, RA_UNLOCKED);
1142 cache_sort_vnodes(&dvlp, &vlp);
1143 cache_lock_vnodes(dvlp, vlp);
1145 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1146 if (rncp == ncp && rncp->nc_dvp == dvp &&
1147 rncp->nc_nlen == cnp->cn_namelen &&
1148 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1152 cache_zap_locked(rncp);
1154 cache_unlock_vnodes(dvlp, vlp);
1155 counter_u64_add(zap_and_exit_bucket_relock_success, 1);
1160 cache_unlock_vnodes(dvlp, vlp);
1164 static int __noinline
1165 cache_zap_wlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1166 uint32_t hash, struct rwlock *blp)
1168 struct mtx *dvlp, *vlp;
1171 cache_assert_bucket_locked(ncp, RA_WLOCKED);
1173 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1175 if (!(ncp->nc_flag & NCF_NEGATIVE))
1176 vlp = VP2VNODELOCK(ncp->nc_vp);
1177 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1178 cache_zap_locked(ncp);
1180 cache_unlock_vnodes(dvlp, vlp);
1186 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1189 static int __noinline
1190 cache_zap_rlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1191 uint32_t hash, struct rwlock *blp)
1193 struct mtx *dvlp, *vlp;
1196 cache_assert_bucket_locked(ncp, RA_RLOCKED);
1198 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1200 if (!(ncp->nc_flag & NCF_NEGATIVE))
1201 vlp = VP2VNODELOCK(ncp->nc_vp);
1202 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1205 cache_zap_locked(ncp);
1207 cache_unlock_vnodes(dvlp, vlp);
1213 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1217 cache_zap_wlocked_bucket_kl(struct namecache *ncp, struct rwlock *blp,
1218 struct mtx **vlpp1, struct mtx **vlpp2)
1220 struct mtx *dvlp, *vlp;
1222 cache_assert_bucket_locked(ncp, RA_WLOCKED);
1224 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1226 if (!(ncp->nc_flag & NCF_NEGATIVE))
1227 vlp = VP2VNODELOCK(ncp->nc_vp);
1228 cache_sort_vnodes(&dvlp, &vlp);
1230 if (*vlpp1 == dvlp && *vlpp2 == vlp) {
1231 cache_zap_locked(ncp);
1232 cache_unlock_vnodes(dvlp, vlp);
1245 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1246 cache_zap_locked(ncp);
1247 cache_unlock_vnodes(dvlp, vlp);
1262 cache_lookup_unlock(struct rwlock *blp, struct mtx *vlp)
1272 static int __noinline
1273 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1274 struct timespec *tsp, int *ticksp)
1279 CTR2(KTR_VFS, "cache_lookup(%p, %s) found via .",
1280 dvp, cnp->cn_nameptr);
1281 counter_u64_add(dothits, 1);
1282 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1289 * When we lookup "." we still can be asked to lock it
1292 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1293 if (ltype != VOP_ISLOCKED(*vpp)) {
1294 if (ltype == LK_EXCLUSIVE) {
1295 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1296 if (VN_IS_DOOMED((*vpp))) {
1297 /* forced unmount */
1303 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1308 static __noinline int
1309 cache_lookup_nomakeentry(struct vnode *dvp, struct vnode **vpp,
1310 struct componentname *cnp, struct timespec *tsp, int *ticksp)
1312 struct namecache *ncp;
1314 struct mtx *dvlp, *dvlp2;
1318 if (cnp->cn_namelen == 2 &&
1319 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1320 counter_u64_add(dotdothits, 1);
1321 dvlp = VP2VNODELOCK(dvp);
1325 ncp = dvp->v_cache_dd;
1327 SDT_PROBE3(vfs, namecache, lookup, miss, dvp,
1334 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1335 if (ncp->nc_dvp != dvp)
1336 panic("dvp %p v_cache_dd %p\n", dvp, ncp);
1337 if (!cache_zap_locked_vnode_kl2(ncp,
1340 MPASS(dvp->v_cache_dd == NULL);
1346 vn_seqc_write_begin(dvp);
1347 dvp->v_cache_dd = NULL;
1348 vn_seqc_write_end(dvp);
1356 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1357 blp = HASH2BUCKETLOCK(hash);
1359 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1364 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1365 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1366 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1370 /* We failed to find an entry */
1376 error = cache_zap_wlocked_bucket(ncp, cnp, hash, blp);
1377 if (__predict_false(error != 0)) {
1378 zap_and_exit_bucket_fail++;
1379 cache_maybe_yield();
1382 counter_u64_add(numposzaps, 1);
1386 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr, NULL);
1387 counter_u64_add(nummisszap, 1);
1392 * Lookup a name in the name cache
1396 * - dvp: Parent directory in which to search.
1397 * - vpp: Return argument. Will contain desired vnode on cache hit.
1398 * - cnp: Parameters of the name search. The most interesting bits of
1399 * the cn_flags field have the following meanings:
1400 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1402 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1403 * - tsp: Return storage for cache timestamp. On a successful (positive
1404 * or negative) lookup, tsp will be filled with any timespec that
1405 * was stored when this cache entry was created. However, it will
1406 * be clear for "." entries.
1407 * - ticks: Return storage for alternate cache timestamp. On a successful
1408 * (positive or negative) lookup, it will contain the ticks value
1409 * that was current when the cache entry was created, unless cnp
1414 * - -1: A positive cache hit. vpp will contain the desired vnode.
1415 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1416 * to a forced unmount. vpp will not be modified. If the entry
1417 * is a whiteout, then the ISWHITEOUT flag will be set in
1419 * - 0: A cache miss. vpp will not be modified.
1423 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1424 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1425 * lock is not recursively acquired.
1428 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1429 struct timespec *tsp, int *ticksp)
1431 struct namecache_ts *ncp_ts;
1432 struct namecache *ncp;
1433 struct negstate *negstate;
1439 bool try_smr, doing_smr, whiteout;
1442 if (__predict_false(!doingcache)) {
1443 cnp->cn_flags &= ~MAKEENTRY;
1448 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.'))
1449 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1451 if ((cnp->cn_flags & MAKEENTRY) == 0)
1452 return (cache_lookup_nomakeentry(dvp, vpp, cnp, tsp, ticksp));
1455 if (cnp->cn_nameiop == CREATE)
1462 if (cnp->cn_namelen == 2 &&
1463 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1464 counter_u64_add(dotdothits, 1);
1465 dvlp = VP2VNODELOCK(dvp);
1467 ncp = dvp->v_cache_dd;
1469 SDT_PROBE3(vfs, namecache, lookup, miss, dvp,
1474 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1475 if (ncp->nc_flag & NCF_NEGATIVE)
1481 /* Return failure if negative entry was found. */
1483 goto negative_success;
1484 CTR3(KTR_VFS, "cache_lookup(%p, %s) found %p via ..",
1485 dvp, cnp->cn_nameptr, *vpp);
1486 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..",
1488 cache_out_ts(ncp, tsp, ticksp);
1489 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1490 NCF_DTS && tsp != NULL) {
1491 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1492 *tsp = ncp_ts->nc_dotdottime;
1497 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1504 blp = HASH2BUCKETLOCK(hash);
1508 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1509 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1510 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1514 /* We failed to find an entry */
1515 if (__predict_false(ncp == NULL)) {
1520 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1522 counter_u64_add(nummiss, 1);
1526 if (ncp->nc_flag & NCF_NEGATIVE)
1527 goto negative_success;
1529 /* We found a "positive" match, return the vnode */
1530 counter_u64_add(numposhits, 1);
1532 CTR4(KTR_VFS, "cache_lookup(%p, %s) found %p via ncp %p",
1533 dvp, cnp->cn_nameptr, *vpp, ncp);
1534 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name,
1536 cache_out_ts(ncp, tsp, ticksp);
1539 * On success we return a locked and ref'd vnode as per the lookup
1543 ltype = 0; /* silence gcc warning */
1544 if (cnp->cn_flags & ISDOTDOT) {
1545 ltype = VOP_ISLOCKED(dvp);
1549 if (!cache_ncp_canuse(ncp)) {
1554 vs = vget_prep_smr(*vpp);
1556 if (__predict_false(vs == VGET_NONE)) {
1561 vs = vget_prep(*vpp);
1562 cache_lookup_unlock(blp, dvlp);
1564 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1565 if (cnp->cn_flags & ISDOTDOT) {
1566 vn_lock(dvp, ltype | LK_RETRY);
1567 if (VN_IS_DOOMED(dvp)) {
1578 if ((cnp->cn_flags & ISLASTCN) &&
1579 (cnp->cn_lkflags & LK_TYPE_MASK) == LK_EXCLUSIVE) {
1580 ASSERT_VOP_ELOCKED(*vpp, "cache_lookup");
1585 /* We found a negative match, and want to create it, so purge */
1586 if (cnp->cn_nameiop == CREATE) {
1588 counter_u64_add(numnegzaps, 1);
1592 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1593 cache_out_ts(ncp, tsp, ticksp);
1594 counter_u64_add(numneghits, 1);
1595 whiteout = (ncp->nc_flag & NCF_WHITE);
1599 * We need to take locks to promote an entry.
1601 negstate = NCP2NEGSTATE(ncp);
1602 if ((negstate->neg_flag & NEG_HOT) == 0 ||
1603 !cache_ncp_canuse(ncp)) {
1610 cache_negative_hit(ncp);
1611 cache_lookup_unlock(blp, dvlp);
1614 cnp->cn_flags |= ISWHITEOUT;
1620 error = cache_zap_rlocked_bucket(ncp, cnp, hash, blp);
1622 error = cache_zap_locked_vnode(ncp, dvp);
1623 if (__predict_false(error != 0)) {
1624 zap_and_exit_bucket_fail2++;
1625 cache_maybe_yield();
1632 struct celockstate {
1634 struct rwlock *blp[2];
1636 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1637 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1640 cache_celockstate_init(struct celockstate *cel)
1643 bzero(cel, sizeof(*cel));
1647 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1650 struct mtx *vlp1, *vlp2;
1652 MPASS(cel->vlp[0] == NULL);
1653 MPASS(cel->vlp[1] == NULL);
1654 MPASS(cel->vlp[2] == NULL);
1656 MPASS(vp != NULL || dvp != NULL);
1658 vlp1 = VP2VNODELOCK(vp);
1659 vlp2 = VP2VNODELOCK(dvp);
1660 cache_sort_vnodes(&vlp1, &vlp2);
1671 cache_unlock_vnodes_cel(struct celockstate *cel)
1674 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
1676 if (cel->vlp[0] != NULL)
1677 mtx_unlock(cel->vlp[0]);
1678 if (cel->vlp[1] != NULL)
1679 mtx_unlock(cel->vlp[1]);
1680 if (cel->vlp[2] != NULL)
1681 mtx_unlock(cel->vlp[2]);
1685 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
1690 cache_assert_vlp_locked(cel->vlp[0]);
1691 cache_assert_vlp_locked(cel->vlp[1]);
1692 MPASS(cel->vlp[2] == NULL);
1695 vlp = VP2VNODELOCK(vp);
1698 if (vlp >= cel->vlp[1]) {
1701 if (mtx_trylock(vlp))
1703 cache_lock_vnodes_cel_3_failures++;
1704 cache_unlock_vnodes_cel(cel);
1705 if (vlp < cel->vlp[0]) {
1707 mtx_lock(cel->vlp[0]);
1708 mtx_lock(cel->vlp[1]);
1710 if (cel->vlp[0] != NULL)
1711 mtx_lock(cel->vlp[0]);
1713 mtx_lock(cel->vlp[1]);
1723 cache_lock_buckets_cel(struct celockstate *cel, struct rwlock *blp1,
1724 struct rwlock *blp2)
1727 MPASS(cel->blp[0] == NULL);
1728 MPASS(cel->blp[1] == NULL);
1730 cache_sort_vnodes(&blp1, &blp2);
1741 cache_unlock_buckets_cel(struct celockstate *cel)
1744 if (cel->blp[0] != NULL)
1745 rw_wunlock(cel->blp[0]);
1746 rw_wunlock(cel->blp[1]);
1750 * Lock part of the cache affected by the insertion.
1752 * This means vnodelocks for dvp, vp and the relevant bucketlock.
1753 * However, insertion can result in removal of an old entry. In this
1754 * case we have an additional vnode and bucketlock pair to lock. If the
1755 * entry is negative, ncelock is locked instead of the vnode.
1757 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
1758 * preserving the locking order (smaller address first).
1761 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1764 struct namecache *ncp;
1765 struct rwlock *blps[2];
1767 blps[0] = HASH2BUCKETLOCK(hash);
1770 cache_lock_vnodes_cel(cel, dvp, vp);
1771 if (vp == NULL || vp->v_type != VDIR)
1773 ncp = vp->v_cache_dd;
1776 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1778 MPASS(ncp->nc_dvp == vp);
1779 blps[1] = NCP2BUCKETLOCK(ncp);
1780 if (ncp->nc_flag & NCF_NEGATIVE)
1782 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1785 * All vnodes got re-locked. Re-validate the state and if
1786 * nothing changed we are done. Otherwise restart.
1788 if (ncp == vp->v_cache_dd &&
1789 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1790 blps[1] == NCP2BUCKETLOCK(ncp) &&
1791 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1793 cache_unlock_vnodes_cel(cel);
1798 cache_lock_buckets_cel(cel, blps[0], blps[1]);
1802 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1805 struct namecache *ncp;
1806 struct rwlock *blps[2];
1808 blps[0] = HASH2BUCKETLOCK(hash);
1811 cache_lock_vnodes_cel(cel, dvp, vp);
1812 ncp = dvp->v_cache_dd;
1815 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1817 MPASS(ncp->nc_dvp == dvp);
1818 blps[1] = NCP2BUCKETLOCK(ncp);
1819 if (ncp->nc_flag & NCF_NEGATIVE)
1821 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1823 if (ncp == dvp->v_cache_dd &&
1824 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1825 blps[1] == NCP2BUCKETLOCK(ncp) &&
1826 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1828 cache_unlock_vnodes_cel(cel);
1833 cache_lock_buckets_cel(cel, blps[0], blps[1]);
1837 cache_enter_unlock(struct celockstate *cel)
1840 cache_unlock_buckets_cel(cel);
1841 cache_unlock_vnodes_cel(cel);
1844 static void __noinline
1845 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
1846 struct componentname *cnp)
1848 struct celockstate cel;
1849 struct namecache *ncp;
1853 if (dvp->v_cache_dd == NULL)
1855 len = cnp->cn_namelen;
1856 cache_celockstate_init(&cel);
1857 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
1858 cache_enter_lock_dd(&cel, dvp, vp, hash);
1859 vn_seqc_write_begin(dvp);
1860 ncp = dvp->v_cache_dd;
1861 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
1862 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
1863 cache_zap_locked(ncp);
1867 dvp->v_cache_dd = NULL;
1868 vn_seqc_write_end(dvp);
1869 cache_enter_unlock(&cel);
1874 * Add an entry to the cache.
1877 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
1878 struct timespec *tsp, struct timespec *dtsp)
1880 struct celockstate cel;
1881 struct namecache *ncp, *n2, *ndd;
1882 struct namecache_ts *ncp_ts, *n2_ts;
1883 struct nchashhead *ncpp;
1889 CTR3(KTR_VFS, "cache_enter(%p, %p, %s)", dvp, vp, cnp->cn_nameptr);
1890 VNASSERT(vp == NULL || !VN_IS_DOOMED(vp), vp,
1891 ("cache_enter: Adding a doomed vnode"));
1892 VNASSERT(dvp == NULL || !VN_IS_DOOMED(dvp), dvp,
1893 ("cache_enter: Doomed vnode used as src"));
1896 if (__predict_false(!doingcache))
1901 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1902 if (cnp->cn_namelen == 1)
1904 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
1905 cache_enter_dotdot_prep(dvp, vp, cnp);
1906 flag = NCF_ISDOTDOT;
1911 * Avoid blowout in namecache entries.
1913 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
1914 if (__predict_false(lnumcache >= ncsize)) {
1915 atomic_add_long(&numcache, -1);
1916 counter_u64_add(numdrops, 1);
1920 cache_celockstate_init(&cel);
1925 * Calculate the hash key and setup as much of the new
1926 * namecache entry as possible before acquiring the lock.
1928 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
1929 ncp->nc_flag = flag | NCF_WIP;
1932 cache_negative_init(ncp);
1935 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1936 ncp_ts->nc_time = *tsp;
1937 ncp_ts->nc_ticks = ticks;
1938 ncp_ts->nc_nc.nc_flag |= NCF_TS;
1940 ncp_ts->nc_dotdottime = *dtsp;
1941 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
1944 len = ncp->nc_nlen = cnp->cn_namelen;
1945 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
1946 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
1947 ncp->nc_name[len] = '\0';
1948 cache_enter_lock(&cel, dvp, vp, hash);
1951 * See if this vnode or negative entry is already in the cache
1952 * with this name. This can happen with concurrent lookups of
1953 * the same path name.
1955 ncpp = NCHHASH(hash);
1956 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
1957 if (n2->nc_dvp == dvp &&
1958 n2->nc_nlen == cnp->cn_namelen &&
1959 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
1961 KASSERT((n2->nc_flag & NCF_TS) != 0,
1963 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
1964 n2_ts->nc_time = ncp_ts->nc_time;
1965 n2_ts->nc_ticks = ncp_ts->nc_ticks;
1967 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
1968 n2_ts->nc_nc.nc_flag |= NCF_DTS;
1971 goto out_unlock_free;
1975 if (flag == NCF_ISDOTDOT) {
1977 * See if we are trying to add .. entry, but some other lookup
1978 * has populated v_cache_dd pointer already.
1980 if (dvp->v_cache_dd != NULL)
1981 goto out_unlock_free;
1982 KASSERT(vp == NULL || vp->v_type == VDIR,
1983 ("wrong vnode type %p", vp));
1984 vn_seqc_write_begin(dvp);
1985 dvp->v_cache_dd = ncp;
1986 vn_seqc_write_end(dvp);
1990 if (vp->v_type == VDIR) {
1991 if (flag != NCF_ISDOTDOT) {
1993 * For this case, the cache entry maps both the
1994 * directory name in it and the name ".." for the
1995 * directory's parent.
1997 vn_seqc_write_begin(vp);
1998 if ((ndd = vp->v_cache_dd) != NULL) {
1999 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2000 cache_zap_locked(ndd);
2004 vp->v_cache_dd = ncp;
2005 vn_seqc_write_end(vp);
2008 if (vp->v_cache_dd != NULL) {
2009 vn_seqc_write_begin(vp);
2010 vp->v_cache_dd = NULL;
2011 vn_seqc_write_end(vp);
2016 if (flag != NCF_ISDOTDOT) {
2017 if (LIST_EMPTY(&dvp->v_cache_src)) {
2019 counter_u64_add(numcachehv, 1);
2021 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2025 * If the entry is "negative", we place it into the
2026 * "negative" cache queue, otherwise, we place it into the
2027 * destination vnode's cache entries queue.
2030 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2031 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2034 if (cnp->cn_flags & ISWHITEOUT)
2035 ncp->nc_flag |= NCF_WHITE;
2036 cache_negative_insert(ncp);
2037 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2042 * Insert the new namecache entry into the appropriate chain
2043 * within the cache entries table.
2045 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2047 atomic_thread_fence_rel();
2049 * Mark the entry as fully constructed.
2050 * It is immutable past this point until its removal.
2052 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2054 cache_enter_unlock(&cel);
2055 if (numneg * ncnegfactor > lnumcache)
2056 cache_negative_zap_one();
2060 cache_enter_unlock(&cel);
2061 atomic_add_long(&numcache, -1);
2067 cache_roundup_2(u_int val)
2071 for (res = 1; res <= val; res <<= 1)
2077 static struct nchashhead *
2078 nchinittbl(u_long elements, u_long *hashmask)
2080 struct nchashhead *hashtbl;
2083 hashsize = cache_roundup_2(elements) / 2;
2085 hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2086 for (i = 0; i < hashsize; i++)
2087 CK_SLIST_INIT(&hashtbl[i]);
2088 *hashmask = hashsize - 1;
2093 ncfreetbl(struct nchashhead *hashtbl)
2096 free(hashtbl, M_VFSCACHE);
2100 * Name cache initialization, from vfs_init() when we are booting
2103 nchinit(void *dummy __unused)
2107 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2108 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2109 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2110 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2111 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2112 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2113 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2114 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2116 VFS_SMR_ZONE_SET(cache_zone_small);
2117 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2118 VFS_SMR_ZONE_SET(cache_zone_large);
2119 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2121 ncsize = desiredvnodes * ncsizefactor;
2122 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2123 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2124 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2126 if (ncbuckethash > nchash)
2127 ncbuckethash = nchash;
2128 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2130 for (i = 0; i < numbucketlocks; i++)
2131 rw_init_flags(&bucketlocks[i], "ncbuc", RW_DUPOK | RW_RECURSE);
2132 ncvnodehash = ncbuckethash;
2133 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2135 for (i = 0; i < numvnodelocks; i++)
2136 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2137 ncpurgeminvnodes = numbucketlocks * 2;
2139 neglists = malloc(sizeof(*neglists) * numneglists, M_VFSCACHE,
2141 for (i = 0; i < numneglists; i++) {
2142 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2143 TAILQ_INIT(&neglists[i].nl_list);
2145 mtx_init(&ncneg_hot.nl_lock, "ncneglh", NULL, MTX_DEF);
2146 TAILQ_INIT(&ncneg_hot.nl_list);
2148 mtx_init(&ncneg_shrink_lock, "ncnegs", NULL, MTX_DEF);
2150 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2153 cache_vnode_init(struct vnode *vp)
2156 LIST_INIT(&vp->v_cache_src);
2157 TAILQ_INIT(&vp->v_cache_dst);
2158 vp->v_cache_dd = NULL;
2163 cache_changesize(u_long newmaxvnodes)
2165 struct nchashhead *new_nchashtbl, *old_nchashtbl;
2166 u_long new_nchash, old_nchash;
2167 struct namecache *ncp;
2172 newncsize = newmaxvnodes * ncsizefactor;
2173 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2174 if (newmaxvnodes < numbucketlocks)
2175 newmaxvnodes = numbucketlocks;
2177 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2178 /* If same hash table size, nothing to do */
2179 if (nchash == new_nchash) {
2180 ncfreetbl(new_nchashtbl);
2184 * Move everything from the old hash table to the new table.
2185 * None of the namecache entries in the table can be removed
2186 * because to do so, they have to be removed from the hash table.
2188 cache_lock_all_vnodes();
2189 cache_lock_all_buckets();
2190 old_nchashtbl = nchashtbl;
2191 old_nchash = nchash;
2192 nchashtbl = new_nchashtbl;
2193 nchash = new_nchash;
2194 for (i = 0; i <= old_nchash; i++) {
2195 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2196 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2198 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2199 CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2203 cache_unlock_all_buckets();
2204 cache_unlock_all_vnodes();
2205 ncfreetbl(old_nchashtbl);
2209 * Invalidate all entries from and to a particular vnode.
2212 cache_purge_impl(struct vnode *vp)
2214 TAILQ_HEAD(, namecache) ncps;
2215 struct namecache *ncp, *nnp;
2216 struct mtx *vlp, *vlp2;
2219 vlp = VP2VNODELOCK(vp);
2221 mtx_assert(vlp, MA_OWNED);
2223 while (!LIST_EMPTY(&vp->v_cache_src)) {
2224 ncp = LIST_FIRST(&vp->v_cache_src);
2225 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2227 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2229 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2230 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2231 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2233 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2235 ncp = vp->v_cache_dd;
2237 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2238 ("lost dotdot link"));
2239 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2241 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2243 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2247 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2253 cache_purge(struct vnode *vp)
2257 SDT_PROBE1(vfs, namecache, purge, done, vp);
2258 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2259 vp->v_cache_dd == NULL)
2261 vlp = VP2VNODELOCK(vp);
2263 cache_purge_impl(vp);
2267 * Only to be used by vgone.
2270 cache_purge_vgone(struct vnode *vp)
2274 VNPASS(VN_IS_DOOMED(vp), vp);
2275 vlp = VP2VNODELOCK(vp);
2276 if (!(LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2277 vp->v_cache_dd == NULL)) {
2279 cache_purge_impl(vp);
2280 mtx_assert(vlp, MA_NOTOWNED);
2285 * All the NULL pointer state we found above may be transient.
2286 * Serialize against a possible thread doing cache_purge.
2288 mtx_wait_unlocked(vlp);
2289 if (!(LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2290 vp->v_cache_dd == NULL)) {
2292 cache_purge_impl(vp);
2293 mtx_assert(vlp, MA_NOTOWNED);
2300 * Invalidate all negative entries for a particular directory vnode.
2303 cache_purge_negative(struct vnode *vp)
2305 TAILQ_HEAD(, namecache) ncps;
2306 struct namecache *ncp, *nnp;
2309 CTR1(KTR_VFS, "cache_purge_negative(%p)", vp);
2310 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2311 if (LIST_EMPTY(&vp->v_cache_src))
2314 vlp = VP2VNODELOCK(vp);
2316 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2317 if (!(ncp->nc_flag & NCF_NEGATIVE))
2319 cache_zap_negative_locked_vnode_kl(ncp, vp);
2320 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2323 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2329 * Flush all entries referencing a particular filesystem.
2332 cache_purgevfs(struct mount *mp, bool force)
2334 TAILQ_HEAD(, namecache) ncps;
2335 struct mtx *vlp1, *vlp2;
2337 struct nchashhead *bucket;
2338 struct namecache *ncp, *nnp;
2339 u_long i, j, n_nchash;
2342 /* Scan hash tables for applicable entries */
2343 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2344 if (!force && mp->mnt_nvnodelistsize <= ncpurgeminvnodes)
2347 n_nchash = nchash + 1;
2349 for (i = 0; i < numbucketlocks; i++) {
2350 blp = (struct rwlock *)&bucketlocks[i];
2352 for (j = i; j < n_nchash; j += numbucketlocks) {
2354 bucket = &nchashtbl[j];
2355 CK_SLIST_FOREACH_SAFE(ncp, bucket, nc_hash, nnp) {
2356 cache_assert_bucket_locked(ncp, RA_WLOCKED);
2357 if (ncp->nc_dvp->v_mount != mp)
2359 error = cache_zap_wlocked_bucket_kl(ncp, blp,
2363 TAILQ_INSERT_HEAD(&ncps, ncp, nc_dst);
2367 if (vlp1 == NULL && vlp2 == NULL)
2368 cache_maybe_yield();
2375 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2381 * Perform canonical checks and cache lookup and pass on to filesystem
2382 * through the vop_cachedlookup only if needed.
2386 vfs_cache_lookup(struct vop_lookup_args *ap)
2390 struct vnode **vpp = ap->a_vpp;
2391 struct componentname *cnp = ap->a_cnp;
2392 int flags = cnp->cn_flags;
2397 if (dvp->v_type != VDIR)
2400 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2401 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2404 error = vn_dir_check_exec(dvp, cnp);
2408 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2410 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2416 /* Implementation of the getcwd syscall. */
2418 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2424 buflen = uap->buflen;
2425 if (__predict_false(buflen < 2))
2427 if (buflen > MAXPATHLEN)
2428 buflen = MAXPATHLEN;
2430 buf = uma_zalloc(namei_zone, M_WAITOK);
2431 error = vn_getcwd(td, buf, &retbuf, &buflen);
2433 error = copyout(retbuf, uap->buf, buflen);
2434 uma_zfree(namei_zone, buf);
2439 vn_getcwd(struct thread *td, char *buf, char **retbuf, size_t *buflen)
2445 error = vn_fullpath_any(td, pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf, buflen);
2449 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2456 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2457 size_t size, int flags, enum uio_seg pathseg)
2459 struct nameidata nd;
2460 char *retbuf, *freebuf;
2465 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2466 pathseg, path, fd, &cap_fstat_rights, td);
2467 if ((error = namei(&nd)) != 0)
2469 error = vn_fullpath_hardlink(td, &nd, &retbuf, &freebuf, &size);
2471 error = copyout(retbuf, buf, size);
2472 free(freebuf, M_TEMP);
2479 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2482 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2483 uap->flags, UIO_USERSPACE));
2487 * Retrieve the full filesystem path that correspond to a vnode from the name
2488 * cache (if available)
2491 vn_fullpath(struct thread *td, struct vnode *vn, char **retbuf, char **freebuf)
2498 if (__predict_false(vn == NULL))
2501 buflen = MAXPATHLEN;
2502 buf = malloc(buflen, M_TEMP, M_WAITOK);
2504 error = vn_fullpath_any(td, vn, pwd->pwd_rdir, buf, retbuf, &buflen);
2515 * This function is similar to vn_fullpath, but it attempts to lookup the
2516 * pathname relative to the global root mount point. This is required for the
2517 * auditing sub-system, as audited pathnames must be absolute, relative to the
2518 * global root mount point.
2521 vn_fullpath_global(struct thread *td, struct vnode *vn,
2522 char **retbuf, char **freebuf)
2528 if (__predict_false(vn == NULL))
2530 buflen = MAXPATHLEN;
2531 buf = malloc(buflen, M_TEMP, M_WAITOK);
2532 error = vn_fullpath_any(td, vn, rootvnode, buf, retbuf, &buflen);
2541 vn_vptocnp(struct vnode **vp, struct ucred *cred, char *buf, size_t *buflen)
2544 struct namecache *ncp;
2548 vlp = VP2VNODELOCK(*vp);
2550 TAILQ_FOREACH(ncp, &((*vp)->v_cache_dst), nc_dst) {
2551 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2555 if (*buflen < ncp->nc_nlen) {
2558 counter_u64_add(numfullpathfail4, 1);
2560 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2564 *buflen -= ncp->nc_nlen;
2565 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2566 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2575 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2578 vn_lock(*vp, LK_SHARED | LK_RETRY);
2579 error = VOP_VPTOCNP(*vp, &dvp, cred, buf, buflen);
2582 counter_u64_add(numfullpathfail2, 1);
2583 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2588 if (VN_IS_DOOMED(dvp)) {
2589 /* forced unmount */
2592 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2596 * *vp has its use count incremented still.
2603 * Resolve a directory to a pathname.
2605 * The name of the directory can always be found in the namecache or fetched
2606 * from the filesystem. There is also guaranteed to be only one parent, meaning
2607 * we can just follow vnodes up until we find the root.
2609 * The vnode must be referenced.
2612 vn_fullpath_dir(struct thread *td, struct vnode *vp, struct vnode *rdir,
2613 char *buf, char **retbuf, size_t *len, bool slash_prefixed, size_t addend)
2615 #ifdef KDTRACE_HOOKS
2616 struct vnode *startvp = vp;
2622 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
2623 VNPASS(vp->v_usecount > 0, vp);
2627 if (!slash_prefixed) {
2635 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
2636 counter_u64_add(numfullpathcalls, 1);
2637 while (vp != rdir && vp != rootvnode) {
2639 * The vp vnode must be already fully constructed,
2640 * since it is either found in namecache or obtained
2641 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
2642 * without obtaining the vnode lock.
2644 if ((vp->v_vflag & VV_ROOT) != 0) {
2645 vn_lock(vp, LK_RETRY | LK_SHARED);
2648 * With the vnode locked, check for races with
2649 * unmount, forced or not. Note that we
2650 * already verified that vp is not equal to
2651 * the root vnode, which means that
2652 * mnt_vnodecovered can be NULL only for the
2655 if (VN_IS_DOOMED(vp) ||
2656 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
2657 vp1->v_mountedhere != vp->v_mount) {
2660 SDT_PROBE3(vfs, namecache, fullpath, return,
2670 if (vp->v_type != VDIR) {
2672 counter_u64_add(numfullpathfail1, 1);
2674 SDT_PROBE3(vfs, namecache, fullpath, return,
2678 error = vn_vptocnp(&vp, td->td_ucred, buf, &buflen);
2684 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2688 buf[--buflen] = '/';
2689 slash_prefixed = true;
2693 if (!slash_prefixed) {
2696 counter_u64_add(numfullpathfail4, 1);
2697 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
2701 buf[--buflen] = '/';
2703 counter_u64_add(numfullpathfound, 1);
2706 *retbuf = buf + buflen;
2707 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
2714 * Resolve an arbitrary vnode to a pathname.
2717 * - hardlinks are not tracked, thus if the vnode is not a directory this can
2718 * resolve to a different path than the one used to find it
2719 * - namecache is not mandatory, meaning names are not guaranteed to be added
2720 * (in which case resolving fails)
2723 vn_fullpath_any(struct thread *td, struct vnode *vp, struct vnode *rdir,
2724 char *buf, char **retbuf, size_t *buflen)
2727 bool slash_prefixed;
2733 orig_buflen = *buflen;
2736 slash_prefixed = false;
2737 if (vp->v_type != VDIR) {
2739 buf[*buflen] = '\0';
2740 error = vn_vptocnp(&vp, td->td_ucred, buf, buflen);
2749 slash_prefixed = true;
2752 return (vn_fullpath_dir(td, vp, rdir, buf, retbuf, buflen, slash_prefixed,
2753 orig_buflen - *buflen));
2757 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
2759 * Since the namecache does not track handlings, the caller is expected to first
2760 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
2762 * Then we have 2 cases:
2763 * - if the found vnode is a directory, the path can be constructed just by
2764 * fullowing names up the chain
2765 * - otherwise we populate the buffer with the saved name and start resolving
2769 vn_fullpath_hardlink(struct thread *td, struct nameidata *ndp, char **retbuf,
2770 char **freebuf, size_t *buflen)
2774 struct componentname *cnp;
2778 bool slash_prefixed;
2782 if (*buflen > MAXPATHLEN)
2783 *buflen = MAXPATHLEN;
2785 slash_prefixed = false;
2787 buf = malloc(*buflen, M_TEMP, M_WAITOK);
2792 if (vp->v_type != VDIR) {
2794 addend = cnp->cn_namelen + 2;
2795 if (*buflen < addend) {
2800 tmpbuf = buf + *buflen;
2802 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
2803 tmpbuf[addend - 1] = '\0';
2804 slash_prefixed = true;
2809 error = vn_fullpath_dir(td, vp, pwd->pwd_rdir, buf, retbuf, buflen,
2810 slash_prefixed, addend);
2825 vn_dir_dd_ino(struct vnode *vp)
2827 struct namecache *ncp;
2832 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
2833 vlp = VP2VNODELOCK(vp);
2835 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
2836 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
2839 vs = vget_prep(ddvp);
2841 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
2850 vn_commname(struct vnode *vp, char *buf, u_int buflen)
2852 struct namecache *ncp;
2856 vlp = VP2VNODELOCK(vp);
2858 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
2859 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2865 l = min(ncp->nc_nlen, buflen - 1);
2866 memcpy(buf, ncp->nc_name, l);
2873 * This function updates path string to vnode's full global path
2874 * and checks the size of the new path string against the pathlen argument.
2876 * Requires a locked, referenced vnode.
2877 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
2879 * If vp is a directory, the call to vn_fullpath_global() always succeeds
2880 * because it falls back to the ".." lookup if the namecache lookup fails.
2883 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
2886 struct nameidata nd;
2891 ASSERT_VOP_ELOCKED(vp, __func__);
2893 /* Construct global filesystem path from vp. */
2895 error = vn_fullpath_global(td, vp, &rpath, &fbuf);
2902 if (strlen(rpath) >= pathlen) {
2904 error = ENAMETOOLONG;
2909 * Re-lookup the vnode by path to detect a possible rename.
2910 * As a side effect, the vnode is relocked.
2911 * If vnode was renamed, return ENOENT.
2913 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
2914 UIO_SYSSPACE, path, td);
2920 NDFREE(&nd, NDF_ONLY_PNBUF);
2924 strcpy(path, rpath);
2937 db_print_vpath(struct vnode *vp)
2940 while (vp != NULL) {
2941 db_printf("%p: ", vp);
2942 if (vp == rootvnode) {
2946 if (vp->v_vflag & VV_ROOT) {
2947 db_printf("<mount point>");
2948 vp = vp->v_mount->mnt_vnodecovered;
2950 struct namecache *ncp;
2954 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2957 for (i = 0; i < ncp->nc_nlen; i++)
2958 db_printf("%c", *ncn++);
2971 DB_SHOW_COMMAND(vpath, db_show_vpath)
2976 db_printf("usage: show vpath <struct vnode *>\n");
2980 vp = (struct vnode *)addr;
2986 static bool __read_frequently cache_fast_lookup = true;
2987 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_lookup, CTLFLAG_RW,
2988 &cache_fast_lookup, 0, "");
2990 #define CACHE_FPL_FAILED -2020
2993 cache_fpl_cleanup_cnp(struct componentname *cnp)
2996 uma_zfree(namei_zone, cnp->cn_pnbuf);
2998 cnp->cn_pnbuf = NULL;
2999 cnp->cn_nameptr = NULL;
3004 cache_fpl_handle_root(struct nameidata *ndp, struct vnode **dpp)
3006 struct componentname *cnp;
3009 while (*(cnp->cn_nameptr) == '/') {
3014 *dpp = ndp->ni_rootdir;
3018 * Components of nameidata (or objects it can point to) which may
3019 * need restoring in case fast path lookup fails.
3021 struct nameidata_saved {
3029 struct nameidata *ndp;
3030 struct componentname *cnp;
3036 struct nameidata_saved snd;
3038 enum cache_fpl_status status:8;
3043 cache_fpl_checkpoint(struct cache_fpl *fpl, struct nameidata_saved *snd)
3046 snd->cn_flags = fpl->ndp->ni_cnd.cn_flags;
3047 snd->cn_namelen = fpl->ndp->ni_cnd.cn_namelen;
3048 snd->cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3049 snd->ni_pathlen = fpl->ndp->ni_pathlen;
3053 cache_fpl_restore(struct cache_fpl *fpl, struct nameidata_saved *snd)
3056 fpl->ndp->ni_cnd.cn_flags = snd->cn_flags;
3057 fpl->ndp->ni_cnd.cn_namelen = snd->cn_namelen;
3058 fpl->ndp->ni_cnd.cn_nameptr = snd->cn_nameptr;
3059 fpl->ndp->ni_pathlen = snd->ni_pathlen;
3063 #define cache_fpl_smr_assert_entered(fpl) ({ \
3064 struct cache_fpl *_fpl = (fpl); \
3065 MPASS(_fpl->in_smr == true); \
3066 VFS_SMR_ASSERT_ENTERED(); \
3068 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
3069 struct cache_fpl *_fpl = (fpl); \
3070 MPASS(_fpl->in_smr == false); \
3071 VFS_SMR_ASSERT_NOT_ENTERED(); \
3074 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3075 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3078 #define cache_fpl_smr_enter_initial(fpl) ({ \
3079 struct cache_fpl *_fpl = (fpl); \
3081 _fpl->in_smr = true; \
3084 #define cache_fpl_smr_enter(fpl) ({ \
3085 struct cache_fpl *_fpl = (fpl); \
3086 MPASS(_fpl->in_smr == false); \
3088 _fpl->in_smr = true; \
3091 #define cache_fpl_smr_exit(fpl) ({ \
3092 struct cache_fpl *_fpl = (fpl); \
3093 MPASS(_fpl->in_smr == true); \
3095 _fpl->in_smr = false; \
3099 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3102 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3103 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3104 ("%s: converting to abort from %d at %d, set at %d\n",
3105 __func__, fpl->status, line, fpl->line));
3107 fpl->status = CACHE_FPL_STATUS_ABORTED;
3109 return (CACHE_FPL_FAILED);
3112 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
3115 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3118 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3119 ("%s: setting to partial at %d, but already set to %d at %d\n",
3120 __func__, line, fpl->status, fpl->line));
3121 cache_fpl_smr_assert_entered(fpl);
3122 fpl->status = CACHE_FPL_STATUS_PARTIAL;
3124 return (CACHE_FPL_FAILED);
3127 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
3130 cache_fpl_handled_impl(struct cache_fpl *fpl, int error, int line)
3133 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3134 ("%s: setting to handled at %d, but already set to %d at %d\n",
3135 __func__, line, fpl->status, fpl->line));
3136 cache_fpl_smr_assert_not_entered(fpl);
3137 MPASS(error != CACHE_FPL_FAILED);
3138 fpl->status = CACHE_FPL_STATUS_HANDLED;
3143 #define cache_fpl_handled(x, e) cache_fpl_handled_impl((x), (e), __LINE__)
3145 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3146 (LOCKLEAF | LOCKPARENT | WANTPARENT | NOCACHE | FOLLOW | LOCKSHARED | SAVENAME | \
3147 SAVESTART | WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2)
3149 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3150 (ISDOTDOT | MAKEENTRY | ISLASTCN)
3152 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3153 "supported and internal flags overlap");
3156 cache_fpl_islastcn(struct nameidata *ndp)
3159 return (*ndp->ni_next == 0);
3163 cache_fpl_isdotdot(struct componentname *cnp)
3166 if (cnp->cn_namelen == 2 &&
3167 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3173 cache_can_fplookup(struct cache_fpl *fpl)
3175 struct nameidata *ndp;
3176 struct componentname *cnp;
3181 td = cnp->cn_thread;
3183 if (!cache_fast_lookup) {
3184 cache_fpl_aborted(fpl);
3188 if (mac_vnode_check_lookup_enabled()) {
3189 cache_fpl_aborted(fpl);
3193 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3194 cache_fpl_aborted(fpl);
3197 if (ndp->ni_dirfd != AT_FDCWD) {
3198 cache_fpl_aborted(fpl);
3201 if (IN_CAPABILITY_MODE(td)) {
3202 cache_fpl_aborted(fpl);
3205 if (AUDITING_TD(td)) {
3206 cache_fpl_aborted(fpl);
3209 if (ndp->ni_startdir != NULL) {
3210 cache_fpl_aborted(fpl);
3217 cache_fplookup_vnode_supported(struct vnode *vp)
3220 return (vp->v_type != VLNK);
3224 * Move a negative entry to the hot list.
3226 * We have to take locks, but they may be contended and in the worst
3227 * case we may need to go off CPU. We don't want to spin within the
3228 * smr section and we can't block with it. Instead we are going to
3229 * look up the entry again.
3231 static int __noinline
3232 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
3235 struct componentname *cnp;
3236 struct namecache *ncp;
3237 struct neglist *neglist;
3238 struct negstate *negstate;
3245 if (!vhold_smr(dvp))
3246 return (cache_fpl_aborted(fpl));
3248 neglist = NCP2NEGLIST(oncp);
3249 cache_fpl_smr_exit(fpl);
3251 mtx_lock(&ncneg_hot.nl_lock);
3252 mtx_lock(&neglist->nl_lock);
3254 * For hash iteration.
3256 cache_fpl_smr_enter(fpl);
3259 * Avoid all surprises by only succeeding if we got the same entry and
3260 * bailing completely otherwise.
3262 * In particular at this point there can be a new ncp which matches the
3263 * search but hashes to a different neglist.
3265 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3271 * No match to begin with.
3273 if (__predict_false(ncp == NULL)) {
3278 * The newly found entry may be something different...
3280 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3281 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
3286 * ... and not even negative.
3288 nc_flag = atomic_load_char(&ncp->nc_flag);
3289 if ((nc_flag & NCF_NEGATIVE) == 0) {
3293 if (__predict_false(!cache_ncp_canuse(ncp))) {
3297 negstate = NCP2NEGSTATE(ncp);
3298 if ((negstate->neg_flag & NEG_HOT) == 0) {
3300 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
3301 TAILQ_INSERT_TAIL(&ncneg_hot.nl_list, ncp, nc_dst);
3302 negstate->neg_flag |= NEG_HOT;
3305 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
3306 counter_u64_add(numneghits, 1);
3307 cache_fpl_smr_exit(fpl);
3308 mtx_unlock(&neglist->nl_lock);
3309 mtx_unlock(&ncneg_hot.nl_lock);
3311 return (cache_fpl_handled(fpl, ENOENT));
3313 cache_fpl_smr_exit(fpl);
3314 mtx_unlock(&neglist->nl_lock);
3315 mtx_unlock(&ncneg_hot.nl_lock);
3317 return (cache_fpl_aborted(fpl));
3321 * The target vnode is not supported, prepare for the slow path to take over.
3323 static int __noinline
3324 cache_fplookup_partial_setup(struct cache_fpl *fpl)
3326 struct nameidata *ndp;
3327 struct componentname *cnp;
3336 dvp_seqc = fpl->dvp_seqc;
3338 dvs = vget_prep_smr(dvp);
3339 if (__predict_false(dvs == VGET_NONE)) {
3340 cache_fpl_smr_exit(fpl);
3341 return (cache_fpl_aborted(fpl));
3344 cache_fpl_smr_exit(fpl);
3346 vget_finish_ref(dvp, dvs);
3347 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3349 return (cache_fpl_aborted(fpl));
3352 pwd = pwd_hold(curthread);
3353 if (fpl->pwd != pwd) {
3356 return (cache_fpl_aborted(fpl));
3359 cache_fpl_restore(fpl, &fpl->snd);
3361 ndp->ni_startdir = dvp;
3362 cnp->cn_flags |= MAKEENTRY;
3363 if (cache_fpl_islastcn(ndp))
3364 cnp->cn_flags |= ISLASTCN;
3365 if (cache_fpl_isdotdot(cnp))
3366 cnp->cn_flags |= ISDOTDOT;
3372 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
3374 struct componentname *cnp;
3381 tvp_seqc = fpl->tvp_seqc;
3383 if ((cnp->cn_flags & LOCKLEAF) != 0) {
3384 lkflags = LK_SHARED;
3385 if ((cnp->cn_flags & LOCKSHARED) == 0)
3386 lkflags = LK_EXCLUSIVE;
3387 error = vget_finish(tvp, lkflags, tvs);
3388 if (__predict_false(error != 0)) {
3389 return (cache_fpl_aborted(fpl));
3392 vget_finish_ref(tvp, tvs);
3395 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
3396 if ((cnp->cn_flags & LOCKLEAF) != 0)
3400 return (cache_fpl_aborted(fpl));
3403 return (cache_fpl_handled(fpl, 0));
3407 * They want to possibly modify the state of the namecache.
3409 * Don't try to match the API contract, just leave.
3410 * TODO: this leaves scalability on the table
3413 cache_fplookup_final_modifying(struct cache_fpl *fpl)
3415 struct componentname *cnp;
3418 MPASS(cnp->cn_nameiop != LOOKUP);
3419 return (cache_fpl_partial(fpl));
3422 static int __noinline
3423 cache_fplookup_final_withparent(struct cache_fpl *fpl)
3425 struct componentname *cnp;
3426 enum vgetstate dvs, tvs;
3427 struct vnode *dvp, *tvp;
3428 seqc_t dvp_seqc, tvp_seqc;
3433 dvp_seqc = fpl->dvp_seqc;
3435 tvp_seqc = fpl->tvp_seqc;
3437 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
3440 * This is less efficient than it can be for simplicity.
3442 dvs = vget_prep_smr(dvp);
3443 if (__predict_false(dvs == VGET_NONE)) {
3444 return (cache_fpl_aborted(fpl));
3446 tvs = vget_prep_smr(tvp);
3447 if (__predict_false(tvs == VGET_NONE)) {
3448 cache_fpl_smr_exit(fpl);
3449 vget_abort(dvp, dvs);
3450 return (cache_fpl_aborted(fpl));
3453 cache_fpl_smr_exit(fpl);
3455 if ((cnp->cn_flags & LOCKPARENT) != 0) {
3456 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
3457 if (__predict_false(error != 0)) {
3458 vget_abort(tvp, tvs);
3459 return (cache_fpl_aborted(fpl));
3462 vget_finish_ref(dvp, dvs);
3465 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3466 vget_abort(tvp, tvs);
3467 if ((cnp->cn_flags & LOCKPARENT) != 0)
3471 return (cache_fpl_aborted(fpl));
3474 error = cache_fplookup_final_child(fpl, tvs);
3475 if (__predict_false(error != 0)) {
3476 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
3477 if ((cnp->cn_flags & LOCKPARENT) != 0)
3484 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
3489 cache_fplookup_final(struct cache_fpl *fpl)
3491 struct componentname *cnp;
3493 struct vnode *dvp, *tvp;
3494 seqc_t dvp_seqc, tvp_seqc;
3498 dvp_seqc = fpl->dvp_seqc;
3500 tvp_seqc = fpl->tvp_seqc;
3502 VNPASS(cache_fplookup_vnode_supported(dvp), dvp);
3504 if (cnp->cn_nameiop != LOOKUP) {
3505 return (cache_fplookup_final_modifying(fpl));
3508 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
3509 return (cache_fplookup_final_withparent(fpl));
3511 tvs = vget_prep_smr(tvp);
3512 if (__predict_false(tvs == VGET_NONE)) {
3513 return (cache_fpl_partial(fpl));
3516 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3517 cache_fpl_smr_exit(fpl);
3518 vget_abort(tvp, tvs);
3519 return (cache_fpl_aborted(fpl));
3522 cache_fpl_smr_exit(fpl);
3523 return (cache_fplookup_final_child(fpl, tvs));
3526 static int __noinline
3527 cache_fplookup_dot(struct cache_fpl *fpl)
3534 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3535 if (seqc_in_modify(fpl->tvp_seqc)) {
3536 return (cache_fpl_aborted(fpl));
3539 counter_u64_add(dothits, 1);
3540 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", dvp);
3545 static int __noinline
3546 cache_fplookup_dotdot(struct cache_fpl *fpl)
3548 struct nameidata *ndp;
3549 struct componentname *cnp;
3550 struct namecache *ncp;
3560 * XXX this is racy the same way regular lookup is
3562 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
3564 if (dvp == pr->pr_root)
3567 if (dvp == ndp->ni_rootdir ||
3568 dvp == ndp->ni_topdir ||
3572 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3573 if (seqc_in_modify(fpl->tvp_seqc)) {
3574 return (cache_fpl_aborted(fpl));
3579 if ((dvp->v_vflag & VV_ROOT) != 0) {
3582 * The opposite of climb mount is needed here.
3584 return (cache_fpl_aborted(fpl));
3587 ncp = atomic_load_ptr(&dvp->v_cache_dd);
3589 return (cache_fpl_aborted(fpl));
3592 nc_flag = atomic_load_char(&ncp->nc_flag);
3593 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3594 if ((nc_flag & NCF_NEGATIVE) != 0)
3595 return (cache_fpl_aborted(fpl));
3596 fpl->tvp = ncp->nc_vp;
3598 fpl->tvp = ncp->nc_dvp;
3601 if (__predict_false(!cache_ncp_canuse(ncp))) {
3602 return (cache_fpl_aborted(fpl));
3605 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
3606 if (seqc_in_modify(fpl->tvp_seqc)) {
3607 return (cache_fpl_partial(fpl));
3610 counter_u64_add(dotdothits, 1);
3615 cache_fplookup_next(struct cache_fpl *fpl)
3617 struct componentname *cnp;
3618 struct namecache *ncp;
3619 struct negstate *negstate;
3620 struct vnode *dvp, *tvp;
3628 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.')) {
3629 return (cache_fplookup_dot(fpl));
3632 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
3634 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3635 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3636 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
3641 * If there is no entry we have to punt to the slow path to perform
3642 * actual lookup. Should there be nothing with this name a negative
3643 * entry will be created.
3645 if (__predict_false(ncp == NULL)) {
3646 return (cache_fpl_partial(fpl));
3649 tvp = atomic_load_ptr(&ncp->nc_vp);
3650 nc_flag = atomic_load_char(&ncp->nc_flag);
3651 if ((nc_flag & NCF_NEGATIVE) != 0) {
3653 * If they want to create an entry we need to replace this one.
3655 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
3656 return (cache_fpl_partial(fpl));
3658 negstate = NCP2NEGSTATE(ncp);
3659 neg_hot = ((negstate->neg_flag & NEG_HOT) != 0);
3660 if (__predict_false(!cache_ncp_canuse(ncp))) {
3661 return (cache_fpl_partial(fpl));
3663 if (__predict_false((nc_flag & NCF_WHITE) != 0)) {
3664 return (cache_fpl_partial(fpl));
3667 return (cache_fplookup_negative_promote(fpl, ncp, hash));
3669 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp,
3671 counter_u64_add(numneghits, 1);
3672 cache_fpl_smr_exit(fpl);
3673 return (cache_fpl_handled(fpl, ENOENT));
3676 if (__predict_false(!cache_ncp_canuse(ncp))) {
3677 return (cache_fpl_partial(fpl));
3681 fpl->tvp_seqc = vn_seqc_read_any(tvp);
3682 if (seqc_in_modify(fpl->tvp_seqc)) {
3683 return (cache_fpl_partial(fpl));
3686 if (!cache_fplookup_vnode_supported(tvp)) {
3687 return (cache_fpl_partial(fpl));
3690 counter_u64_add(numposhits, 1);
3691 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
3696 cache_fplookup_mp_supported(struct mount *mp)
3701 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
3707 * Walk up the mount stack (if any).
3709 * Correctness is provided in the following ways:
3710 * - all vnodes are protected from freeing with SMR
3711 * - struct mount objects are type stable making them always safe to access
3712 * - stability of the particular mount is provided by busying it
3713 * - relationship between the vnode which is mounted on and the mount is
3714 * verified with the vnode sequence counter after busying
3715 * - association between root vnode of the mount and the mount is protected
3718 * From that point on we can read the sequence counter of the root vnode
3719 * and get the next mount on the stack (if any) using the same protection.
3721 * By the end of successful walk we are guaranteed the reached state was
3722 * indeed present at least at some point which matches the regular lookup.
3724 static int __noinline
3725 cache_fplookup_climb_mount(struct cache_fpl *fpl)
3727 struct mount *mp, *prev_mp;
3732 vp_seqc = fpl->tvp_seqc;
3734 VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
3735 mp = atomic_load_ptr(&vp->v_mountedhere);
3741 if (!vfs_op_thread_enter_crit(mp)) {
3742 if (prev_mp != NULL)
3743 vfs_op_thread_exit_crit(prev_mp);
3744 return (cache_fpl_partial(fpl));
3746 if (prev_mp != NULL)
3747 vfs_op_thread_exit_crit(prev_mp);
3748 if (!vn_seqc_consistent(vp, vp_seqc)) {
3749 vfs_op_thread_exit_crit(mp);
3750 return (cache_fpl_partial(fpl));
3752 if (!cache_fplookup_mp_supported(mp)) {
3753 vfs_op_thread_exit_crit(mp);
3754 return (cache_fpl_partial(fpl));
3756 vp = atomic_load_ptr(&mp->mnt_rootvnode);
3757 if (vp == NULL || VN_IS_DOOMED(vp)) {
3758 vfs_op_thread_exit_crit(mp);
3759 return (cache_fpl_partial(fpl));
3761 vp_seqc = vn_seqc_read_any(vp);
3762 if (seqc_in_modify(vp_seqc)) {
3763 vfs_op_thread_exit_crit(mp);
3764 return (cache_fpl_partial(fpl));
3767 mp = atomic_load_ptr(&vp->v_mountedhere);
3772 vfs_op_thread_exit_crit(prev_mp);
3774 fpl->tvp_seqc = vp_seqc;
3779 cache_fplookup_need_climb_mount(struct cache_fpl *fpl)
3787 * Hack: while this is a union, the pointer tends to be NULL so save on
3790 mp = atomic_load_ptr(&vp->v_mountedhere);
3793 if (vp->v_type == VDIR)
3801 * The code is mostly copy-pasted from regular lookup, see lookup().
3802 * The structure is maintained along with comments for easier maintenance.
3803 * Deduplicating the code will become feasible after fast path lookup
3804 * becomes more feature-complete.
3807 cache_fplookup_parse(struct cache_fpl *fpl)
3809 struct nameidata *ndp;
3810 struct componentname *cnp;
3817 * Search a new directory.
3819 * The last component of the filename is left accessible via
3820 * cnp->cn_nameptr for callers that need the name. Callers needing
3821 * the name set the SAVENAME flag. When done, they assume
3822 * responsibility for freeing the pathname buffer.
3824 for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
3826 cnp->cn_namelen = cp - cnp->cn_nameptr;
3827 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
3828 cache_fpl_smr_exit(fpl);
3829 return (cache_fpl_handled(fpl, ENAMETOOLONG));
3831 ndp->ni_pathlen -= cnp->cn_namelen;
3832 KASSERT(ndp->ni_pathlen <= PATH_MAX,
3833 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
3837 * Replace multiple slashes by a single slash and trailing slashes
3838 * by a null. This must be done before VOP_LOOKUP() because some
3839 * fs's don't know about trailing slashes. Remember if there were
3840 * trailing slashes to handle symlinks, existing non-directories
3841 * and non-existing files that won't be directories specially later.
3843 while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
3849 * Regular lookup performs the following:
3850 * *ndp->ni_next = '\0';
3851 * cnp->cn_flags |= TRAILINGSLASH;
3853 * Which is problematic since it modifies data read
3854 * from userspace. Then if fast path lookup was to
3855 * abort we would have to either restore it or convey
3856 * the flag. Since this is a corner case just ignore
3857 * it for simplicity.
3859 return (cache_fpl_partial(fpl));
3865 * Check for degenerate name (e.g. / or "")
3866 * which is a way of talking about a directory,
3867 * e.g. like "/." or ".".
3870 * Another corner case handled by the regular lookup
3872 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
3873 return (cache_fpl_partial(fpl));
3879 cache_fplookup_parse_advance(struct cache_fpl *fpl)
3881 struct nameidata *ndp;
3882 struct componentname *cnp;
3887 cnp->cn_nameptr = ndp->ni_next;
3888 while (*cnp->cn_nameptr == '/') {
3894 static int __noinline
3895 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
3901 * Can happen when racing against vgone.
3904 cache_fpl_partial(fpl);
3908 * See the API contract for VOP_FPLOOKUP_VEXEC.
3910 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
3911 error = cache_fpl_aborted(fpl);
3913 cache_fpl_smr_exit(fpl);
3914 cache_fpl_handled(fpl, error);
3922 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
3924 struct nameidata *ndp;
3925 struct componentname *cnp;
3929 error = CACHE_FPL_FAILED;
3933 cache_fpl_checkpoint(fpl, &fpl->snd);
3936 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
3937 if (seqc_in_modify(fpl->dvp_seqc)) {
3938 cache_fpl_aborted(fpl);
3941 mp = atomic_load_ptr(&fpl->dvp->v_mount);
3942 if (!cache_fplookup_mp_supported(mp)) {
3943 cache_fpl_aborted(fpl);
3947 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
3950 error = cache_fplookup_parse(fpl);
3951 if (__predict_false(error != 0)) {
3955 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
3957 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
3958 if (__predict_false(error != 0)) {
3959 error = cache_fplookup_failed_vexec(fpl, error);
3963 if (__predict_false(cache_fpl_isdotdot(cnp))) {
3964 error = cache_fplookup_dotdot(fpl);
3965 if (__predict_false(error != 0)) {
3969 error = cache_fplookup_next(fpl);
3970 if (__predict_false(error != 0)) {
3974 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
3976 if (cache_fplookup_need_climb_mount(fpl)) {
3977 error = cache_fplookup_climb_mount(fpl);
3978 if (__predict_false(error != 0)) {
3984 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
3986 if (cache_fpl_islastcn(ndp)) {
3987 error = cache_fplookup_final(fpl);
3991 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
3992 error = cache_fpl_aborted(fpl);
3996 fpl->dvp = fpl->tvp;
3997 fpl->dvp_seqc = fpl->tvp_seqc;
3999 cache_fplookup_parse_advance(fpl);
4000 cache_fpl_checkpoint(fpl, &fpl->snd);
4003 switch (fpl->status) {
4004 case CACHE_FPL_STATUS_UNSET:
4005 __assert_unreachable();
4007 case CACHE_FPL_STATUS_PARTIAL:
4008 cache_fpl_smr_assert_entered(fpl);
4009 return (cache_fplookup_partial_setup(fpl));
4010 case CACHE_FPL_STATUS_ABORTED:
4012 cache_fpl_smr_exit(fpl);
4013 return (CACHE_FPL_FAILED);
4014 case CACHE_FPL_STATUS_HANDLED:
4015 MPASS(error != CACHE_FPL_FAILED);
4016 cache_fpl_smr_assert_not_entered(fpl);
4017 if (__predict_false(error != 0)) {
4020 cache_fpl_cleanup_cnp(cnp);
4023 ndp->ni_dvp = fpl->dvp;
4024 ndp->ni_vp = fpl->tvp;
4025 if (cnp->cn_flags & SAVENAME)
4026 cnp->cn_flags |= HASBUF;
4028 cache_fpl_cleanup_cnp(cnp);
4034 * Fast path lookup protected with SMR and sequence counters.
4036 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
4038 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
4041 * Traditional vnode lookup conceptually looks like this:
4047 * vn_unlock(current);
4054 * Each jump to the next vnode is safe memory-wise and atomic with respect to
4055 * any modifications thanks to holding respective locks.
4057 * The same guarantee can be provided with a combination of safe memory
4058 * reclamation and sequence counters instead. If all operations which affect
4059 * the relationship between the current vnode and the one we are looking for
4060 * also modify the counter, we can verify whether all the conditions held as
4061 * we made the jump. This includes things like permissions, mount points etc.
4062 * Counter modification is provided by enclosing relevant places in
4063 * vn_seqc_write_begin()/end() calls.
4065 * Thus this translates to:
4068 * dvp_seqc = seqc_read_any(dvp);
4069 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
4073 * tvp_seqc = seqc_read_any(tvp);
4074 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
4076 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
4078 * dvp = tvp; // we know nothing of importance has changed
4079 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
4083 * vget(); // secure the vnode
4084 * if (!seqc_consistent(tvp, tvp_seqc) // final check
4086 * // at this point we know nothing has changed for any parent<->child pair
4087 * // as they were crossed during the lookup, meaning we matched the guarantee
4088 * // of the locked variant
4091 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
4092 * - they are called while within vfs_smr protection which they must never exit
4093 * - EAGAIN can be returned to denote checking could not be performed, it is
4094 * always valid to return it
4095 * - if the sequence counter has not changed the result must be valid
4096 * - if the sequence counter has changed both false positives and false negatives
4097 * are permitted (since the result will be rejected later)
4098 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
4100 * Caveats to watch out for:
4101 * - vnodes are passed unlocked and unreferenced with nothing stopping
4102 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
4103 * to use atomic_load_ptr to fetch it.
4104 * - the aforementioned object can also get freed, meaning absent other means it
4105 * should be protected with vfs_smr
4106 * - either safely checking permissions as they are modified or guaranteeing
4107 * their stability is left to the routine
4110 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
4113 struct cache_fpl fpl;
4116 struct componentname *cnp;
4117 struct nameidata_saved orig;
4120 MPASS(ndp->ni_lcf == 0);
4122 fpl.status = CACHE_FPL_STATUS_UNSET;
4124 fpl.cnp = &ndp->ni_cnd;
4125 MPASS(curthread == fpl.cnp->cn_thread);
4127 if ((fpl.cnp->cn_flags & SAVESTART) != 0)
4128 MPASS(fpl.cnp->cn_nameiop != LOOKUP);
4130 if (!cache_can_fplookup(&fpl)) {
4131 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4132 *status = fpl.status;
4133 return (EOPNOTSUPP);
4136 cache_fpl_checkpoint(&fpl, &orig);
4138 cache_fpl_smr_enter_initial(&fpl);
4139 pwd = pwd_get_smr();
4141 ndp->ni_rootdir = pwd->pwd_rdir;
4142 ndp->ni_topdir = pwd->pwd_jdir;
4145 cnp->cn_nameptr = cnp->cn_pnbuf;
4146 if (cnp->cn_pnbuf[0] == '/') {
4147 cache_fpl_handle_root(ndp, &dvp);
4149 MPASS(ndp->ni_dirfd == AT_FDCWD);
4150 dvp = pwd->pwd_cdir;
4153 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
4155 error = cache_fplookup_impl(dvp, &fpl);
4156 cache_fpl_smr_assert_not_entered(&fpl);
4157 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4159 *status = fpl.status;
4160 switch (fpl.status) {
4161 case CACHE_FPL_STATUS_UNSET:
4162 __assert_unreachable();
4164 case CACHE_FPL_STATUS_HANDLED:
4165 SDT_PROBE3(vfs, namei, lookup, return, error,
4166 (error == 0 ? ndp->ni_vp : NULL), true);
4168 case CACHE_FPL_STATUS_PARTIAL:
4171 * Status restored by cache_fplookup_partial_setup.
4174 case CACHE_FPL_STATUS_ABORTED:
4175 cache_fpl_restore(&fpl, &orig);