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>
54 #include <sys/mount.h>
55 #include <sys/namei.h>
57 #include <sys/rwlock.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 SDT_PROVIDER_DECLARE(vfs);
83 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
85 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
87 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
88 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
89 "char *", "struct vnode *");
90 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
91 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
92 "struct vnode *", "char *");
93 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
95 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
96 "struct vnode *", "char *");
97 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
99 SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
100 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
101 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
102 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
104 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
106 SDT_PROBE_DEFINE2(vfs, namecache, shrink_negative, done, "struct vnode *",
109 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
110 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
111 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
114 * This structure describes the elements in the cache of recent
115 * names looked up by namei.
120 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
121 "the state must fit in a union with a pointer without growing it");
124 CK_LIST_ENTRY(namecache) nc_hash;/* hash chain */
125 LIST_ENTRY(namecache) nc_src; /* source vnode list */
126 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
127 struct vnode *nc_dvp; /* vnode of parent of name */
129 struct vnode *nu_vp; /* vnode the name refers to */
130 struct negstate nu_neg;/* negative entry state */
132 u_char nc_flag; /* flag bits */
133 u_char nc_nlen; /* length of name */
134 char nc_name[0]; /* segment name + nul */
138 * struct namecache_ts repeats struct namecache layout up to the
140 * struct namecache_ts is used in place of struct namecache when time(s) need
141 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
142 * both a non-dotdot directory name plus dotdot for the directory's
145 struct namecache_ts {
146 struct timespec nc_time; /* timespec provided by fs */
147 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
148 int nc_ticks; /* ticks value when entry was added */
149 struct namecache nc_nc;
152 #define nc_vp n_un.nu_vp
153 #define nc_neg n_un.nu_neg
156 * Flags in namecache.nc_flag
158 #define NCF_WHITE 0x01
159 #define NCF_ISDOTDOT 0x02
162 #define NCF_DVDROP 0x10
163 #define NCF_NEGATIVE 0x20
164 #define NCF_INVALID 0x40
167 * Flags in negstate.neg_flag
172 * Mark an entry as invalid.
174 * This is called before it starts getting deconstructed.
177 cache_ncp_invalidate(struct namecache *ncp)
180 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
181 ("%s: entry %p already invalid", __func__, ncp));
182 ncp->nc_flag |= NCF_INVALID;
183 atomic_thread_fence_rel();
187 * Verify validity of an entry.
189 * All places which elide locks are supposed to call this after they are
190 * done with reading from an entry.
193 cache_ncp_invalid(struct namecache *ncp)
196 atomic_thread_fence_acq();
197 return ((ncp->nc_flag & NCF_INVALID) != 0);
201 * Name caching works as follows:
203 * Names found by directory scans are retained in a cache
204 * for future reference. It is managed LRU, so frequently
205 * used names will hang around. Cache is indexed by hash value
206 * obtained from (dvp, name) where dvp refers to the directory
209 * If it is a "negative" entry, (i.e. for a name that is known NOT to
210 * exist) the vnode pointer will be NULL.
212 * Upon reaching the last segment of a path, if the reference
213 * is for DELETE, or NOCACHE is set (rewrite), and the
214 * name is located in the cache, it will be dropped.
216 * These locks are used (in the order in which they can be taken):
218 * vnodelock mtx vnode lists and v_cache_dd field protection
219 * bucketlock rwlock for access to given set of hash buckets
220 * neglist mtx negative entry LRU management
222 * Additionally, ncneg_shrink_lock mtx is used to have at most one thread
223 * shrinking the LRU list.
225 * It is legal to take multiple vnodelock and bucketlock locks. The locking
226 * order is lower address first. Both are recursive.
228 * "." lookups are lockless.
230 * ".." and vnode -> name lookups require vnodelock.
232 * name -> vnode lookup requires the relevant bucketlock to be held for reading.
234 * Insertions and removals of entries require involved vnodes and bucketlocks
235 * to be write-locked to prevent other threads from seeing the entry.
237 * Some lookups result in removal of the found entry (e.g. getting rid of a
238 * negative entry with the intent to create a positive one), which poses a
239 * problem when multiple threads reach the state. Similarly, two different
240 * threads can purge two different vnodes and try to remove the same name.
242 * If the already held vnode lock is lower than the second required lock, we
243 * can just take the other lock. However, in the opposite case, this could
244 * deadlock. As such, this is resolved by trylocking and if that fails unlocking
245 * the first node, locking everything in order and revalidating the state.
251 * Structures associated with name caching.
253 #define NCHHASH(hash) \
254 (&nchashtbl[(hash) & nchash])
255 static __read_mostly CK_LIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
256 static u_long __read_mostly nchash; /* size of hash table */
257 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
258 "Size of namecache hash table");
259 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
260 SYSCTL_ULONG(_vfs, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
261 "Ratio of negative namecache entries");
262 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
263 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
264 u_int ncsizefactor = 2;
265 SYSCTL_UINT(_vfs, OID_AUTO, ncsizefactor, CTLFLAG_RW, &ncsizefactor, 0,
266 "Size factor for namecache");
267 static u_int __read_mostly ncpurgeminvnodes;
268 SYSCTL_UINT(_vfs, OID_AUTO, ncpurgeminvnodes, CTLFLAG_RW, &ncpurgeminvnodes, 0,
269 "Number of vnodes below which purgevfs ignores the request");
270 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
272 struct nchstats nchstats; /* cache effectiveness statistics */
274 static struct mtx __exclusive_cache_line ncneg_shrink_lock;
278 TAILQ_HEAD(, namecache) nl_list;
279 } __aligned(CACHE_LINE_SIZE);
281 static struct neglist __read_mostly *neglists;
282 static struct neglist ncneg_hot;
283 static u_long numhotneg;
285 #define numneglists (ncneghash + 1)
286 static u_int __read_mostly ncneghash;
287 static inline struct neglist *
288 NCP2NEGLIST(struct namecache *ncp)
291 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
294 static inline struct negstate *
295 NCP2NEGSTATE(struct namecache *ncp)
298 MPASS(ncp->nc_flag & NCF_NEGATIVE);
299 return (&ncp->nc_neg);
302 #define numbucketlocks (ncbuckethash + 1)
303 static u_int __read_mostly ncbuckethash;
304 static struct rwlock_padalign __read_mostly *bucketlocks;
305 #define HASH2BUCKETLOCK(hash) \
306 ((struct rwlock *)(&bucketlocks[((hash) & ncbuckethash)]))
308 #define numvnodelocks (ncvnodehash + 1)
309 static u_int __read_mostly ncvnodehash;
310 static struct mtx __read_mostly *vnodelocks;
311 static inline struct mtx *
312 VP2VNODELOCK(struct vnode *vp)
315 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
319 * UMA zones for the VFS cache.
321 * The small cache is used for entries with short names, which are the
322 * most common. The large cache is used for entries which are too big to
323 * fit in the small cache.
325 static uma_zone_t __read_mostly cache_zone_small;
326 static uma_zone_t __read_mostly cache_zone_small_ts;
327 static uma_zone_t __read_mostly cache_zone_large;
328 static uma_zone_t __read_mostly cache_zone_large_ts;
330 #define CACHE_PATH_CUTOFF 35
332 static struct namecache *
333 cache_alloc(int len, int ts)
335 struct namecache_ts *ncp_ts;
336 struct namecache *ncp;
338 if (__predict_false(ts)) {
339 if (len <= CACHE_PATH_CUTOFF)
340 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
342 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
343 ncp = &ncp_ts->nc_nc;
345 if (len <= CACHE_PATH_CUTOFF)
346 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
348 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
354 cache_free(struct namecache *ncp)
356 struct namecache_ts *ncp_ts;
360 if ((ncp->nc_flag & NCF_DVDROP) != 0)
362 if (__predict_false(ncp->nc_flag & NCF_TS)) {
363 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
364 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
365 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
367 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
369 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
370 uma_zfree_smr(cache_zone_small, ncp);
372 uma_zfree_smr(cache_zone_large, ncp);
377 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
379 struct namecache_ts *ncp_ts;
381 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
382 (tsp == NULL && ticksp == NULL),
385 if (tsp == NULL && ticksp == NULL)
388 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
390 *tsp = ncp_ts->nc_time;
392 *ticksp = ncp_ts->nc_ticks;
396 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
397 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
398 "VFS namecache enabled");
401 /* Export size information to userland */
402 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
403 sizeof(struct namecache), "sizeof(struct namecache)");
406 * The new name cache statistics
408 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
409 "Name cache statistics");
410 #define STATNODE_ULONG(name, descr) \
411 SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, descr);
412 #define STATNODE_COUNTER(name, descr) \
413 static COUNTER_U64_DEFINE_EARLY(name); \
414 SYSCTL_COUNTER_U64(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, \
416 STATNODE_ULONG(numneg, "Number of negative cache entries");
417 STATNODE_ULONG(numcache, "Number of cache entries");
418 STATNODE_COUNTER(numcachehv, "Number of namecache entries with vnodes held");
419 STATNODE_COUNTER(numdrops, "Number of dropped entries due to reaching the limit");
420 STATNODE_COUNTER(dothits, "Number of '.' hits");
421 STATNODE_COUNTER(dotdothits, "Number of '..' hits");
422 STATNODE_COUNTER(nummiss, "Number of cache misses");
423 STATNODE_COUNTER(nummisszap, "Number of cache misses we do not want to cache");
424 STATNODE_COUNTER(numposzaps,
425 "Number of cache hits (positive) we do not want to cache");
426 STATNODE_COUNTER(numposhits, "Number of cache hits (positive)");
427 STATNODE_COUNTER(numnegzaps,
428 "Number of cache hits (negative) we do not want to cache");
429 STATNODE_COUNTER(numneghits, "Number of cache hits (negative)");
430 /* These count for vn_getcwd(), too. */
431 STATNODE_COUNTER(numfullpathcalls, "Number of fullpath search calls");
432 STATNODE_COUNTER(numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
433 STATNODE_COUNTER(numfullpathfail2,
434 "Number of fullpath search errors (VOP_VPTOCNP failures)");
435 STATNODE_COUNTER(numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
436 STATNODE_COUNTER(numfullpathfound, "Number of successful fullpath calls");
437 STATNODE_COUNTER(zap_and_exit_bucket_relock_success,
438 "Number of successful removals after relocking");
439 static long zap_and_exit_bucket_fail; STATNODE_ULONG(zap_and_exit_bucket_fail,
440 "Number of times zap_and_exit failed to lock");
441 static long zap_and_exit_bucket_fail2; STATNODE_ULONG(zap_and_exit_bucket_fail2,
442 "Number of times zap_and_exit failed to lock");
443 static long cache_lock_vnodes_cel_3_failures;
444 STATNODE_ULONG(cache_lock_vnodes_cel_3_failures,
445 "Number of times 3-way vnode locking failed");
446 STATNODE_ULONG(numhotneg, "Number of hot negative entries");
447 STATNODE_COUNTER(numneg_evicted,
448 "Number of negative entries evicted when adding a new entry");
449 STATNODE_COUNTER(shrinking_skipped,
450 "Number of times shrinking was already in progress");
452 static void cache_zap_locked(struct namecache *ncp);
453 static int vn_fullpath_hardlink(struct thread *td, struct nameidata *ndp, char **retbuf,
454 char **freebuf, size_t *buflen);
455 static int vn_fullpath_any(struct thread *td, struct vnode *vp, struct vnode *rdir,
456 char *buf, char **retbuf, size_t *buflen);
457 static int vn_fullpath_dir(struct thread *td, struct vnode *vp, struct vnode *rdir,
458 char *buf, char **retbuf, size_t *len, bool slash_prefixed, size_t addend);
460 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
462 static int cache_yield;
463 SYSCTL_INT(_vfs_cache, OID_AUTO, yield, CTLFLAG_RD, &cache_yield, 0,
464 "Number of times cache called yield");
466 static void __noinline
467 cache_maybe_yield(void)
470 if (should_yield()) {
472 kern_yield(PRI_USER);
477 cache_assert_vlp_locked(struct mtx *vlp)
481 mtx_assert(vlp, MA_OWNED);
485 cache_assert_vnode_locked(struct vnode *vp)
489 vlp = VP2VNODELOCK(vp);
490 cache_assert_vlp_locked(vlp);
494 cache_get_hash(char *name, u_char len, struct vnode *dvp)
498 hash = fnv_32_buf(name, len, FNV1_32_INIT);
499 hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
503 static inline struct rwlock *
504 NCP2BUCKETLOCK(struct namecache *ncp)
508 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
509 return (HASH2BUCKETLOCK(hash));
514 cache_assert_bucket_locked(struct namecache *ncp, int mode)
518 blp = NCP2BUCKETLOCK(ncp);
519 rw_assert(blp, mode);
522 #define cache_assert_bucket_locked(x, y) do { } while (0)
525 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
527 _cache_sort_vnodes(void **p1, void **p2)
531 MPASS(*p1 != NULL || *p2 != NULL);
541 cache_lock_all_buckets(void)
545 for (i = 0; i < numbucketlocks; i++)
546 rw_wlock(&bucketlocks[i]);
550 cache_unlock_all_buckets(void)
554 for (i = 0; i < numbucketlocks; i++)
555 rw_wunlock(&bucketlocks[i]);
559 cache_lock_all_vnodes(void)
563 for (i = 0; i < numvnodelocks; i++)
564 mtx_lock(&vnodelocks[i]);
568 cache_unlock_all_vnodes(void)
572 for (i = 0; i < numvnodelocks; i++)
573 mtx_unlock(&vnodelocks[i]);
577 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
580 cache_sort_vnodes(&vlp1, &vlp2);
583 if (!mtx_trylock(vlp1))
586 if (!mtx_trylock(vlp2)) {
596 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
599 MPASS(vlp1 != NULL || vlp2 != NULL);
609 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
612 MPASS(vlp1 != NULL || vlp2 != NULL);
621 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
623 struct nchstats snap;
625 if (req->oldptr == NULL)
626 return (SYSCTL_OUT(req, 0, sizeof(snap)));
629 snap.ncs_goodhits = counter_u64_fetch(numposhits);
630 snap.ncs_neghits = counter_u64_fetch(numneghits);
631 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
632 counter_u64_fetch(numnegzaps);
633 snap.ncs_miss = counter_u64_fetch(nummisszap) +
634 counter_u64_fetch(nummiss);
636 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
638 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
639 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
640 "VFS cache effectiveness statistics");
644 * Grab an atomic snapshot of the name cache hash chain lengths
646 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
647 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
651 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
653 struct nchashhead *ncpp;
654 struct namecache *ncp;
655 int i, error, n_nchash, *cntbuf;
658 n_nchash = nchash + 1; /* nchash is max index, not count */
659 if (req->oldptr == NULL)
660 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
661 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
662 cache_lock_all_buckets();
663 if (n_nchash != nchash + 1) {
664 cache_unlock_all_buckets();
665 free(cntbuf, M_TEMP);
668 /* Scan hash tables counting entries */
669 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
670 CK_LIST_FOREACH(ncp, ncpp, nc_hash)
672 cache_unlock_all_buckets();
673 for (error = 0, i = 0; i < n_nchash; i++)
674 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
676 free(cntbuf, M_TEMP);
679 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
680 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
681 "nchash chain lengths");
684 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
687 struct nchashhead *ncpp;
688 struct namecache *ncp;
690 int count, maxlength, used, pct;
693 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
695 cache_lock_all_buckets();
696 n_nchash = nchash + 1; /* nchash is max index, not count */
700 /* Scan hash tables for applicable entries */
701 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
703 CK_LIST_FOREACH(ncp, ncpp, nc_hash) {
708 if (maxlength < count)
711 n_nchash = nchash + 1;
712 cache_unlock_all_buckets();
713 pct = (used * 100) / (n_nchash / 100);
714 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
717 error = SYSCTL_OUT(req, &used, sizeof(used));
720 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
723 error = SYSCTL_OUT(req, &pct, sizeof(pct));
728 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
729 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
730 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
734 * Negative entries management
736 * A variation of LRU scheme is used. New entries are hashed into one of
737 * numneglists cold lists. Entries get promoted to the hot list on first hit.
739 * The shrinker will demote hot list head and evict from the cold list in a
740 * round-robin manner.
743 cache_negative_init(struct namecache *ncp)
745 struct negstate *negstate;
747 ncp->nc_flag |= NCF_NEGATIVE;
748 negstate = NCP2NEGSTATE(ncp);
749 negstate->neg_flag = 0;
753 cache_negative_hit(struct namecache *ncp)
755 struct neglist *neglist;
756 struct negstate *negstate;
758 negstate = NCP2NEGSTATE(ncp);
759 if ((negstate->neg_flag & NEG_HOT) != 0)
761 neglist = NCP2NEGLIST(ncp);
762 mtx_lock(&ncneg_hot.nl_lock);
763 mtx_lock(&neglist->nl_lock);
764 if ((negstate->neg_flag & NEG_HOT) == 0) {
766 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
767 TAILQ_INSERT_TAIL(&ncneg_hot.nl_list, ncp, nc_dst);
768 negstate->neg_flag |= NEG_HOT;
770 mtx_unlock(&neglist->nl_lock);
771 mtx_unlock(&ncneg_hot.nl_lock);
775 cache_negative_insert(struct namecache *ncp)
777 struct neglist *neglist;
779 MPASS(ncp->nc_flag & NCF_NEGATIVE);
780 cache_assert_bucket_locked(ncp, RA_WLOCKED);
781 neglist = NCP2NEGLIST(ncp);
782 mtx_lock(&neglist->nl_lock);
783 TAILQ_INSERT_TAIL(&neglist->nl_list, ncp, nc_dst);
784 mtx_unlock(&neglist->nl_lock);
785 atomic_add_rel_long(&numneg, 1);
789 cache_negative_remove(struct namecache *ncp)
791 struct neglist *neglist;
792 struct negstate *negstate;
793 bool hot_locked = false;
794 bool list_locked = false;
796 cache_assert_bucket_locked(ncp, RA_WLOCKED);
797 neglist = NCP2NEGLIST(ncp);
798 negstate = NCP2NEGSTATE(ncp);
799 if ((negstate->neg_flag & NEG_HOT) != 0) {
801 mtx_lock(&ncneg_hot.nl_lock);
802 if ((negstate->neg_flag & NEG_HOT) == 0) {
804 mtx_lock(&neglist->nl_lock);
808 mtx_lock(&neglist->nl_lock);
810 * We may be racing against promotion in lockless lookup.
812 if ((negstate->neg_flag & NEG_HOT) != 0) {
813 mtx_unlock(&neglist->nl_lock);
815 mtx_lock(&ncneg_hot.nl_lock);
816 mtx_lock(&neglist->nl_lock);
819 if ((negstate->neg_flag & NEG_HOT) != 0) {
820 mtx_assert(&ncneg_hot.nl_lock, MA_OWNED);
821 TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
824 mtx_assert(&neglist->nl_lock, MA_OWNED);
825 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
828 mtx_unlock(&neglist->nl_lock);
830 mtx_unlock(&ncneg_hot.nl_lock);
831 atomic_subtract_rel_long(&numneg, 1);
835 cache_negative_shrink_select(struct namecache **ncpp,
836 struct neglist **neglistpp)
838 struct neglist *neglist;
839 struct namecache *ncp;
845 for (i = 0; i < numneglists; i++) {
846 neglist = &neglists[(cycle + i) % numneglists];
847 if (TAILQ_FIRST(&neglist->nl_list) == NULL)
849 mtx_lock(&neglist->nl_lock);
850 ncp = TAILQ_FIRST(&neglist->nl_list);
853 mtx_unlock(&neglist->nl_lock);
856 *neglistpp = neglist;
862 cache_negative_zap_one(void)
864 struct namecache *ncp, *ncp2;
865 struct neglist *neglist;
866 struct negstate *negstate;
870 if (mtx_owner(&ncneg_shrink_lock) != NULL ||
871 !mtx_trylock(&ncneg_shrink_lock)) {
872 counter_u64_add(shrinking_skipped, 1);
876 mtx_lock(&ncneg_hot.nl_lock);
877 ncp = TAILQ_FIRST(&ncneg_hot.nl_list);
879 neglist = NCP2NEGLIST(ncp);
880 negstate = NCP2NEGSTATE(ncp);
881 mtx_lock(&neglist->nl_lock);
882 MPASS((negstate->neg_flag & NEG_HOT) != 0);
883 TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
884 TAILQ_INSERT_TAIL(&neglist->nl_list, ncp, nc_dst);
885 negstate->neg_flag &= ~NEG_HOT;
887 mtx_unlock(&neglist->nl_lock);
889 mtx_unlock(&ncneg_hot.nl_lock);
891 cache_negative_shrink_select(&ncp, &neglist);
893 mtx_unlock(&ncneg_shrink_lock);
897 MPASS(ncp->nc_flag & NCF_NEGATIVE);
898 dvlp = VP2VNODELOCK(ncp->nc_dvp);
899 blp = NCP2BUCKETLOCK(ncp);
900 mtx_unlock(&neglist->nl_lock);
904 * Enter SMR to safely check the negative list.
905 * Even if the found pointer matches, the entry may now be reallocated
906 * and used by a different vnode.
909 ncp2 = TAILQ_FIRST(&neglist->nl_list);
910 if (ncp != ncp2 || dvlp != VP2VNODELOCK(ncp2->nc_dvp) ||
911 blp != NCP2BUCKETLOCK(ncp2)) {
916 SDT_PROBE2(vfs, namecache, shrink_negative, done, ncp->nc_dvp,
918 cache_zap_locked(ncp);
919 counter_u64_add(numneg_evicted, 1);
927 * cache_zap_locked():
929 * Removes a namecache entry from cache, whether it contains an actual
930 * pointer to a vnode or if it is just a negative cache entry.
933 cache_zap_locked(struct namecache *ncp)
936 if (!(ncp->nc_flag & NCF_NEGATIVE))
937 cache_assert_vnode_locked(ncp->nc_vp);
938 cache_assert_vnode_locked(ncp->nc_dvp);
939 cache_assert_bucket_locked(ncp, RA_WLOCKED);
941 CTR2(KTR_VFS, "cache_zap(%p) vp %p", ncp,
942 (ncp->nc_flag & NCF_NEGATIVE) ? NULL : ncp->nc_vp);
944 cache_ncp_invalidate(ncp);
946 CK_LIST_REMOVE(ncp, nc_hash);
947 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
948 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
949 ncp->nc_name, ncp->nc_vp);
950 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
951 if (ncp == ncp->nc_vp->v_cache_dd)
952 ncp->nc_vp->v_cache_dd = NULL;
954 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
956 cache_negative_remove(ncp);
958 if (ncp->nc_flag & NCF_ISDOTDOT) {
959 if (ncp == ncp->nc_dvp->v_cache_dd)
960 ncp->nc_dvp->v_cache_dd = NULL;
962 LIST_REMOVE(ncp, nc_src);
963 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
964 ncp->nc_flag |= NCF_DVDROP;
965 counter_u64_add(numcachehv, -1);
968 atomic_subtract_rel_long(&numcache, 1);
972 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
976 MPASS(ncp->nc_dvp == vp);
977 MPASS(ncp->nc_flag & NCF_NEGATIVE);
978 cache_assert_vnode_locked(vp);
980 blp = NCP2BUCKETLOCK(ncp);
982 cache_zap_locked(ncp);
987 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
990 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
993 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
994 cache_assert_vnode_locked(vp);
996 if (ncp->nc_flag & NCF_NEGATIVE) {
1001 cache_zap_negative_locked_vnode_kl(ncp, vp);
1005 pvlp = VP2VNODELOCK(vp);
1006 blp = NCP2BUCKETLOCK(ncp);
1007 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1008 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1010 if (*vlpp == vlp1 || *vlpp == vlp2) {
1014 if (*vlpp != NULL) {
1018 cache_sort_vnodes(&vlp1, &vlp2);
1023 if (!mtx_trylock(vlp1))
1029 cache_zap_locked(ncp);
1031 if (to_unlock != NULL)
1032 mtx_unlock(to_unlock);
1039 MPASS(*vlpp == NULL);
1044 static int __noinline
1045 cache_zap_locked_vnode(struct namecache *ncp, struct vnode *vp)
1047 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1051 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1052 cache_assert_vnode_locked(vp);
1054 pvlp = VP2VNODELOCK(vp);
1055 if (ncp->nc_flag & NCF_NEGATIVE) {
1056 cache_zap_negative_locked_vnode_kl(ncp, vp);
1060 blp = NCP2BUCKETLOCK(ncp);
1061 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1062 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1063 cache_sort_vnodes(&vlp1, &vlp2);
1068 if (!mtx_trylock(vlp1)) {
1075 cache_zap_locked(ncp);
1077 mtx_unlock(to_unlock);
1084 * If trylocking failed we can get here. We know enough to take all needed locks
1085 * in the right order and re-lookup the entry.
1088 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1089 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1092 struct namecache *rncp;
1094 cache_assert_bucket_locked(ncp, RA_UNLOCKED);
1096 cache_sort_vnodes(&dvlp, &vlp);
1097 cache_lock_vnodes(dvlp, vlp);
1099 CK_LIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1100 if (rncp == ncp && rncp->nc_dvp == dvp &&
1101 rncp->nc_nlen == cnp->cn_namelen &&
1102 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1106 cache_zap_locked(rncp);
1108 cache_unlock_vnodes(dvlp, vlp);
1109 counter_u64_add(zap_and_exit_bucket_relock_success, 1);
1114 cache_unlock_vnodes(dvlp, vlp);
1118 static int __noinline
1119 cache_zap_wlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1120 uint32_t hash, struct rwlock *blp)
1122 struct mtx *dvlp, *vlp;
1125 cache_assert_bucket_locked(ncp, RA_WLOCKED);
1127 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1129 if (!(ncp->nc_flag & NCF_NEGATIVE))
1130 vlp = VP2VNODELOCK(ncp->nc_vp);
1131 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1132 cache_zap_locked(ncp);
1134 cache_unlock_vnodes(dvlp, vlp);
1140 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1143 static int __noinline
1144 cache_zap_rlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1145 uint32_t hash, struct rwlock *blp)
1147 struct mtx *dvlp, *vlp;
1150 cache_assert_bucket_locked(ncp, RA_RLOCKED);
1152 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1154 if (!(ncp->nc_flag & NCF_NEGATIVE))
1155 vlp = VP2VNODELOCK(ncp->nc_vp);
1156 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1159 cache_zap_locked(ncp);
1161 cache_unlock_vnodes(dvlp, vlp);
1167 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1171 cache_zap_wlocked_bucket_kl(struct namecache *ncp, struct rwlock *blp,
1172 struct mtx **vlpp1, struct mtx **vlpp2)
1174 struct mtx *dvlp, *vlp;
1176 cache_assert_bucket_locked(ncp, RA_WLOCKED);
1178 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1180 if (!(ncp->nc_flag & NCF_NEGATIVE))
1181 vlp = VP2VNODELOCK(ncp->nc_vp);
1182 cache_sort_vnodes(&dvlp, &vlp);
1184 if (*vlpp1 == dvlp && *vlpp2 == vlp) {
1185 cache_zap_locked(ncp);
1186 cache_unlock_vnodes(dvlp, vlp);
1199 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1200 cache_zap_locked(ncp);
1201 cache_unlock_vnodes(dvlp, vlp);
1216 cache_lookup_unlock(struct rwlock *blp, struct mtx *vlp)
1226 static int __noinline
1227 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1228 struct timespec *tsp, int *ticksp)
1233 CTR2(KTR_VFS, "cache_lookup(%p, %s) found via .",
1234 dvp, cnp->cn_nameptr);
1235 counter_u64_add(dothits, 1);
1236 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1243 * When we lookup "." we still can be asked to lock it
1246 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1247 if (ltype != VOP_ISLOCKED(*vpp)) {
1248 if (ltype == LK_EXCLUSIVE) {
1249 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1250 if (VN_IS_DOOMED((*vpp))) {
1251 /* forced unmount */
1257 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1262 static __noinline int
1263 cache_lookup_nomakeentry(struct vnode *dvp, struct vnode **vpp,
1264 struct componentname *cnp, struct timespec *tsp, int *ticksp)
1266 struct namecache *ncp;
1268 struct mtx *dvlp, *dvlp2;
1272 if (cnp->cn_namelen == 2 &&
1273 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1274 counter_u64_add(dotdothits, 1);
1275 dvlp = VP2VNODELOCK(dvp);
1279 ncp = dvp->v_cache_dd;
1281 SDT_PROBE3(vfs, namecache, lookup, miss, dvp,
1288 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1289 if (ncp->nc_dvp != dvp)
1290 panic("dvp %p v_cache_dd %p\n", dvp, ncp);
1291 if (!cache_zap_locked_vnode_kl2(ncp,
1294 MPASS(dvp->v_cache_dd == NULL);
1300 dvp->v_cache_dd = NULL;
1308 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1309 blp = HASH2BUCKETLOCK(hash);
1311 if (CK_LIST_EMPTY(NCHHASH(hash)))
1316 CK_LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1317 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1318 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1322 /* We failed to find an entry */
1328 error = cache_zap_wlocked_bucket(ncp, cnp, hash, blp);
1329 if (__predict_false(error != 0)) {
1330 zap_and_exit_bucket_fail++;
1331 cache_maybe_yield();
1334 counter_u64_add(numposzaps, 1);
1338 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr, NULL);
1339 counter_u64_add(nummisszap, 1);
1344 * Lookup a name in the name cache
1348 * - dvp: Parent directory in which to search.
1349 * - vpp: Return argument. Will contain desired vnode on cache hit.
1350 * - cnp: Parameters of the name search. The most interesting bits of
1351 * the cn_flags field have the following meanings:
1352 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1354 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1355 * - tsp: Return storage for cache timestamp. On a successful (positive
1356 * or negative) lookup, tsp will be filled with any timespec that
1357 * was stored when this cache entry was created. However, it will
1358 * be clear for "." entries.
1359 * - ticks: Return storage for alternate cache timestamp. On a successful
1360 * (positive or negative) lookup, it will contain the ticks value
1361 * that was current when the cache entry was created, unless cnp
1366 * - -1: A positive cache hit. vpp will contain the desired vnode.
1367 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1368 * to a forced unmount. vpp will not be modified. If the entry
1369 * is a whiteout, then the ISWHITEOUT flag will be set in
1371 * - 0: A cache miss. vpp will not be modified.
1375 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1376 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1377 * lock is not recursively acquired.
1380 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1381 struct timespec *tsp, int *ticksp)
1383 struct namecache_ts *ncp_ts;
1384 struct namecache *ncp;
1385 struct negstate *negstate;
1391 bool try_smr, doing_smr, whiteout;
1394 if (__predict_false(!doingcache)) {
1395 cnp->cn_flags &= ~MAKEENTRY;
1400 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.'))
1401 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1403 if ((cnp->cn_flags & MAKEENTRY) == 0)
1404 return (cache_lookup_nomakeentry(dvp, vpp, cnp, tsp, ticksp));
1407 if (cnp->cn_nameiop == CREATE)
1414 if (cnp->cn_namelen == 2 &&
1415 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1416 counter_u64_add(dotdothits, 1);
1417 dvlp = VP2VNODELOCK(dvp);
1419 ncp = dvp->v_cache_dd;
1421 SDT_PROBE3(vfs, namecache, lookup, miss, dvp,
1426 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1427 if (ncp->nc_flag & NCF_NEGATIVE)
1433 /* Return failure if negative entry was found. */
1435 goto negative_success;
1436 CTR3(KTR_VFS, "cache_lookup(%p, %s) found %p via ..",
1437 dvp, cnp->cn_nameptr, *vpp);
1438 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..",
1440 cache_out_ts(ncp, tsp, ticksp);
1441 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1442 NCF_DTS && tsp != NULL) {
1443 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1444 *tsp = ncp_ts->nc_dotdottime;
1449 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1456 blp = HASH2BUCKETLOCK(hash);
1460 CK_LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1461 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1462 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1466 /* We failed to find an entry */
1467 if (__predict_false(ncp == NULL)) {
1472 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1474 counter_u64_add(nummiss, 1);
1478 if (ncp->nc_flag & NCF_NEGATIVE)
1479 goto negative_success;
1481 /* We found a "positive" match, return the vnode */
1482 counter_u64_add(numposhits, 1);
1484 CTR4(KTR_VFS, "cache_lookup(%p, %s) found %p via ncp %p",
1485 dvp, cnp->cn_nameptr, *vpp, ncp);
1486 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name,
1488 cache_out_ts(ncp, tsp, ticksp);
1491 * On success we return a locked and ref'd vnode as per the lookup
1495 ltype = 0; /* silence gcc warning */
1496 if (cnp->cn_flags & ISDOTDOT) {
1497 ltype = VOP_ISLOCKED(dvp);
1501 if (cache_ncp_invalid(ncp)) {
1506 vs = vget_prep_smr(*vpp);
1508 if (vs == VGET_NONE) {
1513 vs = vget_prep(*vpp);
1514 cache_lookup_unlock(blp, dvlp);
1516 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1517 if (cnp->cn_flags & ISDOTDOT) {
1518 vn_lock(dvp, ltype | LK_RETRY);
1519 if (VN_IS_DOOMED(dvp)) {
1530 if ((cnp->cn_flags & ISLASTCN) &&
1531 (cnp->cn_lkflags & LK_TYPE_MASK) == LK_EXCLUSIVE) {
1532 ASSERT_VOP_ELOCKED(*vpp, "cache_lookup");
1537 /* We found a negative match, and want to create it, so purge */
1538 if (cnp->cn_nameiop == CREATE) {
1540 counter_u64_add(numnegzaps, 1);
1544 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1545 cache_out_ts(ncp, tsp, ticksp);
1546 counter_u64_add(numneghits, 1);
1547 whiteout = (ncp->nc_flag & NCF_WHITE);
1551 * We need to take locks to promote an entry.
1553 negstate = NCP2NEGSTATE(ncp);
1554 if ((negstate->neg_flag & NEG_HOT) == 0 ||
1555 cache_ncp_invalid(ncp)) {
1562 cache_negative_hit(ncp);
1563 cache_lookup_unlock(blp, dvlp);
1566 cnp->cn_flags |= ISWHITEOUT;
1572 error = cache_zap_rlocked_bucket(ncp, cnp, hash, blp);
1574 error = cache_zap_locked_vnode(ncp, dvp);
1575 if (__predict_false(error != 0)) {
1576 zap_and_exit_bucket_fail2++;
1577 cache_maybe_yield();
1584 struct celockstate {
1586 struct rwlock *blp[2];
1588 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1589 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1592 cache_celockstate_init(struct celockstate *cel)
1595 bzero(cel, sizeof(*cel));
1599 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1602 struct mtx *vlp1, *vlp2;
1604 MPASS(cel->vlp[0] == NULL);
1605 MPASS(cel->vlp[1] == NULL);
1606 MPASS(cel->vlp[2] == NULL);
1608 MPASS(vp != NULL || dvp != NULL);
1610 vlp1 = VP2VNODELOCK(vp);
1611 vlp2 = VP2VNODELOCK(dvp);
1612 cache_sort_vnodes(&vlp1, &vlp2);
1623 cache_unlock_vnodes_cel(struct celockstate *cel)
1626 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
1628 if (cel->vlp[0] != NULL)
1629 mtx_unlock(cel->vlp[0]);
1630 if (cel->vlp[1] != NULL)
1631 mtx_unlock(cel->vlp[1]);
1632 if (cel->vlp[2] != NULL)
1633 mtx_unlock(cel->vlp[2]);
1637 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
1642 cache_assert_vlp_locked(cel->vlp[0]);
1643 cache_assert_vlp_locked(cel->vlp[1]);
1644 MPASS(cel->vlp[2] == NULL);
1647 vlp = VP2VNODELOCK(vp);
1650 if (vlp >= cel->vlp[1]) {
1653 if (mtx_trylock(vlp))
1655 cache_lock_vnodes_cel_3_failures++;
1656 cache_unlock_vnodes_cel(cel);
1657 if (vlp < cel->vlp[0]) {
1659 mtx_lock(cel->vlp[0]);
1660 mtx_lock(cel->vlp[1]);
1662 if (cel->vlp[0] != NULL)
1663 mtx_lock(cel->vlp[0]);
1665 mtx_lock(cel->vlp[1]);
1675 cache_lock_buckets_cel(struct celockstate *cel, struct rwlock *blp1,
1676 struct rwlock *blp2)
1679 MPASS(cel->blp[0] == NULL);
1680 MPASS(cel->blp[1] == NULL);
1682 cache_sort_vnodes(&blp1, &blp2);
1693 cache_unlock_buckets_cel(struct celockstate *cel)
1696 if (cel->blp[0] != NULL)
1697 rw_wunlock(cel->blp[0]);
1698 rw_wunlock(cel->blp[1]);
1702 * Lock part of the cache affected by the insertion.
1704 * This means vnodelocks for dvp, vp and the relevant bucketlock.
1705 * However, insertion can result in removal of an old entry. In this
1706 * case we have an additional vnode and bucketlock pair to lock. If the
1707 * entry is negative, ncelock is locked instead of the vnode.
1709 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
1710 * preserving the locking order (smaller address first).
1713 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1716 struct namecache *ncp;
1717 struct rwlock *blps[2];
1719 blps[0] = HASH2BUCKETLOCK(hash);
1722 cache_lock_vnodes_cel(cel, dvp, vp);
1723 if (vp == NULL || vp->v_type != VDIR)
1725 ncp = vp->v_cache_dd;
1728 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1730 MPASS(ncp->nc_dvp == vp);
1731 blps[1] = NCP2BUCKETLOCK(ncp);
1732 if (ncp->nc_flag & NCF_NEGATIVE)
1734 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1737 * All vnodes got re-locked. Re-validate the state and if
1738 * nothing changed we are done. Otherwise restart.
1740 if (ncp == vp->v_cache_dd &&
1741 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1742 blps[1] == NCP2BUCKETLOCK(ncp) &&
1743 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1745 cache_unlock_vnodes_cel(cel);
1750 cache_lock_buckets_cel(cel, blps[0], blps[1]);
1754 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1757 struct namecache *ncp;
1758 struct rwlock *blps[2];
1760 blps[0] = HASH2BUCKETLOCK(hash);
1763 cache_lock_vnodes_cel(cel, dvp, vp);
1764 ncp = dvp->v_cache_dd;
1767 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1769 MPASS(ncp->nc_dvp == dvp);
1770 blps[1] = NCP2BUCKETLOCK(ncp);
1771 if (ncp->nc_flag & NCF_NEGATIVE)
1773 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1775 if (ncp == dvp->v_cache_dd &&
1776 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1777 blps[1] == NCP2BUCKETLOCK(ncp) &&
1778 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1780 cache_unlock_vnodes_cel(cel);
1785 cache_lock_buckets_cel(cel, blps[0], blps[1]);
1789 cache_enter_unlock(struct celockstate *cel)
1792 cache_unlock_buckets_cel(cel);
1793 cache_unlock_vnodes_cel(cel);
1796 static void __noinline
1797 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
1798 struct componentname *cnp)
1800 struct celockstate cel;
1801 struct namecache *ncp;
1805 if (dvp->v_cache_dd == NULL)
1807 len = cnp->cn_namelen;
1808 cache_celockstate_init(&cel);
1809 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
1810 cache_enter_lock_dd(&cel, dvp, vp, hash);
1811 ncp = dvp->v_cache_dd;
1812 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
1813 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
1814 cache_zap_locked(ncp);
1818 dvp->v_cache_dd = NULL;
1819 cache_enter_unlock(&cel);
1824 * Add an entry to the cache.
1827 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
1828 struct timespec *tsp, struct timespec *dtsp)
1830 struct celockstate cel;
1831 struct namecache *ncp, *n2, *ndd;
1832 struct namecache_ts *ncp_ts, *n2_ts;
1833 struct nchashhead *ncpp;
1839 CTR3(KTR_VFS, "cache_enter(%p, %p, %s)", dvp, vp, cnp->cn_nameptr);
1840 VNASSERT(vp == NULL || !VN_IS_DOOMED(vp), vp,
1841 ("cache_enter: Adding a doomed vnode"));
1842 VNASSERT(dvp == NULL || !VN_IS_DOOMED(dvp), dvp,
1843 ("cache_enter: Doomed vnode used as src"));
1846 if (__predict_false(!doingcache))
1851 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1852 if (cnp->cn_namelen == 1)
1854 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
1855 cache_enter_dotdot_prep(dvp, vp, cnp);
1856 flag = NCF_ISDOTDOT;
1861 * Avoid blowout in namecache entries.
1863 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
1864 if (__predict_false(lnumcache >= ncsize)) {
1865 atomic_add_long(&numcache, -1);
1866 counter_u64_add(numdrops, 1);
1870 cache_celockstate_init(&cel);
1875 * Calculate the hash key and setup as much of the new
1876 * namecache entry as possible before acquiring the lock.
1878 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
1879 ncp->nc_flag = flag;
1882 cache_negative_init(ncp);
1885 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1886 ncp_ts->nc_time = *tsp;
1887 ncp_ts->nc_ticks = ticks;
1888 ncp_ts->nc_nc.nc_flag |= NCF_TS;
1890 ncp_ts->nc_dotdottime = *dtsp;
1891 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
1894 len = ncp->nc_nlen = cnp->cn_namelen;
1895 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
1896 strlcpy(ncp->nc_name, cnp->cn_nameptr, len + 1);
1897 cache_enter_lock(&cel, dvp, vp, hash);
1900 * See if this vnode or negative entry is already in the cache
1901 * with this name. This can happen with concurrent lookups of
1902 * the same path name.
1904 ncpp = NCHHASH(hash);
1905 CK_LIST_FOREACH(n2, ncpp, nc_hash) {
1906 if (n2->nc_dvp == dvp &&
1907 n2->nc_nlen == cnp->cn_namelen &&
1908 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
1910 KASSERT((n2->nc_flag & NCF_TS) != 0,
1912 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
1913 n2_ts->nc_time = ncp_ts->nc_time;
1914 n2_ts->nc_ticks = ncp_ts->nc_ticks;
1916 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
1917 n2_ts->nc_nc.nc_flag |= NCF_DTS;
1920 goto out_unlock_free;
1924 if (flag == NCF_ISDOTDOT) {
1926 * See if we are trying to add .. entry, but some other lookup
1927 * has populated v_cache_dd pointer already.
1929 if (dvp->v_cache_dd != NULL)
1930 goto out_unlock_free;
1931 KASSERT(vp == NULL || vp->v_type == VDIR,
1932 ("wrong vnode type %p", vp));
1933 dvp->v_cache_dd = ncp;
1937 if (vp->v_type == VDIR) {
1938 if (flag != NCF_ISDOTDOT) {
1940 * For this case, the cache entry maps both the
1941 * directory name in it and the name ".." for the
1942 * directory's parent.
1944 if ((ndd = vp->v_cache_dd) != NULL) {
1945 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
1946 cache_zap_locked(ndd);
1950 vp->v_cache_dd = ncp;
1953 vp->v_cache_dd = NULL;
1957 if (flag != NCF_ISDOTDOT) {
1958 if (LIST_EMPTY(&dvp->v_cache_src)) {
1960 counter_u64_add(numcachehv, 1);
1962 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
1966 * If the entry is "negative", we place it into the
1967 * "negative" cache queue, otherwise, we place it into the
1968 * destination vnode's cache entries queue.
1971 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
1972 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
1975 if (cnp->cn_flags & ISWHITEOUT)
1976 ncp->nc_flag |= NCF_WHITE;
1977 cache_negative_insert(ncp);
1978 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
1982 atomic_thread_fence_rel();
1984 * Insert the new namecache entry into the appropriate chain
1985 * within the cache entries table.
1987 CK_LIST_INSERT_HEAD(ncpp, ncp, nc_hash);
1989 cache_enter_unlock(&cel);
1990 if (numneg * ncnegfactor > lnumcache)
1991 cache_negative_zap_one();
1995 cache_enter_unlock(&cel);
2001 cache_roundup_2(u_int val)
2005 for (res = 1; res <= val; res <<= 1)
2012 * Name cache initialization, from vfs_init() when we are booting
2015 nchinit(void *dummy __unused)
2019 cache_zone_small = uma_zcreate("S VFS Cache",
2020 sizeof(struct namecache) + CACHE_PATH_CUTOFF + 1,
2021 NULL, NULL, NULL, NULL, UMA_ALIGNOF(struct namecache),
2023 cache_zone_small_ts = uma_zcreate("STS VFS Cache",
2024 sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1,
2025 NULL, NULL, NULL, NULL, UMA_ALIGNOF(struct namecache_ts),
2027 cache_zone_large = uma_zcreate("L VFS Cache",
2028 sizeof(struct namecache) + NAME_MAX + 1,
2029 NULL, NULL, NULL, NULL, UMA_ALIGNOF(struct namecache),
2031 cache_zone_large_ts = uma_zcreate("LTS VFS Cache",
2032 sizeof(struct namecache_ts) + NAME_MAX + 1,
2033 NULL, NULL, NULL, NULL, UMA_ALIGNOF(struct namecache_ts),
2036 VFS_SMR_ZONE_SET(cache_zone_small);
2037 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2038 VFS_SMR_ZONE_SET(cache_zone_large);
2039 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2041 ncsize = desiredvnodes * ncsizefactor;
2042 nchashtbl = hashinit(desiredvnodes * 2, M_VFSCACHE, &nchash);
2043 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2044 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2046 if (ncbuckethash > nchash)
2047 ncbuckethash = nchash;
2048 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2050 for (i = 0; i < numbucketlocks; i++)
2051 rw_init_flags(&bucketlocks[i], "ncbuc", RW_DUPOK | RW_RECURSE);
2052 ncvnodehash = ncbuckethash;
2053 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2055 for (i = 0; i < numvnodelocks; i++)
2056 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2057 ncpurgeminvnodes = numbucketlocks * 2;
2060 neglists = malloc(sizeof(*neglists) * numneglists, M_VFSCACHE,
2062 for (i = 0; i < numneglists; i++) {
2063 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2064 TAILQ_INIT(&neglists[i].nl_list);
2066 mtx_init(&ncneg_hot.nl_lock, "ncneglh", NULL, MTX_DEF);
2067 TAILQ_INIT(&ncneg_hot.nl_list);
2069 mtx_init(&ncneg_shrink_lock, "ncnegs", NULL, MTX_DEF);
2071 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2074 cache_changesize(u_long newmaxvnodes)
2076 struct nchashhead *new_nchashtbl, *old_nchashtbl;
2077 u_long new_nchash, old_nchash;
2078 struct namecache *ncp;
2083 newncsize = newmaxvnodes * ncsizefactor;
2084 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2085 if (newmaxvnodes < numbucketlocks)
2086 newmaxvnodes = numbucketlocks;
2088 new_nchashtbl = hashinit(newmaxvnodes, M_VFSCACHE, &new_nchash);
2089 /* If same hash table size, nothing to do */
2090 if (nchash == new_nchash) {
2091 free(new_nchashtbl, M_VFSCACHE);
2095 * Move everything from the old hash table to the new table.
2096 * None of the namecache entries in the table can be removed
2097 * because to do so, they have to be removed from the hash table.
2099 cache_lock_all_vnodes();
2100 cache_lock_all_buckets();
2101 old_nchashtbl = nchashtbl;
2102 old_nchash = nchash;
2103 nchashtbl = new_nchashtbl;
2104 nchash = new_nchash;
2105 for (i = 0; i <= old_nchash; i++) {
2106 while ((ncp = CK_LIST_FIRST(&old_nchashtbl[i])) != NULL) {
2107 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2109 CK_LIST_REMOVE(ncp, nc_hash);
2110 CK_LIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2114 cache_unlock_all_buckets();
2115 cache_unlock_all_vnodes();
2116 free(old_nchashtbl, M_VFSCACHE);
2120 * Invalidate all entries from and to a particular vnode.
2123 cache_purge(struct vnode *vp)
2125 TAILQ_HEAD(, namecache) ncps;
2126 struct namecache *ncp, *nnp;
2127 struct mtx *vlp, *vlp2;
2129 CTR1(KTR_VFS, "cache_purge(%p)", vp);
2130 SDT_PROBE1(vfs, namecache, purge, done, vp);
2131 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2132 vp->v_cache_dd == NULL)
2135 vlp = VP2VNODELOCK(vp);
2139 while (!LIST_EMPTY(&vp->v_cache_src)) {
2140 ncp = LIST_FIRST(&vp->v_cache_src);
2141 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2143 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2145 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2146 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2147 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2149 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2151 ncp = vp->v_cache_dd;
2153 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2154 ("lost dotdot link"));
2155 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2157 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2159 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2163 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2169 * Invalidate all negative entries for a particular directory vnode.
2172 cache_purge_negative(struct vnode *vp)
2174 TAILQ_HEAD(, namecache) ncps;
2175 struct namecache *ncp, *nnp;
2178 CTR1(KTR_VFS, "cache_purge_negative(%p)", vp);
2179 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2180 if (LIST_EMPTY(&vp->v_cache_src))
2183 vlp = VP2VNODELOCK(vp);
2185 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2186 if (!(ncp->nc_flag & NCF_NEGATIVE))
2188 cache_zap_negative_locked_vnode_kl(ncp, vp);
2189 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2192 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2198 * Flush all entries referencing a particular filesystem.
2201 cache_purgevfs(struct mount *mp, bool force)
2203 TAILQ_HEAD(, namecache) ncps;
2204 struct mtx *vlp1, *vlp2;
2206 struct nchashhead *bucket;
2207 struct namecache *ncp, *nnp;
2208 u_long i, j, n_nchash;
2211 /* Scan hash tables for applicable entries */
2212 SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2213 if (!force && mp->mnt_nvnodelistsize <= ncpurgeminvnodes)
2216 n_nchash = nchash + 1;
2218 for (i = 0; i < numbucketlocks; i++) {
2219 blp = (struct rwlock *)&bucketlocks[i];
2221 for (j = i; j < n_nchash; j += numbucketlocks) {
2223 bucket = &nchashtbl[j];
2224 CK_LIST_FOREACH_SAFE(ncp, bucket, nc_hash, nnp) {
2225 cache_assert_bucket_locked(ncp, RA_WLOCKED);
2226 if (ncp->nc_dvp->v_mount != mp)
2228 error = cache_zap_wlocked_bucket_kl(ncp, blp,
2232 TAILQ_INSERT_HEAD(&ncps, ncp, nc_dst);
2236 if (vlp1 == NULL && vlp2 == NULL)
2237 cache_maybe_yield();
2244 TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2250 * Perform canonical checks and cache lookup and pass on to filesystem
2251 * through the vop_cachedlookup only if needed.
2255 vfs_cache_lookup(struct vop_lookup_args *ap)
2259 struct vnode **vpp = ap->a_vpp;
2260 struct componentname *cnp = ap->a_cnp;
2261 int flags = cnp->cn_flags;
2266 if (dvp->v_type != VDIR)
2269 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2270 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2273 error = vn_dir_check_exec(dvp, cnp);
2277 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2279 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2285 /* Implementation of the getcwd syscall. */
2287 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2293 buflen = uap->buflen;
2294 if (__predict_false(buflen < 2))
2296 if (buflen > MAXPATHLEN)
2297 buflen = MAXPATHLEN;
2299 buf = malloc(buflen, M_TEMP, M_WAITOK);
2300 error = vn_getcwd(td, buf, &retbuf, &buflen);
2302 error = copyout(retbuf, uap->buf, buflen);
2308 vn_getcwd(struct thread *td, char *buf, char **retbuf, size_t *buflen)
2314 error = vn_fullpath_any(td, pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf, buflen);
2318 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2325 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2326 size_t size, int flags, enum uio_seg pathseg)
2328 struct nameidata nd;
2329 char *retbuf, *freebuf;
2334 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2335 pathseg, path, fd, &cap_fstat_rights, td);
2336 if ((error = namei(&nd)) != 0)
2338 error = vn_fullpath_hardlink(td, &nd, &retbuf, &freebuf, &size);
2340 error = copyout(retbuf, buf, size);
2341 free(freebuf, M_TEMP);
2348 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2351 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2352 uap->flags, UIO_USERSPACE));
2356 * Retrieve the full filesystem path that correspond to a vnode from the name
2357 * cache (if available)
2360 vn_fullpath(struct thread *td, struct vnode *vn, char **retbuf, char **freebuf)
2367 if (__predict_false(vn == NULL))
2370 buflen = MAXPATHLEN;
2371 buf = malloc(buflen, M_TEMP, M_WAITOK);
2373 error = vn_fullpath_any(td, vn, pwd->pwd_rdir, buf, retbuf, &buflen);
2384 * This function is similar to vn_fullpath, but it attempts to lookup the
2385 * pathname relative to the global root mount point. This is required for the
2386 * auditing sub-system, as audited pathnames must be absolute, relative to the
2387 * global root mount point.
2390 vn_fullpath_global(struct thread *td, struct vnode *vn,
2391 char **retbuf, char **freebuf)
2397 if (__predict_false(vn == NULL))
2399 buflen = MAXPATHLEN;
2400 buf = malloc(buflen, M_TEMP, M_WAITOK);
2401 error = vn_fullpath_any(td, vn, rootvnode, buf, retbuf, &buflen);
2410 vn_vptocnp(struct vnode **vp, struct ucred *cred, char *buf, size_t *buflen)
2413 struct namecache *ncp;
2417 vlp = VP2VNODELOCK(*vp);
2419 TAILQ_FOREACH(ncp, &((*vp)->v_cache_dst), nc_dst) {
2420 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2424 if (*buflen < ncp->nc_nlen) {
2427 counter_u64_add(numfullpathfail4, 1);
2429 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2433 *buflen -= ncp->nc_nlen;
2434 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2435 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2444 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2447 vn_lock(*vp, LK_SHARED | LK_RETRY);
2448 error = VOP_VPTOCNP(*vp, &dvp, cred, buf, buflen);
2451 counter_u64_add(numfullpathfail2, 1);
2452 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2457 if (VN_IS_DOOMED(dvp)) {
2458 /* forced unmount */
2461 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2465 * *vp has its use count incremented still.
2472 * Resolve a directory to a pathname.
2474 * The name of the directory can always be found in the namecache or fetched
2475 * from the filesystem. There is also guaranteed to be only one parent, meaning
2476 * we can just follow vnodes up until we find the root.
2478 * The vnode must be referenced.
2481 vn_fullpath_dir(struct thread *td, struct vnode *vp, struct vnode *rdir,
2482 char *buf, char **retbuf, size_t *len, bool slash_prefixed, size_t addend)
2484 #ifdef KDTRACE_HOOKS
2485 struct vnode *startvp = vp;
2491 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
2492 VNPASS(vp->v_usecount > 0, vp);
2496 if (!slash_prefixed) {
2504 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
2505 counter_u64_add(numfullpathcalls, 1);
2506 while (vp != rdir && vp != rootvnode) {
2508 * The vp vnode must be already fully constructed,
2509 * since it is either found in namecache or obtained
2510 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
2511 * without obtaining the vnode lock.
2513 if ((vp->v_vflag & VV_ROOT) != 0) {
2514 vn_lock(vp, LK_RETRY | LK_SHARED);
2517 * With the vnode locked, check for races with
2518 * unmount, forced or not. Note that we
2519 * already verified that vp is not equal to
2520 * the root vnode, which means that
2521 * mnt_vnodecovered can be NULL only for the
2524 if (VN_IS_DOOMED(vp) ||
2525 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
2526 vp1->v_mountedhere != vp->v_mount) {
2529 SDT_PROBE3(vfs, namecache, fullpath, return,
2539 if (vp->v_type != VDIR) {
2541 counter_u64_add(numfullpathfail1, 1);
2543 SDT_PROBE3(vfs, namecache, fullpath, return,
2547 error = vn_vptocnp(&vp, td->td_ucred, buf, &buflen);
2553 SDT_PROBE3(vfs, namecache, fullpath, return, error,
2557 buf[--buflen] = '/';
2558 slash_prefixed = true;
2562 if (!slash_prefixed) {
2565 counter_u64_add(numfullpathfail4, 1);
2566 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
2570 buf[--buflen] = '/';
2572 counter_u64_add(numfullpathfound, 1);
2575 *retbuf = buf + buflen;
2576 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
2583 * Resolve an arbitrary vnode to a pathname.
2586 * - hardlinks are not tracked, thus if the vnode is not a directory this can
2587 * resolve to a different path than the one used to find it
2588 * - namecache is not mandatory, meaning names are not guaranteed to be added
2589 * (in which case resolving fails)
2592 vn_fullpath_any(struct thread *td, struct vnode *vp, struct vnode *rdir,
2593 char *buf, char **retbuf, size_t *buflen)
2596 bool slash_prefixed;
2602 orig_buflen = *buflen;
2605 slash_prefixed = false;
2606 if (vp->v_type != VDIR) {
2608 buf[*buflen] = '\0';
2609 error = vn_vptocnp(&vp, td->td_ucred, buf, buflen);
2618 slash_prefixed = true;
2621 return (vn_fullpath_dir(td, vp, rdir, buf, retbuf, buflen, slash_prefixed,
2622 orig_buflen - *buflen));
2626 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
2628 * Since the namecache does not track handlings, the caller is expected to first
2629 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
2631 * Then we have 2 cases:
2632 * - if the found vnode is a directory, the path can be constructed just by
2633 * fullowing names up the chain
2634 * - otherwise we populate the buffer with the saved name and start resolving
2638 vn_fullpath_hardlink(struct thread *td, struct nameidata *ndp, char **retbuf,
2639 char **freebuf, size_t *buflen)
2643 struct componentname *cnp;
2647 bool slash_prefixed;
2651 if (*buflen > MAXPATHLEN)
2652 *buflen = MAXPATHLEN;
2654 slash_prefixed = false;
2656 buf = malloc(*buflen, M_TEMP, M_WAITOK);
2661 if (vp->v_type != VDIR) {
2663 addend = cnp->cn_namelen + 2;
2664 if (*buflen < addend) {
2669 tmpbuf = buf + *buflen;
2671 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
2672 tmpbuf[addend - 1] = '\0';
2673 slash_prefixed = true;
2678 error = vn_fullpath_dir(td, vp, pwd->pwd_rdir, buf, retbuf, buflen,
2679 slash_prefixed, addend);
2694 vn_dir_dd_ino(struct vnode *vp)
2696 struct namecache *ncp;
2701 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
2702 vlp = VP2VNODELOCK(vp);
2704 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
2705 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
2708 vs = vget_prep(ddvp);
2710 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
2719 vn_commname(struct vnode *vp, char *buf, u_int buflen)
2721 struct namecache *ncp;
2725 vlp = VP2VNODELOCK(vp);
2727 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
2728 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2734 l = min(ncp->nc_nlen, buflen - 1);
2735 memcpy(buf, ncp->nc_name, l);
2742 * This function updates path string to vnode's full global path
2743 * and checks the size of the new path string against the pathlen argument.
2745 * Requires a locked, referenced vnode.
2746 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
2748 * If vp is a directory, the call to vn_fullpath_global() always succeeds
2749 * because it falls back to the ".." lookup if the namecache lookup fails.
2752 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
2755 struct nameidata nd;
2760 ASSERT_VOP_ELOCKED(vp, __func__);
2762 /* Construct global filesystem path from vp. */
2764 error = vn_fullpath_global(td, vp, &rpath, &fbuf);
2771 if (strlen(rpath) >= pathlen) {
2773 error = ENAMETOOLONG;
2778 * Re-lookup the vnode by path to detect a possible rename.
2779 * As a side effect, the vnode is relocked.
2780 * If vnode was renamed, return ENOENT.
2782 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
2783 UIO_SYSSPACE, path, td);
2789 NDFREE(&nd, NDF_ONLY_PNBUF);
2793 strcpy(path, rpath);
2806 db_print_vpath(struct vnode *vp)
2809 while (vp != NULL) {
2810 db_printf("%p: ", vp);
2811 if (vp == rootvnode) {
2815 if (vp->v_vflag & VV_ROOT) {
2816 db_printf("<mount point>");
2817 vp = vp->v_mount->mnt_vnodecovered;
2819 struct namecache *ncp;
2823 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2826 for (i = 0; i < ncp->nc_nlen; i++)
2827 db_printf("%c", *ncn++);
2840 DB_SHOW_COMMAND(vpath, db_show_vpath)
2845 db_printf("usage: show vpath <struct vnode *>\n");
2849 vp = (struct vnode *)addr;
2855 extern uma_zone_t namei_zone;
2857 static bool __read_frequently cache_fast_lookup = true;
2858 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_lookup, CTLFLAG_RW,
2859 &cache_fast_lookup, 0, "");
2861 #define CACHE_FPL_FAILED -2020
2864 cache_fpl_cleanup_cnp(struct componentname *cnp)
2867 uma_zfree(namei_zone, cnp->cn_pnbuf);
2869 cnp->cn_pnbuf = NULL;
2870 cnp->cn_nameptr = NULL;
2875 cache_fpl_handle_root(struct nameidata *ndp, struct vnode **dpp)
2877 struct componentname *cnp;
2880 while (*(cnp->cn_nameptr) == '/') {
2885 *dpp = ndp->ni_rootdir;
2889 * Components of nameidata (or objects it can point to) which may
2890 * need restoring in case fast path lookup fails.
2892 struct nameidata_saved {
2901 enum cache_fpl_status status;
2903 struct nameidata *ndp;
2904 struct nameidata_saved snd;
2905 struct componentname *cnp;
2914 cache_fpl_checkpoint(struct cache_fpl *fpl, struct nameidata_saved *snd)
2917 snd->cn_flags = fpl->ndp->ni_cnd.cn_flags;
2918 snd->cn_namelen = fpl->ndp->ni_cnd.cn_namelen;
2919 snd->cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
2920 snd->ni_pathlen = fpl->ndp->ni_pathlen;
2924 cache_fpl_restore(struct cache_fpl *fpl, struct nameidata_saved *snd)
2927 fpl->ndp->ni_cnd.cn_flags = snd->cn_flags;
2928 fpl->ndp->ni_cnd.cn_namelen = snd->cn_namelen;
2929 fpl->ndp->ni_cnd.cn_nameptr = snd->cn_nameptr;
2930 fpl->ndp->ni_pathlen = snd->ni_pathlen;
2934 #define cache_fpl_smr_assert_entered(fpl) ({ \
2935 struct cache_fpl *_fpl = (fpl); \
2936 MPASS(_fpl->in_smr == true); \
2937 VFS_SMR_ASSERT_ENTERED(); \
2939 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
2940 struct cache_fpl *_fpl = (fpl); \
2941 MPASS(_fpl->in_smr == false); \
2942 VFS_SMR_ASSERT_NOT_ENTERED(); \
2945 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
2946 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
2949 #define cache_fpl_smr_enter(fpl) ({ \
2950 struct cache_fpl *_fpl = (fpl); \
2951 MPASS(_fpl->in_smr == false); \
2953 _fpl->in_smr = true; \
2956 #define cache_fpl_smr_exit(fpl) ({ \
2957 struct cache_fpl *_fpl = (fpl); \
2958 MPASS(_fpl->in_smr == true); \
2960 _fpl->in_smr = false; \
2964 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
2967 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
2968 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
2969 ("%s: converting to abort from %d at %d, set at %d\n",
2970 __func__, fpl->status, line, fpl->line));
2972 fpl->status = CACHE_FPL_STATUS_ABORTED;
2974 return (CACHE_FPL_FAILED);
2977 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
2980 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
2983 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
2984 ("%s: setting to partial at %d, but already set to %d at %d\n",
2985 __func__, line, fpl->status, fpl->line));
2986 cache_fpl_smr_assert_entered(fpl);
2987 fpl->status = CACHE_FPL_STATUS_PARTIAL;
2989 return (CACHE_FPL_FAILED);
2992 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
2995 cache_fpl_handled_impl(struct cache_fpl *fpl, int error, int line)
2998 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
2999 ("%s: setting to handled at %d, but already set to %d at %d\n",
3000 __func__, line, fpl->status, fpl->line));
3001 cache_fpl_smr_assert_not_entered(fpl);
3002 MPASS(error != CACHE_FPL_FAILED);
3003 fpl->status = CACHE_FPL_STATUS_HANDLED;
3008 #define cache_fpl_handled(x, e) cache_fpl_handled_impl((x), (e), __LINE__)
3010 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3011 (LOCKLEAF | LOCKPARENT | WANTPARENT | FOLLOW | LOCKSHARED | SAVENAME | \
3012 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2)
3015 cache_can_fplookup(struct cache_fpl *fpl)
3017 struct nameidata *ndp;
3018 struct componentname *cnp;
3023 td = cnp->cn_thread;
3025 if (!cache_fast_lookup) {
3026 cache_fpl_aborted(fpl);
3030 if (mac_vnode_check_lookup_enabled()) {
3031 cache_fpl_aborted(fpl);
3035 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3036 cache_fpl_aborted(fpl);
3039 if (cnp->cn_nameiop != LOOKUP) {
3040 cache_fpl_aborted(fpl);
3043 if (ndp->ni_dirfd != AT_FDCWD) {
3044 cache_fpl_aborted(fpl);
3047 if (IN_CAPABILITY_MODE(td)) {
3048 cache_fpl_aborted(fpl);
3051 if (AUDITING_TD(td)) {
3052 cache_fpl_aborted(fpl);
3055 if (ndp->ni_startdir != NULL) {
3056 cache_fpl_aborted(fpl);
3063 cache_fplookup_vnode_supported(struct vnode *vp)
3066 return (vp->v_type != VLNK);
3070 * Move a negative entry to the hot list.
3072 * We have to take locks, but they may be contended and in the worst
3073 * case we may need to go off CPU. We don't want to spin within the
3074 * smr section and we can't block with it. Instead we are going to
3075 * look up the entry again.
3077 static int __noinline
3078 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
3081 struct componentname *cnp;
3082 struct namecache *ncp;
3083 struct neglist *neglist;
3084 struct negstate *negstate;
3091 if (!vhold_smr(dvp))
3092 return (cache_fpl_aborted(fpl));
3094 neglist = NCP2NEGLIST(oncp);
3095 cache_fpl_smr_exit(fpl);
3097 mtx_lock(&ncneg_hot.nl_lock);
3098 mtx_lock(&neglist->nl_lock);
3100 * For hash iteration.
3102 cache_fpl_smr_enter(fpl);
3105 * Avoid all surprises by only succeeding if we got the same entry and
3106 * bailing completely otherwise.
3108 * In particular at this point there can be a new ncp which matches the
3109 * search but hashes to a different neglist.
3111 CK_LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3117 * No match to begin with.
3119 if (__predict_false(ncp == NULL)) {
3124 * The newly found entry may be something different...
3126 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3127 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
3132 * ... and not even negative.
3134 nc_flag = atomic_load_char(&ncp->nc_flag);
3135 if ((nc_flag & NCF_NEGATIVE) == 0) {
3139 if (__predict_false(cache_ncp_invalid(ncp))) {
3143 negstate = NCP2NEGSTATE(ncp);
3144 if ((negstate->neg_flag & NEG_HOT) == 0) {
3146 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
3147 TAILQ_INSERT_TAIL(&ncneg_hot.nl_list, ncp, nc_dst);
3148 negstate->neg_flag |= NEG_HOT;
3151 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
3152 counter_u64_add(numneghits, 1);
3153 cache_fpl_smr_exit(fpl);
3154 mtx_unlock(&neglist->nl_lock);
3155 mtx_unlock(&ncneg_hot.nl_lock);
3157 return (cache_fpl_handled(fpl, ENOENT));
3159 cache_fpl_smr_exit(fpl);
3160 mtx_unlock(&neglist->nl_lock);
3161 mtx_unlock(&ncneg_hot.nl_lock);
3163 return (cache_fpl_aborted(fpl));
3167 * The target vnode is not supported, prepare for the slow path to take over.
3170 cache_fplookup_partial_setup(struct cache_fpl *fpl)
3172 struct componentname *cnp;
3180 dvp_seqc = fpl->dvp_seqc;
3182 dvs = vget_prep_smr(dvp);
3183 if (dvs == VGET_NONE) {
3184 cache_fpl_smr_exit(fpl);
3185 return (cache_fpl_aborted(fpl));
3188 cache_fpl_smr_exit(fpl);
3190 vget_finish_ref(dvp, dvs);
3191 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3193 return (cache_fpl_aborted(fpl));
3196 pwd = pwd_hold(curthread);
3197 if (fpl->pwd != pwd) {
3200 return (cache_fpl_aborted(fpl));
3203 fpl->ndp->ni_startdir = dvp;
3208 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
3210 struct componentname *cnp;
3217 tvp_seqc = fpl->tvp_seqc;
3219 if ((cnp->cn_flags & LOCKLEAF) != 0) {
3220 error = vget_finish(tvp, cnp->cn_lkflags, tvs);
3222 return (cache_fpl_aborted(fpl));
3225 vget_finish_ref(tvp, tvs);
3228 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
3229 if ((cnp->cn_flags & LOCKLEAF) != 0)
3233 return (cache_fpl_aborted(fpl));
3236 return (cache_fpl_handled(fpl, 0));
3239 static int __noinline
3240 cache_fplookup_final_withparent(struct cache_fpl *fpl)
3242 enum vgetstate dvs, tvs;
3243 struct componentname *cnp;
3244 struct vnode *dvp, *tvp;
3245 seqc_t dvp_seqc, tvp_seqc;
3250 dvp_seqc = fpl->dvp_seqc;
3252 tvp_seqc = fpl->tvp_seqc;
3254 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
3257 * This is less efficient than it can be for simplicity.
3259 dvs = vget_prep_smr(dvp);
3260 if (dvs == VGET_NONE) {
3261 return (cache_fpl_aborted(fpl));
3263 tvs = vget_prep_smr(tvp);
3264 if (tvs == VGET_NONE) {
3265 cache_fpl_smr_exit(fpl);
3266 vget_abort(dvp, dvs);
3267 return (cache_fpl_aborted(fpl));
3270 cache_fpl_smr_exit(fpl);
3272 if ((cnp->cn_flags & LOCKPARENT) != 0) {
3273 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
3275 vget_abort(tvp, tvs);
3276 return (cache_fpl_aborted(fpl));
3279 vget_finish_ref(dvp, dvs);
3282 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3283 vget_abort(tvp, tvs);
3284 if ((cnp->cn_flags & LOCKPARENT) != 0)
3288 cache_fpl_aborted(fpl);
3292 error = cache_fplookup_final_child(fpl, tvs);
3294 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
3295 if ((cnp->cn_flags & LOCKPARENT) != 0)
3302 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
3307 cache_fplookup_final(struct cache_fpl *fpl)
3309 struct componentname *cnp;
3311 struct vnode *dvp, *tvp;
3312 seqc_t dvp_seqc, tvp_seqc;
3316 dvp_seqc = fpl->dvp_seqc;
3318 tvp_seqc = fpl->tvp_seqc;
3320 VNPASS(cache_fplookup_vnode_supported(dvp), dvp);
3322 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
3323 return (cache_fplookup_final_withparent(fpl));
3325 tvs = vget_prep_smr(tvp);
3326 if (tvs == VGET_NONE) {
3327 return (cache_fpl_partial(fpl));
3330 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3331 cache_fpl_smr_exit(fpl);
3332 vget_abort(tvp, tvs);
3333 return (cache_fpl_aborted(fpl));
3336 cache_fpl_smr_exit(fpl);
3337 return (cache_fplookup_final_child(fpl, tvs));
3341 cache_fplookup_next(struct cache_fpl *fpl)
3343 struct componentname *cnp;
3344 struct namecache *ncp;
3345 struct negstate *negstate;
3346 struct vnode *dvp, *tvp;
3354 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.')) {
3356 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3357 if (seqc_in_modify(fpl->tvp_seqc)) {
3358 return (cache_fpl_aborted(fpl));
3363 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
3365 CK_LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3366 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3367 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
3372 * If there is no entry we have to punt to the slow path to perform
3373 * actual lookup. Should there be nothing with this name a negative
3374 * entry will be created.
3376 if (__predict_false(ncp == NULL)) {
3377 return (cache_fpl_partial(fpl));
3380 tvp = atomic_load_ptr(&ncp->nc_vp);
3381 nc_flag = atomic_load_char(&ncp->nc_flag);
3382 if ((nc_flag & NCF_NEGATIVE) != 0) {
3383 negstate = NCP2NEGSTATE(ncp);
3384 neg_hot = ((negstate->neg_flag & NEG_HOT) != 0);
3385 if (__predict_false(cache_ncp_invalid(ncp))) {
3386 return (cache_fpl_partial(fpl));
3388 if (__predict_false((nc_flag & NCF_WHITE) != 0)) {
3389 return (cache_fpl_partial(fpl));
3392 return (cache_fplookup_negative_promote(fpl, ncp, hash));
3394 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp,
3396 counter_u64_add(numneghits, 1);
3397 cache_fpl_smr_exit(fpl);
3398 return (cache_fpl_handled(fpl, ENOENT));
3401 if (__predict_false(cache_ncp_invalid(ncp))) {
3402 return (cache_fpl_partial(fpl));
3406 fpl->tvp_seqc = vn_seqc_read_any(tvp);
3407 if (seqc_in_modify(fpl->tvp_seqc)) {
3408 return (cache_fpl_partial(fpl));
3411 if (!cache_fplookup_vnode_supported(tvp)) {
3412 return (cache_fpl_partial(fpl));
3415 counter_u64_add(numposhits, 1);
3416 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
3421 cache_fplookup_mp_supported(struct mount *mp)
3426 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
3428 if ((mp->mnt_flag & MNT_UNION) != 0)
3434 * Walk up the mount stack (if any).
3436 * Correctness is provided in the following ways:
3437 * - all vnodes are protected from freeing with SMR
3438 * - struct mount objects are type stable making them always safe to access
3439 * - stability of the particular mount is provided by busying it
3440 * - relationship between the vnode which is mounted on and the mount is
3441 * verified with the vnode sequence counter after busying
3442 * - association between root vnode of the mount and the mount is protected
3445 * From that point on we can read the sequence counter of the root vnode
3446 * and get the next mount on the stack (if any) using the same protection.
3448 * By the end of successful walk we are guaranteed the reached state was
3449 * indeed present at least at some point which matches the regular lookup.
3452 cache_fplookup_climb_mount(struct cache_fpl *fpl)
3454 struct mount *mp, *prev_mp;
3459 vp_seqc = fpl->tvp_seqc;
3460 if (vp->v_type != VDIR)
3463 mp = atomic_load_ptr(&vp->v_mountedhere);
3469 if (!vfs_op_thread_enter(mp)) {
3470 if (prev_mp != NULL)
3471 vfs_op_thread_exit(prev_mp);
3472 return (cache_fpl_partial(fpl));
3474 if (prev_mp != NULL)
3475 vfs_op_thread_exit(prev_mp);
3476 if (!vn_seqc_consistent(vp, vp_seqc)) {
3477 vfs_op_thread_exit(mp);
3478 return (cache_fpl_partial(fpl));
3480 if (!cache_fplookup_mp_supported(mp)) {
3481 vfs_op_thread_exit(mp);
3482 return (cache_fpl_partial(fpl));
3484 vp = atomic_load_ptr(&mp->mnt_rootvnode);
3485 if (vp == NULL || VN_IS_DOOMED(vp)) {
3486 vfs_op_thread_exit(mp);
3487 return (cache_fpl_partial(fpl));
3489 vp_seqc = vn_seqc_read_any(vp);
3490 if (seqc_in_modify(vp_seqc)) {
3491 vfs_op_thread_exit(mp);
3492 return (cache_fpl_partial(fpl));
3495 mp = atomic_load_ptr(&vp->v_mountedhere);
3500 vfs_op_thread_exit(prev_mp);
3502 fpl->tvp_seqc = vp_seqc;
3509 * The code is mostly copy-pasted from regular lookup, see lookup().
3510 * The structure is maintained along with comments for easier maintenance.
3511 * Deduplicating the code will become feasible after fast path lookup
3512 * becomes more feature-complete.
3515 cache_fplookup_parse(struct cache_fpl *fpl)
3517 struct nameidata *ndp;
3518 struct componentname *cnp;
3520 char *prev_ni_next; /* saved ndp->ni_next */
3521 size_t prev_ni_pathlen; /* saved ndp->ni_pathlen */
3527 * Search a new directory.
3529 * The last component of the filename is left accessible via
3530 * cnp->cn_nameptr for callers that need the name. Callers needing
3531 * the name set the SAVENAME flag. When done, they assume
3532 * responsibility for freeing the pathname buffer.
3534 for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
3536 cnp->cn_namelen = cp - cnp->cn_nameptr;
3537 if (cnp->cn_namelen > NAME_MAX) {
3538 cache_fpl_smr_exit(fpl);
3539 return (cache_fpl_handled(fpl, ENAMETOOLONG));
3541 prev_ni_pathlen = ndp->ni_pathlen;
3542 ndp->ni_pathlen -= cnp->cn_namelen;
3543 KASSERT(ndp->ni_pathlen <= PATH_MAX,
3544 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
3545 prev_ni_next = ndp->ni_next;
3549 * Replace multiple slashes by a single slash and trailing slashes
3550 * by a null. This must be done before VOP_LOOKUP() because some
3551 * fs's don't know about trailing slashes. Remember if there were
3552 * trailing slashes to handle symlinks, existing non-directories
3553 * and non-existing files that won't be directories specially later.
3555 while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
3561 * Regular lookup performs the following:
3562 * *ndp->ni_next = '\0';
3563 * cnp->cn_flags |= TRAILINGSLASH;
3565 * Which is problematic since it modifies data read
3566 * from userspace. Then if fast path lookup was to
3567 * abort we would have to either restore it or convey
3568 * the flag. Since this is a corner case just ignore
3569 * it for simplicity.
3571 return (cache_fpl_partial(fpl));
3576 cnp->cn_flags |= MAKEENTRY;
3578 if (cnp->cn_namelen == 2 &&
3579 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3580 cnp->cn_flags |= ISDOTDOT;
3582 cnp->cn_flags &= ~ISDOTDOT;
3583 if (*ndp->ni_next == 0)
3584 cnp->cn_flags |= ISLASTCN;
3586 cnp->cn_flags &= ~ISLASTCN;
3589 * Check for degenerate name (e.g. / or "")
3590 * which is a way of talking about a directory,
3591 * e.g. like "/." or ".".
3594 * Another corner case handled by the regular lookup
3596 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
3597 return (cache_fpl_partial(fpl));
3603 cache_fplookup_parse_advance(struct cache_fpl *fpl)
3605 struct nameidata *ndp;
3606 struct componentname *cnp;
3611 cnp->cn_nameptr = ndp->ni_next;
3612 while (*cnp->cn_nameptr == '/') {
3619 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
3621 struct nameidata *ndp;
3622 struct componentname *cnp;
3626 error = CACHE_FPL_FAILED;
3630 cnp->cn_lkflags = LK_SHARED;
3631 if ((cnp->cn_flags & LOCKSHARED) == 0)
3632 cnp->cn_lkflags = LK_EXCLUSIVE;
3634 cache_fpl_checkpoint(fpl, &fpl->snd);
3637 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
3638 if (seqc_in_modify(fpl->dvp_seqc)) {
3639 cache_fpl_aborted(fpl);
3642 mp = atomic_load_ptr(&fpl->dvp->v_mount);
3643 if (!cache_fplookup_mp_supported(mp)) {
3644 cache_fpl_aborted(fpl);
3648 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
3651 error = cache_fplookup_parse(fpl);
3652 if (__predict_false(error != 0)) {
3656 if (cnp->cn_flags & ISDOTDOT) {
3657 error = cache_fpl_partial(fpl);
3661 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
3663 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred, cnp->cn_thread);
3664 if (__predict_false(error != 0)) {
3667 case EOPNOTSUPP: /* can happen when racing against vgone */
3668 cache_fpl_partial(fpl);
3672 * See the API contract for VOP_FPLOOKUP_VEXEC.
3674 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
3675 error = cache_fpl_aborted(fpl);
3677 cache_fpl_smr_exit(fpl);
3678 cache_fpl_handled(fpl, error);
3685 error = cache_fplookup_next(fpl);
3686 if (__predict_false(error != 0)) {
3690 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
3692 error = cache_fplookup_climb_mount(fpl);
3693 if (__predict_false(error != 0)) {
3697 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
3699 if (cnp->cn_flags & ISLASTCN) {
3700 error = cache_fplookup_final(fpl);
3704 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
3705 error = cache_fpl_aborted(fpl);
3709 fpl->dvp = fpl->tvp;
3710 fpl->dvp_seqc = fpl->tvp_seqc;
3712 cache_fplookup_parse_advance(fpl);
3713 cache_fpl_checkpoint(fpl, &fpl->snd);
3716 switch (fpl->status) {
3717 case CACHE_FPL_STATUS_UNSET:
3718 __assert_unreachable();
3720 case CACHE_FPL_STATUS_PARTIAL:
3721 cache_fpl_smr_assert_entered(fpl);
3722 return (cache_fplookup_partial_setup(fpl));
3723 case CACHE_FPL_STATUS_ABORTED:
3725 cache_fpl_smr_exit(fpl);
3726 return (CACHE_FPL_FAILED);
3727 case CACHE_FPL_STATUS_HANDLED:
3728 cache_fpl_smr_assert_not_entered(fpl);
3729 if (__predict_false(error != 0)) {
3732 cache_fpl_cleanup_cnp(cnp);
3735 ndp->ni_dvp = fpl->dvp;
3736 ndp->ni_vp = fpl->tvp;
3737 if (cnp->cn_flags & SAVENAME)
3738 cnp->cn_flags |= HASBUF;
3740 cache_fpl_cleanup_cnp(cnp);
3746 * Fast path lookup protected with SMR and sequence counters.
3748 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
3750 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
3753 * Traditional vnode lookup conceptually looks like this:
3759 * vn_unlock(current);
3766 * Each jump to the next vnode is safe memory-wise and atomic with respect to
3767 * any modifications thanks to holding respective locks.
3769 * The same guarantee can be provided with a combination of safe memory
3770 * reclamation and sequence counters instead. If all operations which affect
3771 * the relationship between the current vnode and the one we are looking for
3772 * also modify the counter, we can verify whether all the conditions held as
3773 * we made the jump. This includes things like permissions, mount points etc.
3774 * Counter modification is provided by enclosing relevant places in
3775 * vn_seqc_write_begin()/end() calls.
3777 * Thus this translates to:
3780 * dvp_seqc = seqc_read_any(dvp);
3781 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
3785 * tvp_seqc = seqc_read_any(tvp);
3786 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
3788 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
3790 * dvp = tvp; // we know nothing of importance has changed
3791 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
3795 * vget(); // secure the vnode
3796 * if (!seqc_consistent(tvp, tvp_seqc) // final check
3798 * // at this point we know nothing has changed for any parent<->child pair
3799 * // as they were crossed during the lookup, meaning we matched the guarantee
3800 * // of the locked variant
3803 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
3804 * - they are called while within vfs_smr protection which they must never exit
3805 * - EAGAIN can be returned to denote checking could not be performed, it is
3806 * always valid to return it
3807 * - if the sequence counter has not changed the result must be valid
3808 * - if the sequence counter has changed both false positives and false negatives
3809 * are permitted (since the result will be rejected later)
3810 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
3812 * Caveats to watch out for:
3813 * - vnodes are passed unlocked and unreferenced with nothing stopping
3814 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
3815 * to use atomic_load_ptr to fetch it.
3816 * - the aforementioned object can also get freed, meaning absent other means it
3817 * should be protected with vfs_smr
3818 * - either safely checking permissions as they are modified or guaranteeing
3819 * their stability is left to the routine
3822 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
3825 struct cache_fpl fpl;
3828 struct componentname *cnp;
3829 struct nameidata_saved orig;
3832 *status = CACHE_FPL_STATUS_UNSET;
3833 bzero(&fpl, sizeof(fpl));
3834 fpl.status = CACHE_FPL_STATUS_UNSET;
3836 fpl.cnp = &ndp->ni_cnd;
3837 MPASS(curthread == fpl.cnp->cn_thread);
3839 if (!cache_can_fplookup(&fpl)) {
3840 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
3841 *status = fpl.status;
3842 return (EOPNOTSUPP);
3845 cache_fpl_checkpoint(&fpl, &orig);
3847 cache_fpl_smr_enter(&fpl);
3848 pwd = pwd_get_smr();
3850 ndp->ni_rootdir = pwd->pwd_rdir;
3851 ndp->ni_topdir = pwd->pwd_jdir;
3854 cnp->cn_nameptr = cnp->cn_pnbuf;
3855 if (cnp->cn_pnbuf[0] == '/') {
3856 cache_fpl_handle_root(ndp, &dvp);
3858 MPASS(ndp->ni_dirfd == AT_FDCWD);
3859 dvp = pwd->pwd_cdir;
3862 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
3864 error = cache_fplookup_impl(dvp, &fpl);
3865 cache_fpl_smr_assert_not_entered(&fpl);
3866 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
3868 *status = fpl.status;
3869 switch (fpl.status) {
3870 case CACHE_FPL_STATUS_UNSET:
3871 __assert_unreachable();
3873 case CACHE_FPL_STATUS_HANDLED:
3874 SDT_PROBE3(vfs, namei, lookup, return, error,
3875 (error == 0 ? ndp->ni_vp : NULL), true);
3877 case CACHE_FPL_STATUS_PARTIAL:
3879 cache_fpl_restore(&fpl, &fpl.snd);
3881 case CACHE_FPL_STATUS_ABORTED:
3882 cache_fpl_restore(&fpl, &orig);