xref: /freebsd-14.2/sys/kern/vfs_cache.c (revision 8f7aafe2)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993, 1995
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Poul-Henning Kamp of the FreeBSD Project.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
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.
21  *
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
32  * SUCH DAMAGE.
33  *
34  *	@(#)vfs_cache.c	8.5 (Berkeley) 3/22/95
35  */
36 
37 #include <sys/cdefs.h>
38 #include "opt_ddb.h"
39 #include "opt_ktrace.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/capsicum.h>
44 #include <sys/counter.h>
45 #include <sys/filedesc.h>
46 #include <sys/fnv_hash.h>
47 #include <sys/kernel.h>
48 #include <sys/ktr.h>
49 #include <sys/lock.h>
50 #include <sys/malloc.h>
51 #include <sys/fcntl.h>
52 #include <sys/jail.h>
53 #include <sys/mount.h>
54 #include <sys/namei.h>
55 #include <sys/proc.h>
56 #include <sys/seqc.h>
57 #include <sys/sdt.h>
58 #include <sys/smr.h>
59 #include <sys/smp.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysproto.h>
63 #include <sys/vnode.h>
64 #include <ck_queue.h>
65 #ifdef KTRACE
66 #include <sys/ktrace.h>
67 #endif
68 #ifdef INVARIANTS
69 #include <machine/_inttypes.h>
70 #endif
71 
72 #include <security/audit/audit.h>
73 #include <security/mac/mac_framework.h>
74 
75 #ifdef DDB
76 #include <ddb/ddb.h>
77 #endif
78 
79 #include <vm/uma.h>
80 
81 /*
82  * High level overview of name caching in the VFS layer.
83  *
84  * Originally caching was implemented as part of UFS, later extracted to allow
85  * use by other filesystems. A decision was made to make it optional and
86  * completely detached from the rest of the kernel, which comes with limitations
87  * outlined near the end of this comment block.
88  *
89  * This fundamental choice needs to be revisited. In the meantime, the current
90  * state is described below. Significance of all notable routines is explained
91  * in comments placed above their implementation. Scattered thoroughout the
92  * file are TODO comments indicating shortcomings which can be fixed without
93  * reworking everything (most of the fixes will likely be reusable). Various
94  * details are omitted from this explanation to not clutter the overview, they
95  * have to be checked by reading the code and associated commentary.
96  *
97  * Keep in mind that it's individual path components which are cached, not full
98  * paths. That is, for a fully cached path "foo/bar/baz" there are 3 entries,
99  * one for each name.
100  *
101  * I. Data organization
102  *
103  * Entries are described by "struct namecache" objects and stored in a hash
104  * table. See cache_get_hash for more information.
105  *
106  * "struct vnode" contains pointers to source entries (names which can be found
107  * when traversing through said vnode), destination entries (names of that
108  * vnode (see "Limitations" for a breakdown on the subject) and a pointer to
109  * the parent vnode.
110  *
111  * The (directory vnode; name) tuple reliably determines the target entry if
112  * it exists.
113  *
114  * Since there are no small locks at this time (all are 32 bytes in size on
115  * LP64), the code works around the problem by introducing lock arrays to
116  * protect hash buckets and vnode lists.
117  *
118  * II. Filesystem integration
119  *
120  * Filesystems participating in name caching do the following:
121  * - set vop_lookup routine to vfs_cache_lookup
122  * - set vop_cachedlookup to whatever can perform the lookup if the above fails
123  * - if they support lockless lookup (see below), vop_fplookup_vexec and
124  *   vop_fplookup_symlink are set along with the MNTK_FPLOOKUP flag on the
125  *   mount point
126  * - call cache_purge or cache_vop_* routines to eliminate stale entries as
127  *   applicable
128  * - call cache_enter to add entries depending on the MAKEENTRY flag
129  *
130  * With the above in mind, there are 2 entry points when doing lookups:
131  * - ... -> namei -> cache_fplookup -- this is the default
132  * - ... -> VOP_LOOKUP -> vfs_cache_lookup -- normally only called by namei
133  *   should the above fail
134  *
135  * Example code flow how an entry is added:
136  * ... -> namei -> cache_fplookup -> cache_fplookup_noentry -> VOP_LOOKUP ->
137  * vfs_cache_lookup -> VOP_CACHEDLOOKUP -> ufs_lookup_ino -> cache_enter
138  *
139  * III. Performance considerations
140  *
141  * For lockless case forward lookup avoids any writes to shared areas apart
142  * from the terminal path component. In other words non-modifying lookups of
143  * different files don't suffer any scalability problems in the namecache.
144  * Looking up the same file is limited by VFS and goes beyond the scope of this
145  * file.
146  *
147  * At least on amd64 the single-threaded bottleneck for long paths is hashing
148  * (see cache_get_hash). There are cases where the code issues acquire fence
149  * multiple times, they can be combined on architectures which suffer from it.
150  *
151  * For locked case each encountered vnode has to be referenced and locked in
152  * order to be handed out to the caller (normally that's namei). This
153  * introduces significant hit single-threaded and serialization multi-threaded.
154  *
155  * Reverse lookup (e.g., "getcwd") fully scales provided it is fully cached --
156  * avoids any writes to shared areas to any components.
157  *
158  * Unrelated insertions are partially serialized on updating the global entry
159  * counter and possibly serialized on colliding bucket or vnode locks.
160  *
161  * IV. Observability
162  *
163  * Note not everything has an explicit dtrace probe nor it should have, thus
164  * some of the one-liners below depend on implementation details.
165  *
166  * Examples:
167  *
168  * # Check what lookups failed to be handled in a lockless manner. Column 1 is
169  * # line number, column 2 is status code (see cache_fpl_status)
170  * dtrace -n 'vfs:fplookup:lookup:done { @[arg1, arg2] = count(); }'
171  *
172  * # Lengths of names added by binary name
173  * dtrace -n 'fbt::cache_enter_time:entry { @[execname] = quantize(args[2]->cn_namelen); }'
174  *
175  * # Same as above but only those which exceed 64 characters
176  * dtrace -n 'fbt::cache_enter_time:entry /args[2]->cn_namelen > 64/ { @[execname] = quantize(args[2]->cn_namelen); }'
177  *
178  * # Who is performing lookups with spurious slashes (e.g., "foo//bar") and what
179  * # path is it
180  * dtrace -n 'fbt::cache_fplookup_skip_slashes:entry { @[execname, stringof(args[0]->cnp->cn_pnbuf)] = count(); }'
181  *
182  * V. Limitations and implementation defects
183  *
184  * - since it is possible there is no entry for an open file, tools like
185  *   "procstat" may fail to resolve fd -> vnode -> path to anything
186  * - even if a filesystem adds an entry, it may get purged (e.g., due to memory
187  *   shortage) in which case the above problem applies
188  * - hardlinks are not tracked, thus if a vnode is reachable in more than one
189  *   way, resolving a name may return a different path than the one used to
190  *   open it (even if said path is still valid)
191  * - by default entries are not added for newly created files
192  * - adding an entry may need to evict negative entry first, which happens in 2
193  *   distinct places (evicting on lookup, adding in a later VOP) making it
194  *   impossible to simply reuse it
195  * - there is a simple scheme to evict negative entries as the cache is approaching
196  *   its capacity, but it is very unclear if doing so is a good idea to begin with
197  * - vnodes are subject to being recycled even if target inode is left in memory,
198  *   which loses the name cache entries when it perhaps should not. in case of tmpfs
199  *   names get duplicated -- kept by filesystem itself and namecache separately
200  * - struct namecache has a fixed size and comes in 2 variants, often wasting space.
201  *   now hard to replace with malloc due to dependence on SMR.
202  * - lack of better integration with the kernel also turns nullfs into a layered
203  *   filesystem instead of something which can take advantage of caching
204  */
205 
206 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
207     "Name cache");
208 
209 SDT_PROVIDER_DECLARE(vfs);
210 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
211     "struct vnode *");
212 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
213     "struct vnode *");
214 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
215     "char *");
216 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
217     "const char *");
218 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
219     "struct namecache *", "int", "int");
220 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
221 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
222     "char *", "struct vnode *");
223 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
224 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
225     "struct vnode *", "char *");
226 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
227     "struct vnode *");
228 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
229     "struct vnode *", "char *");
230 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
231     "char *");
232 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
233     "struct componentname *");
234 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
235     "struct componentname *");
236 SDT_PROBE_DEFINE3(vfs, namecache, purge, done, "struct vnode *", "size_t", "size_t");
237 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
238 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
239 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
240 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
241     "struct vnode *");
242 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
243     "char *");
244 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
245     "char *");
246 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
247 
248 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
249 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
250 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
251 
252 static char __read_frequently cache_fast_lookup_enabled = true;
253 
254 /*
255  * This structure describes the elements in the cache of recent
256  * names looked up by namei.
257  */
258 struct negstate {
259 	u_char neg_flag;
260 	u_char neg_hit;
261 };
262 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
263     "the state must fit in a union with a pointer without growing it");
264 
265 struct	namecache {
266 	LIST_ENTRY(namecache) nc_src;	/* source vnode list */
267 	TAILQ_ENTRY(namecache) nc_dst;	/* destination vnode list */
268 	CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
269 	struct	vnode *nc_dvp;		/* vnode of parent of name */
270 	union {
271 		struct	vnode *nu_vp;	/* vnode the name refers to */
272 		struct	negstate nu_neg;/* negative entry state */
273 	} n_un;
274 	u_char	nc_flag;		/* flag bits */
275 	u_char	nc_nlen;		/* length of name */
276 	char	nc_name[];		/* segment name + nul */
277 };
278 
279 /*
280  * struct namecache_ts repeats struct namecache layout up to the
281  * nc_nlen member.
282  * struct namecache_ts is used in place of struct namecache when time(s) need
283  * to be stored.  The nc_dotdottime field is used when a cache entry is mapping
284  * both a non-dotdot directory name plus dotdot for the directory's
285  * parent.
286  *
287  * See below for alignment requirement.
288  */
289 struct	namecache_ts {
290 	struct	timespec nc_time;	/* timespec provided by fs */
291 	struct	timespec nc_dotdottime;	/* dotdot timespec provided by fs */
292 	int	nc_ticks;		/* ticks value when entry was added */
293 	int	nc_pad;
294 	struct namecache nc_nc;
295 };
296 
297 TAILQ_HEAD(cache_freebatch, namecache);
298 
299 /*
300  * At least mips n32 performs 64-bit accesses to timespec as found
301  * in namecache_ts and requires them to be aligned. Since others
302  * may be in the same spot suffer a little bit and enforce the
303  * alignment for everyone. Note this is a nop for 64-bit platforms.
304  */
305 #define CACHE_ZONE_ALIGNMENT	UMA_ALIGNOF(time_t)
306 
307 /*
308  * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
309  * 4.4 BSD codebase. Later on struct namecache was tweaked to become
310  * smaller and the value was bumped to retain the total size, but it
311  * was never re-evaluated for suitability. A simple test counting
312  * lengths during package building shows that the value of 45 covers
313  * about 86% of all added entries, reaching 99% at 65.
314  *
315  * Regardless of the above, use of dedicated zones instead of malloc may be
316  * inducing additional waste. This may be hard to address as said zones are
317  * tied to VFS SMR. Even if retaining them, the current split should be
318  * re-evaluated.
319  */
320 #ifdef __LP64__
321 #define	CACHE_PATH_CUTOFF	45
322 #define	CACHE_LARGE_PAD		6
323 #else
324 #define	CACHE_PATH_CUTOFF	41
325 #define	CACHE_LARGE_PAD		2
326 #endif
327 
328 #define CACHE_ZONE_SMALL_SIZE		(offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
329 #define CACHE_ZONE_SMALL_TS_SIZE	(offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
330 #define CACHE_ZONE_LARGE_SIZE		(offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
331 #define CACHE_ZONE_LARGE_TS_SIZE	(offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
332 
333 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
334 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
335 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
336 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
337 
338 #define	nc_vp		n_un.nu_vp
339 #define	nc_neg		n_un.nu_neg
340 
341 /*
342  * Flags in namecache.nc_flag
343  */
344 #define NCF_WHITE	0x01
345 #define NCF_ISDOTDOT	0x02
346 #define	NCF_TS		0x04
347 #define	NCF_DTS		0x08
348 #define	NCF_DVDROP	0x10
349 #define	NCF_NEGATIVE	0x20
350 #define	NCF_INVALID	0x40
351 #define	NCF_WIP		0x80
352 
353 /*
354  * Flags in negstate.neg_flag
355  */
356 #define NEG_HOT		0x01
357 
358 static bool	cache_neg_evict_cond(u_long lnumcache);
359 
360 /*
361  * Mark an entry as invalid.
362  *
363  * This is called before it starts getting deconstructed.
364  */
365 static void
366 cache_ncp_invalidate(struct namecache *ncp)
367 {
368 
369 	KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
370 	    ("%s: entry %p already invalid", __func__, ncp));
371 	atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
372 	atomic_thread_fence_rel();
373 }
374 
375 /*
376  * Check whether the entry can be safely used.
377  *
378  * All places which elide locks are supposed to call this after they are
379  * done with reading from an entry.
380  */
381 #define cache_ncp_canuse(ncp)	({					\
382 	struct namecache *_ncp = (ncp);					\
383 	u_char _nc_flag;						\
384 									\
385 	atomic_thread_fence_acq();					\
386 	_nc_flag = atomic_load_char(&_ncp->nc_flag);			\
387 	__predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0);	\
388 })
389 
390 /*
391  * Like the above but also checks NCF_WHITE.
392  */
393 #define cache_fpl_neg_ncp_canuse(ncp)	({				\
394 	struct namecache *_ncp = (ncp);					\
395 	u_char _nc_flag;						\
396 									\
397 	atomic_thread_fence_acq();					\
398 	_nc_flag = atomic_load_char(&_ncp->nc_flag);			\
399 	__predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0);	\
400 })
401 
402 VFS_SMR_DECLARE;
403 
404 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
405     "Name cache parameters");
406 
407 static u_int __read_mostly	ncsize; /* the size as computed on creation or resizing */
408 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RD, &ncsize, 0,
409     "Total namecache capacity");
410 
411 u_int ncsizefactor = 2;
412 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
413     "Size factor for namecache");
414 
415 static u_long __read_mostly	ncnegfactor = 5; /* ratio of negative entries */
416 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
417     "Ratio of negative namecache entries");
418 
419 /*
420  * Negative entry % of namecache capacity above which automatic eviction is allowed.
421  *
422  * Check cache_neg_evict_cond for details.
423  */
424 static u_int ncnegminpct = 3;
425 
426 static u_int __read_mostly     neg_min; /* the above recomputed against ncsize */
427 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
428     "Negative entry count above which automatic eviction is allowed");
429 
430 /*
431  * Structures associated with name caching.
432  */
433 #define NCHHASH(hash) \
434 	(&nchashtbl[(hash) & nchash])
435 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
436 static u_long __read_mostly	nchash;			/* size of hash table */
437 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
438     "Size of namecache hash table");
439 static u_long __exclusive_cache_line	numneg;	/* number of negative entries allocated */
440 static u_long __exclusive_cache_line	numcache;/* number of cache entries allocated */
441 
442 struct nchstats	nchstats;		/* cache effectiveness statistics */
443 
444 static u_int __exclusive_cache_line neg_cycle;
445 
446 #define ncneghash	3
447 #define	numneglists	(ncneghash + 1)
448 
449 struct neglist {
450 	struct mtx		nl_evict_lock;
451 	struct mtx		nl_lock __aligned(CACHE_LINE_SIZE);
452 	TAILQ_HEAD(, namecache) nl_list;
453 	TAILQ_HEAD(, namecache) nl_hotlist;
454 	u_long			nl_hotnum;
455 } __aligned(CACHE_LINE_SIZE);
456 
457 static struct neglist neglists[numneglists];
458 
459 static inline struct neglist *
460 NCP2NEGLIST(struct namecache *ncp)
461 {
462 
463 	return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
464 }
465 
466 static inline struct negstate *
467 NCP2NEGSTATE(struct namecache *ncp)
468 {
469 
470 	MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
471 	return (&ncp->nc_neg);
472 }
473 
474 #define	numbucketlocks (ncbuckethash + 1)
475 static u_int __read_mostly  ncbuckethash;
476 static struct mtx_padalign __read_mostly  *bucketlocks;
477 #define	HASH2BUCKETLOCK(hash) \
478 	((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
479 
480 #define	numvnodelocks (ncvnodehash + 1)
481 static u_int __read_mostly  ncvnodehash;
482 static struct mtx __read_mostly *vnodelocks;
483 static inline struct mtx *
484 VP2VNODELOCK(struct vnode *vp)
485 {
486 
487 	return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
488 }
489 
490 static void
491 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
492 {
493 	struct namecache_ts *ncp_ts;
494 
495 	KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
496 	    (tsp == NULL && ticksp == NULL),
497 	    ("No NCF_TS"));
498 
499 	if (tsp == NULL)
500 		return;
501 
502 	ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
503 	*tsp = ncp_ts->nc_time;
504 	*ticksp = ncp_ts->nc_ticks;
505 }
506 
507 #ifdef DEBUG_CACHE
508 static int __read_mostly	doingcache = 1;	/* 1 => enable the cache */
509 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
510     "VFS namecache enabled");
511 #endif
512 
513 /* Export size information to userland */
514 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
515     sizeof(struct namecache), "sizeof(struct namecache)");
516 
517 /*
518  * The new name cache statistics
519  */
520 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
521     "Name cache statistics");
522 
523 #define STATNODE_ULONG(name, varname, descr)					\
524 	SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
525 #define STATNODE_COUNTER(name, varname, descr)					\
526 	static COUNTER_U64_DEFINE_EARLY(varname);				\
527 	SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
528 	    descr);
529 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
530 STATNODE_ULONG(count, numcache, "Number of cache entries");
531 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
532 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
533 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
534 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
535 STATNODE_COUNTER(poszaps, numposzaps,
536     "Number of cache hits (positive) we do not want to cache");
537 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
538 STATNODE_COUNTER(negzaps, numnegzaps,
539     "Number of cache hits (negative) we do not want to cache");
540 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
541 /* These count for vn_getcwd(), too. */
542 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
543 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
544     "Number of fullpath search errors (VOP_VPTOCNP failures)");
545 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
546 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
547 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
548 
549 /*
550  * Debug or developer statistics.
551  */
552 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
553     "Name cache debugging");
554 #define DEBUGNODE_ULONG(name, varname, descr)					\
555 	SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
556 static u_long zap_bucket_relock_success;
557 DEBUGNODE_ULONG(zap_bucket_relock_success, zap_bucket_relock_success,
558     "Number of successful removals after relocking");
559 static u_long zap_bucket_fail;
560 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
561 static u_long zap_bucket_fail2;
562 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
563 static u_long cache_lock_vnodes_cel_3_failures;
564 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
565     "Number of times 3-way vnode locking failed");
566 
567 static void cache_zap_locked(struct namecache *ncp);
568 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
569     char **retbuf, size_t *buflen, size_t addend);
570 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
571     char **retbuf, size_t *buflen);
572 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
573     char **retbuf, size_t *len, size_t addend);
574 
575 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
576 
577 static inline void
578 cache_assert_vlp_locked(struct mtx *vlp)
579 {
580 
581 	if (vlp != NULL)
582 		mtx_assert(vlp, MA_OWNED);
583 }
584 
585 static inline void
586 cache_assert_vnode_locked(struct vnode *vp)
587 {
588 	struct mtx *vlp;
589 
590 	vlp = VP2VNODELOCK(vp);
591 	cache_assert_vlp_locked(vlp);
592 }
593 
594 /*
595  * Directory vnodes with entries are held for two reasons:
596  * 1. make them less of a target for reclamation in vnlru
597  * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
598  *
599  * It will be feasible to stop doing it altogether if all filesystems start
600  * supporting lockless lookup.
601  */
602 static void
603 cache_hold_vnode(struct vnode *vp)
604 {
605 
606 	cache_assert_vnode_locked(vp);
607 	VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
608 	vhold(vp);
609 	counter_u64_add(numcachehv, 1);
610 }
611 
612 static void
613 cache_drop_vnode(struct vnode *vp)
614 {
615 
616 	/*
617 	 * Called after all locks are dropped, meaning we can't assert
618 	 * on the state of v_cache_src.
619 	 */
620 	vdrop(vp);
621 	counter_u64_add(numcachehv, -1);
622 }
623 
624 /*
625  * UMA zones.
626  */
627 static uma_zone_t __read_mostly cache_zone_small;
628 static uma_zone_t __read_mostly cache_zone_small_ts;
629 static uma_zone_t __read_mostly cache_zone_large;
630 static uma_zone_t __read_mostly cache_zone_large_ts;
631 
632 char *
633 cache_symlink_alloc(size_t size, int flags)
634 {
635 
636 	if (size < CACHE_ZONE_SMALL_SIZE) {
637 		return (uma_zalloc_smr(cache_zone_small, flags));
638 	}
639 	if (size < CACHE_ZONE_LARGE_SIZE) {
640 		return (uma_zalloc_smr(cache_zone_large, flags));
641 	}
642 	counter_u64_add(symlinktoobig, 1);
643 	SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
644 	return (NULL);
645 }
646 
647 void
648 cache_symlink_free(char *string, size_t size)
649 {
650 
651 	MPASS(string != NULL);
652 	KASSERT(size < CACHE_ZONE_LARGE_SIZE,
653 	    ("%s: size %zu too big", __func__, size));
654 
655 	if (size < CACHE_ZONE_SMALL_SIZE) {
656 		uma_zfree_smr(cache_zone_small, string);
657 		return;
658 	}
659 	if (size < CACHE_ZONE_LARGE_SIZE) {
660 		uma_zfree_smr(cache_zone_large, string);
661 		return;
662 	}
663 	__assert_unreachable();
664 }
665 
666 static struct namecache *
667 cache_alloc_uma(int len, bool ts)
668 {
669 	struct namecache_ts *ncp_ts;
670 	struct namecache *ncp;
671 
672 	if (__predict_false(ts)) {
673 		if (len <= CACHE_PATH_CUTOFF)
674 			ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
675 		else
676 			ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
677 		ncp = &ncp_ts->nc_nc;
678 	} else {
679 		if (len <= CACHE_PATH_CUTOFF)
680 			ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
681 		else
682 			ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
683 	}
684 	return (ncp);
685 }
686 
687 static void
688 cache_free_uma(struct namecache *ncp)
689 {
690 	struct namecache_ts *ncp_ts;
691 
692 	if (__predict_false(ncp->nc_flag & NCF_TS)) {
693 		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
694 		if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
695 			uma_zfree_smr(cache_zone_small_ts, ncp_ts);
696 		else
697 			uma_zfree_smr(cache_zone_large_ts, ncp_ts);
698 	} else {
699 		if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
700 			uma_zfree_smr(cache_zone_small, ncp);
701 		else
702 			uma_zfree_smr(cache_zone_large, ncp);
703 	}
704 }
705 
706 static struct namecache *
707 cache_alloc(int len, bool ts)
708 {
709 	u_long lnumcache;
710 
711 	/*
712 	 * Avoid blowout in namecache entries.
713 	 *
714 	 * Bugs:
715 	 * 1. filesystems may end up trying to add an already existing entry
716 	 * (for example this can happen after a cache miss during concurrent
717 	 * lookup), in which case we will call cache_neg_evict despite not
718 	 * adding anything.
719 	 * 2. the routine may fail to free anything and no provisions are made
720 	 * to make it try harder (see the inside for failure modes)
721 	 * 3. it only ever looks at negative entries.
722 	 */
723 	lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
724 	if (cache_neg_evict_cond(lnumcache)) {
725 		lnumcache = atomic_load_long(&numcache);
726 	}
727 	if (__predict_false(lnumcache >= ncsize)) {
728 		atomic_subtract_long(&numcache, 1);
729 		counter_u64_add(numdrops, 1);
730 		return (NULL);
731 	}
732 	return (cache_alloc_uma(len, ts));
733 }
734 
735 static void
736 cache_free(struct namecache *ncp)
737 {
738 
739 	MPASS(ncp != NULL);
740 	if ((ncp->nc_flag & NCF_DVDROP) != 0) {
741 		cache_drop_vnode(ncp->nc_dvp);
742 	}
743 	cache_free_uma(ncp);
744 	atomic_subtract_long(&numcache, 1);
745 }
746 
747 static void
748 cache_free_batch(struct cache_freebatch *batch)
749 {
750 	struct namecache *ncp, *nnp;
751 	int i;
752 
753 	i = 0;
754 	if (TAILQ_EMPTY(batch))
755 		goto out;
756 	TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
757 		if ((ncp->nc_flag & NCF_DVDROP) != 0) {
758 			cache_drop_vnode(ncp->nc_dvp);
759 		}
760 		cache_free_uma(ncp);
761 		i++;
762 	}
763 	atomic_subtract_long(&numcache, i);
764 out:
765 	SDT_PROBE1(vfs, namecache, purge, batch, i);
766 }
767 
768 /*
769  * Hashing.
770  *
771  * The code was made to use FNV in 2001 and this choice needs to be revisited.
772  *
773  * Short summary of the difficulty:
774  * The longest name which can be inserted is NAME_MAX characters in length (or
775  * 255 at the time of writing this comment), while majority of names used in
776  * practice are significantly shorter (mostly below 10). More importantly
777  * majority of lookups performed find names are even shorter than that.
778  *
779  * This poses a problem where hashes which do better than FNV past word size
780  * (or so) tend to come with additional overhead when finalizing the result,
781  * making them noticeably slower for the most commonly used range.
782  *
783  * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
784  *
785  * When looking it up the most time consuming part by a large margin (at least
786  * on amd64) is hashing.  Replacing FNV with something which pessimizes short
787  * input would make the slowest part stand out even more.
788  */
789 
790 /*
791  * TODO: With the value stored we can do better than computing the hash based
792  * on the address.
793  */
794 static void
795 cache_prehash(struct vnode *vp)
796 {
797 
798 	vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
799 }
800 
801 static uint32_t
802 cache_get_hash(char *name, u_char len, struct vnode *dvp)
803 {
804 
805 	return (fnv_32_buf(name, len, dvp->v_nchash));
806 }
807 
808 static uint32_t
809 cache_get_hash_iter_start(struct vnode *dvp)
810 {
811 
812 	return (dvp->v_nchash);
813 }
814 
815 static uint32_t
816 cache_get_hash_iter(char c, uint32_t hash)
817 {
818 
819 	return (fnv_32_buf(&c, 1, hash));
820 }
821 
822 static uint32_t
823 cache_get_hash_iter_finish(uint32_t hash)
824 {
825 
826 	return (hash);
827 }
828 
829 static inline struct nchashhead *
830 NCP2BUCKET(struct namecache *ncp)
831 {
832 	uint32_t hash;
833 
834 	hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
835 	return (NCHHASH(hash));
836 }
837 
838 static inline struct mtx *
839 NCP2BUCKETLOCK(struct namecache *ncp)
840 {
841 	uint32_t hash;
842 
843 	hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
844 	return (HASH2BUCKETLOCK(hash));
845 }
846 
847 #ifdef INVARIANTS
848 static void
849 cache_assert_bucket_locked(struct namecache *ncp)
850 {
851 	struct mtx *blp;
852 
853 	blp = NCP2BUCKETLOCK(ncp);
854 	mtx_assert(blp, MA_OWNED);
855 }
856 
857 static void
858 cache_assert_bucket_unlocked(struct namecache *ncp)
859 {
860 	struct mtx *blp;
861 
862 	blp = NCP2BUCKETLOCK(ncp);
863 	mtx_assert(blp, MA_NOTOWNED);
864 }
865 #else
866 #define cache_assert_bucket_locked(x) do { } while (0)
867 #define cache_assert_bucket_unlocked(x) do { } while (0)
868 #endif
869 
870 #define cache_sort_vnodes(x, y)	_cache_sort_vnodes((void **)(x), (void **)(y))
871 static void
872 _cache_sort_vnodes(void **p1, void **p2)
873 {
874 	void *tmp;
875 
876 	MPASS(*p1 != NULL || *p2 != NULL);
877 
878 	if (*p1 > *p2) {
879 		tmp = *p2;
880 		*p2 = *p1;
881 		*p1 = tmp;
882 	}
883 }
884 
885 static void
886 cache_lock_all_buckets(void)
887 {
888 	u_int i;
889 
890 	for (i = 0; i < numbucketlocks; i++)
891 		mtx_lock(&bucketlocks[i]);
892 }
893 
894 static void
895 cache_unlock_all_buckets(void)
896 {
897 	u_int i;
898 
899 	for (i = 0; i < numbucketlocks; i++)
900 		mtx_unlock(&bucketlocks[i]);
901 }
902 
903 static void
904 cache_lock_all_vnodes(void)
905 {
906 	u_int i;
907 
908 	for (i = 0; i < numvnodelocks; i++)
909 		mtx_lock(&vnodelocks[i]);
910 }
911 
912 static void
913 cache_unlock_all_vnodes(void)
914 {
915 	u_int i;
916 
917 	for (i = 0; i < numvnodelocks; i++)
918 		mtx_unlock(&vnodelocks[i]);
919 }
920 
921 static int
922 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
923 {
924 
925 	cache_sort_vnodes(&vlp1, &vlp2);
926 
927 	if (vlp1 != NULL) {
928 		if (!mtx_trylock(vlp1))
929 			return (EAGAIN);
930 	}
931 	if (!mtx_trylock(vlp2)) {
932 		if (vlp1 != NULL)
933 			mtx_unlock(vlp1);
934 		return (EAGAIN);
935 	}
936 
937 	return (0);
938 }
939 
940 static void
941 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
942 {
943 
944 	MPASS(vlp1 != NULL || vlp2 != NULL);
945 	MPASS(vlp1 <= vlp2);
946 
947 	if (vlp1 != NULL)
948 		mtx_lock(vlp1);
949 	if (vlp2 != NULL)
950 		mtx_lock(vlp2);
951 }
952 
953 static void
954 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
955 {
956 
957 	MPASS(vlp1 != NULL || vlp2 != NULL);
958 
959 	if (vlp1 != NULL)
960 		mtx_unlock(vlp1);
961 	if (vlp2 != NULL)
962 		mtx_unlock(vlp2);
963 }
964 
965 static int
966 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
967 {
968 	struct nchstats snap;
969 
970 	if (req->oldptr == NULL)
971 		return (SYSCTL_OUT(req, 0, sizeof(snap)));
972 
973 	snap = nchstats;
974 	snap.ncs_goodhits = counter_u64_fetch(numposhits);
975 	snap.ncs_neghits = counter_u64_fetch(numneghits);
976 	snap.ncs_badhits = counter_u64_fetch(numposzaps) +
977 	    counter_u64_fetch(numnegzaps);
978 	snap.ncs_miss = counter_u64_fetch(nummisszap) +
979 	    counter_u64_fetch(nummiss);
980 
981 	return (SYSCTL_OUT(req, &snap, sizeof(snap)));
982 }
983 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
984     CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
985     "VFS cache effectiveness statistics");
986 
987 static void
988 cache_recalc_neg_min(void)
989 {
990 
991 	neg_min = (ncsize * ncnegminpct) / 100;
992 }
993 
994 static int
995 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
996 {
997 	u_int val;
998 	int error;
999 
1000 	val = ncnegminpct;
1001 	error = sysctl_handle_int(oidp, &val, 0, req);
1002 	if (error != 0 || req->newptr == NULL)
1003 		return (error);
1004 
1005 	if (val == ncnegminpct)
1006 		return (0);
1007 	if (val < 0 || val > 99)
1008 		return (EINVAL);
1009 	ncnegminpct = val;
1010 	cache_recalc_neg_min();
1011 	return (0);
1012 }
1013 
1014 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1015     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1016     "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1017 
1018 #ifdef DEBUG_CACHE
1019 /*
1020  * Grab an atomic snapshot of the name cache hash chain lengths
1021  */
1022 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1023     CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1024     "hash table stats");
1025 
1026 static int
1027 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1028 {
1029 	struct nchashhead *ncpp;
1030 	struct namecache *ncp;
1031 	int i, error, n_nchash, *cntbuf;
1032 
1033 retry:
1034 	n_nchash = nchash + 1;	/* nchash is max index, not count */
1035 	if (req->oldptr == NULL)
1036 		return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1037 	cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1038 	cache_lock_all_buckets();
1039 	if (n_nchash != nchash + 1) {
1040 		cache_unlock_all_buckets();
1041 		free(cntbuf, M_TEMP);
1042 		goto retry;
1043 	}
1044 	/* Scan hash tables counting entries */
1045 	for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1046 		CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1047 			cntbuf[i]++;
1048 	cache_unlock_all_buckets();
1049 	for (error = 0, i = 0; i < n_nchash; i++)
1050 		if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1051 			break;
1052 	free(cntbuf, M_TEMP);
1053 	return (error);
1054 }
1055 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1056     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1057     "nchash chain lengths");
1058 
1059 static int
1060 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1061 {
1062 	int error;
1063 	struct nchashhead *ncpp;
1064 	struct namecache *ncp;
1065 	int n_nchash;
1066 	int count, maxlength, used, pct;
1067 
1068 	if (!req->oldptr)
1069 		return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1070 
1071 	cache_lock_all_buckets();
1072 	n_nchash = nchash + 1;	/* nchash is max index, not count */
1073 	used = 0;
1074 	maxlength = 0;
1075 
1076 	/* Scan hash tables for applicable entries */
1077 	for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1078 		count = 0;
1079 		CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1080 			count++;
1081 		}
1082 		if (count)
1083 			used++;
1084 		if (maxlength < count)
1085 			maxlength = count;
1086 	}
1087 	n_nchash = nchash + 1;
1088 	cache_unlock_all_buckets();
1089 	pct = (used * 100) / (n_nchash / 100);
1090 	error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1091 	if (error)
1092 		return (error);
1093 	error = SYSCTL_OUT(req, &used, sizeof(used));
1094 	if (error)
1095 		return (error);
1096 	error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1097 	if (error)
1098 		return (error);
1099 	error = SYSCTL_OUT(req, &pct, sizeof(pct));
1100 	if (error)
1101 		return (error);
1102 	return (0);
1103 }
1104 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1105     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1106     "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1107 #endif
1108 
1109 /*
1110  * Negative entries management
1111  *
1112  * Various workloads create plenty of negative entries and barely use them
1113  * afterwards. Moreover malicious users can keep performing bogus lookups
1114  * adding even more entries. For example "make tinderbox" as of writing this
1115  * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1116  * negative.
1117  *
1118  * As such, a rather aggressive eviction method is needed. The currently
1119  * employed method is a placeholder.
1120  *
1121  * Entries are split over numneglists separate lists, each of which is further
1122  * split into hot and cold entries. Entries get promoted after getting a hit.
1123  * Eviction happens on addition of new entry.
1124  */
1125 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1126     "Name cache negative entry statistics");
1127 
1128 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1129     "Number of negative cache entries");
1130 
1131 static COUNTER_U64_DEFINE_EARLY(neg_created);
1132 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1133     "Number of created negative entries");
1134 
1135 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1136 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1137     "Number of evicted negative entries");
1138 
1139 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1140 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1141     &neg_evict_skipped_empty,
1142     "Number of times evicting failed due to lack of entries");
1143 
1144 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1145 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1146     &neg_evict_skipped_missed,
1147     "Number of times evicting failed due to target entry disappearing");
1148 
1149 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1150 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1151     &neg_evict_skipped_contended,
1152     "Number of times evicting failed due to contention");
1153 
1154 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1155     "Number of cache hits (negative)");
1156 
1157 static int
1158 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1159 {
1160 	int i, out;
1161 
1162 	out = 0;
1163 	for (i = 0; i < numneglists; i++)
1164 		out += neglists[i].nl_hotnum;
1165 
1166 	return (SYSCTL_OUT(req, &out, sizeof(out)));
1167 }
1168 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1169     CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1170     "Number of hot negative entries");
1171 
1172 static void
1173 cache_neg_init(struct namecache *ncp)
1174 {
1175 	struct negstate *ns;
1176 
1177 	ncp->nc_flag |= NCF_NEGATIVE;
1178 	ns = NCP2NEGSTATE(ncp);
1179 	ns->neg_flag = 0;
1180 	ns->neg_hit = 0;
1181 	counter_u64_add(neg_created, 1);
1182 }
1183 
1184 #define CACHE_NEG_PROMOTION_THRESH 2
1185 
1186 static bool
1187 cache_neg_hit_prep(struct namecache *ncp)
1188 {
1189 	struct negstate *ns;
1190 	u_char n;
1191 
1192 	ns = NCP2NEGSTATE(ncp);
1193 	n = atomic_load_char(&ns->neg_hit);
1194 	for (;;) {
1195 		if (n >= CACHE_NEG_PROMOTION_THRESH)
1196 			return (false);
1197 		if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1198 			break;
1199 	}
1200 	return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1201 }
1202 
1203 /*
1204  * Nothing to do here but it is provided for completeness as some
1205  * cache_neg_hit_prep callers may end up returning without even
1206  * trying to promote.
1207  */
1208 #define cache_neg_hit_abort(ncp)	do { } while (0)
1209 
1210 static void
1211 cache_neg_hit_finish(struct namecache *ncp)
1212 {
1213 
1214 	SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1215 	counter_u64_add(numneghits, 1);
1216 }
1217 
1218 /*
1219  * Move a negative entry to the hot list.
1220  */
1221 static void
1222 cache_neg_promote_locked(struct namecache *ncp)
1223 {
1224 	struct neglist *nl;
1225 	struct negstate *ns;
1226 
1227 	ns = NCP2NEGSTATE(ncp);
1228 	nl = NCP2NEGLIST(ncp);
1229 	mtx_assert(&nl->nl_lock, MA_OWNED);
1230 	if ((ns->neg_flag & NEG_HOT) == 0) {
1231 		TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1232 		TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1233 		nl->nl_hotnum++;
1234 		ns->neg_flag |= NEG_HOT;
1235 	}
1236 }
1237 
1238 /*
1239  * Move a hot negative entry to the cold list.
1240  */
1241 static void
1242 cache_neg_demote_locked(struct namecache *ncp)
1243 {
1244 	struct neglist *nl;
1245 	struct negstate *ns;
1246 
1247 	ns = NCP2NEGSTATE(ncp);
1248 	nl = NCP2NEGLIST(ncp);
1249 	mtx_assert(&nl->nl_lock, MA_OWNED);
1250 	MPASS(ns->neg_flag & NEG_HOT);
1251 	TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1252 	TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1253 	nl->nl_hotnum--;
1254 	ns->neg_flag &= ~NEG_HOT;
1255 	atomic_store_char(&ns->neg_hit, 0);
1256 }
1257 
1258 /*
1259  * Move a negative entry to the hot list if it matches the lookup.
1260  *
1261  * We have to take locks, but they may be contended and in the worst
1262  * case we may need to go off CPU. We don't want to spin within the
1263  * smr section and we can't block with it. Exiting the section means
1264  * the found entry could have been evicted. We are going to look it
1265  * up again.
1266  */
1267 static bool
1268 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1269     struct namecache *oncp, uint32_t hash)
1270 {
1271 	struct namecache *ncp;
1272 	struct neglist *nl;
1273 	u_char nc_flag;
1274 
1275 	nl = NCP2NEGLIST(oncp);
1276 
1277 	mtx_lock(&nl->nl_lock);
1278 	/*
1279 	 * For hash iteration.
1280 	 */
1281 	vfs_smr_enter();
1282 
1283 	/*
1284 	 * Avoid all surprises by only succeeding if we got the same entry and
1285 	 * bailing completely otherwise.
1286 	 * XXX There are no provisions to keep the vnode around, meaning we may
1287 	 * end up promoting a negative entry for a *new* vnode and returning
1288 	 * ENOENT on its account. This is the error we want to return anyway
1289 	 * and promotion is harmless.
1290 	 *
1291 	 * In particular at this point there can be a new ncp which matches the
1292 	 * search but hashes to a different neglist.
1293 	 */
1294 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1295 		if (ncp == oncp)
1296 			break;
1297 	}
1298 
1299 	/*
1300 	 * No match to begin with.
1301 	 */
1302 	if (__predict_false(ncp == NULL)) {
1303 		goto out_abort;
1304 	}
1305 
1306 	/*
1307 	 * The newly found entry may be something different...
1308 	 */
1309 	if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1310 	    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1311 		goto out_abort;
1312 	}
1313 
1314 	/*
1315 	 * ... and not even negative.
1316 	 */
1317 	nc_flag = atomic_load_char(&ncp->nc_flag);
1318 	if ((nc_flag & NCF_NEGATIVE) == 0) {
1319 		goto out_abort;
1320 	}
1321 
1322 	if (!cache_ncp_canuse(ncp)) {
1323 		goto out_abort;
1324 	}
1325 
1326 	cache_neg_promote_locked(ncp);
1327 	cache_neg_hit_finish(ncp);
1328 	vfs_smr_exit();
1329 	mtx_unlock(&nl->nl_lock);
1330 	return (true);
1331 out_abort:
1332 	vfs_smr_exit();
1333 	mtx_unlock(&nl->nl_lock);
1334 	return (false);
1335 }
1336 
1337 static void
1338 cache_neg_promote(struct namecache *ncp)
1339 {
1340 	struct neglist *nl;
1341 
1342 	nl = NCP2NEGLIST(ncp);
1343 	mtx_lock(&nl->nl_lock);
1344 	cache_neg_promote_locked(ncp);
1345 	mtx_unlock(&nl->nl_lock);
1346 }
1347 
1348 static void
1349 cache_neg_insert(struct namecache *ncp)
1350 {
1351 	struct neglist *nl;
1352 
1353 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
1354 	cache_assert_bucket_locked(ncp);
1355 	nl = NCP2NEGLIST(ncp);
1356 	mtx_lock(&nl->nl_lock);
1357 	TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1358 	mtx_unlock(&nl->nl_lock);
1359 	atomic_add_long(&numneg, 1);
1360 }
1361 
1362 static void
1363 cache_neg_remove(struct namecache *ncp)
1364 {
1365 	struct neglist *nl;
1366 	struct negstate *ns;
1367 
1368 	cache_assert_bucket_locked(ncp);
1369 	nl = NCP2NEGLIST(ncp);
1370 	ns = NCP2NEGSTATE(ncp);
1371 	mtx_lock(&nl->nl_lock);
1372 	if ((ns->neg_flag & NEG_HOT) != 0) {
1373 		TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1374 		nl->nl_hotnum--;
1375 	} else {
1376 		TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1377 	}
1378 	mtx_unlock(&nl->nl_lock);
1379 	atomic_subtract_long(&numneg, 1);
1380 }
1381 
1382 static struct neglist *
1383 cache_neg_evict_select_list(void)
1384 {
1385 	struct neglist *nl;
1386 	u_int c;
1387 
1388 	c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1389 	nl = &neglists[c % numneglists];
1390 	if (!mtx_trylock(&nl->nl_evict_lock)) {
1391 		counter_u64_add(neg_evict_skipped_contended, 1);
1392 		return (NULL);
1393 	}
1394 	return (nl);
1395 }
1396 
1397 static struct namecache *
1398 cache_neg_evict_select_entry(struct neglist *nl)
1399 {
1400 	struct namecache *ncp, *lncp;
1401 	struct negstate *ns, *lns;
1402 	int i;
1403 
1404 	mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1405 	mtx_assert(&nl->nl_lock, MA_OWNED);
1406 	ncp = TAILQ_FIRST(&nl->nl_list);
1407 	if (ncp == NULL)
1408 		return (NULL);
1409 	lncp = ncp;
1410 	lns = NCP2NEGSTATE(lncp);
1411 	for (i = 1; i < 4; i++) {
1412 		ncp = TAILQ_NEXT(ncp, nc_dst);
1413 		if (ncp == NULL)
1414 			break;
1415 		ns = NCP2NEGSTATE(ncp);
1416 		if (ns->neg_hit < lns->neg_hit) {
1417 			lncp = ncp;
1418 			lns = ns;
1419 		}
1420 	}
1421 	return (lncp);
1422 }
1423 
1424 static bool
1425 cache_neg_evict(void)
1426 {
1427 	struct namecache *ncp, *ncp2;
1428 	struct neglist *nl;
1429 	struct vnode *dvp;
1430 	struct mtx *dvlp;
1431 	struct mtx *blp;
1432 	uint32_t hash;
1433 	u_char nlen;
1434 	bool evicted;
1435 
1436 	nl = cache_neg_evict_select_list();
1437 	if (nl == NULL) {
1438 		return (false);
1439 	}
1440 
1441 	mtx_lock(&nl->nl_lock);
1442 	ncp = TAILQ_FIRST(&nl->nl_hotlist);
1443 	if (ncp != NULL) {
1444 		cache_neg_demote_locked(ncp);
1445 	}
1446 	ncp = cache_neg_evict_select_entry(nl);
1447 	if (ncp == NULL) {
1448 		counter_u64_add(neg_evict_skipped_empty, 1);
1449 		mtx_unlock(&nl->nl_lock);
1450 		mtx_unlock(&nl->nl_evict_lock);
1451 		return (false);
1452 	}
1453 	nlen = ncp->nc_nlen;
1454 	dvp = ncp->nc_dvp;
1455 	hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1456 	dvlp = VP2VNODELOCK(dvp);
1457 	blp = HASH2BUCKETLOCK(hash);
1458 	mtx_unlock(&nl->nl_lock);
1459 	mtx_unlock(&nl->nl_evict_lock);
1460 	mtx_lock(dvlp);
1461 	mtx_lock(blp);
1462 	/*
1463 	 * Note that since all locks were dropped above, the entry may be
1464 	 * gone or reallocated to be something else.
1465 	 */
1466 	CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1467 		if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1468 		    ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1469 			break;
1470 	}
1471 	if (ncp2 == NULL) {
1472 		counter_u64_add(neg_evict_skipped_missed, 1);
1473 		ncp = NULL;
1474 		evicted = false;
1475 	} else {
1476 		MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1477 		MPASS(blp == NCP2BUCKETLOCK(ncp));
1478 		SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1479 		    ncp->nc_name);
1480 		cache_zap_locked(ncp);
1481 		counter_u64_add(neg_evicted, 1);
1482 		evicted = true;
1483 	}
1484 	mtx_unlock(blp);
1485 	mtx_unlock(dvlp);
1486 	if (ncp != NULL)
1487 		cache_free(ncp);
1488 	return (evicted);
1489 }
1490 
1491 /*
1492  * Maybe evict a negative entry to create more room.
1493  *
1494  * The ncnegfactor parameter limits what fraction of the total count
1495  * can comprise of negative entries. However, if the cache is just
1496  * warming up this leads to excessive evictions.  As such, ncnegminpct
1497  * (recomputed to neg_min) dictates whether the above should be
1498  * applied.
1499  *
1500  * Try evicting if the cache is close to full capacity regardless of
1501  * other considerations.
1502  */
1503 static bool
1504 cache_neg_evict_cond(u_long lnumcache)
1505 {
1506 	u_long lnumneg;
1507 
1508 	if (ncsize - 1000 < lnumcache)
1509 		goto out_evict;
1510 	lnumneg = atomic_load_long(&numneg);
1511 	if (lnumneg < neg_min)
1512 		return (false);
1513 	if (lnumneg * ncnegfactor < lnumcache)
1514 		return (false);
1515 out_evict:
1516 	return (cache_neg_evict());
1517 }
1518 
1519 /*
1520  * cache_zap_locked():
1521  *
1522  *   Removes a namecache entry from cache, whether it contains an actual
1523  *   pointer to a vnode or if it is just a negative cache entry.
1524  */
1525 static void
1526 cache_zap_locked(struct namecache *ncp)
1527 {
1528 	struct nchashhead *ncpp;
1529 	struct vnode *dvp, *vp;
1530 
1531 	dvp = ncp->nc_dvp;
1532 	vp = ncp->nc_vp;
1533 
1534 	if (!(ncp->nc_flag & NCF_NEGATIVE))
1535 		cache_assert_vnode_locked(vp);
1536 	cache_assert_vnode_locked(dvp);
1537 	cache_assert_bucket_locked(ncp);
1538 
1539 	cache_ncp_invalidate(ncp);
1540 
1541 	ncpp = NCP2BUCKET(ncp);
1542 	CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1543 	if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1544 		SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1545 		TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1546 		if (ncp == vp->v_cache_dd) {
1547 			atomic_store_ptr(&vp->v_cache_dd, NULL);
1548 		}
1549 	} else {
1550 		SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1551 		cache_neg_remove(ncp);
1552 	}
1553 	if (ncp->nc_flag & NCF_ISDOTDOT) {
1554 		if (ncp == dvp->v_cache_dd) {
1555 			atomic_store_ptr(&dvp->v_cache_dd, NULL);
1556 		}
1557 	} else {
1558 		LIST_REMOVE(ncp, nc_src);
1559 		if (LIST_EMPTY(&dvp->v_cache_src)) {
1560 			ncp->nc_flag |= NCF_DVDROP;
1561 		}
1562 	}
1563 }
1564 
1565 static void
1566 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1567 {
1568 	struct mtx *blp;
1569 
1570 	MPASS(ncp->nc_dvp == vp);
1571 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
1572 	cache_assert_vnode_locked(vp);
1573 
1574 	blp = NCP2BUCKETLOCK(ncp);
1575 	mtx_lock(blp);
1576 	cache_zap_locked(ncp);
1577 	mtx_unlock(blp);
1578 }
1579 
1580 static bool
1581 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1582     struct mtx **vlpp)
1583 {
1584 	struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1585 	struct mtx *blp;
1586 
1587 	MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1588 	cache_assert_vnode_locked(vp);
1589 
1590 	if (ncp->nc_flag & NCF_NEGATIVE) {
1591 		if (*vlpp != NULL) {
1592 			mtx_unlock(*vlpp);
1593 			*vlpp = NULL;
1594 		}
1595 		cache_zap_negative_locked_vnode_kl(ncp, vp);
1596 		return (true);
1597 	}
1598 
1599 	pvlp = VP2VNODELOCK(vp);
1600 	blp = NCP2BUCKETLOCK(ncp);
1601 	vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1602 	vlp2 = VP2VNODELOCK(ncp->nc_vp);
1603 
1604 	if (*vlpp == vlp1 || *vlpp == vlp2) {
1605 		to_unlock = *vlpp;
1606 		*vlpp = NULL;
1607 	} else {
1608 		if (*vlpp != NULL) {
1609 			mtx_unlock(*vlpp);
1610 			*vlpp = NULL;
1611 		}
1612 		cache_sort_vnodes(&vlp1, &vlp2);
1613 		if (vlp1 == pvlp) {
1614 			mtx_lock(vlp2);
1615 			to_unlock = vlp2;
1616 		} else {
1617 			if (!mtx_trylock(vlp1))
1618 				goto out_relock;
1619 			to_unlock = vlp1;
1620 		}
1621 	}
1622 	mtx_lock(blp);
1623 	cache_zap_locked(ncp);
1624 	mtx_unlock(blp);
1625 	if (to_unlock != NULL)
1626 		mtx_unlock(to_unlock);
1627 	return (true);
1628 
1629 out_relock:
1630 	mtx_unlock(vlp2);
1631 	mtx_lock(vlp1);
1632 	mtx_lock(vlp2);
1633 	MPASS(*vlpp == NULL);
1634 	*vlpp = vlp1;
1635 	return (false);
1636 }
1637 
1638 /*
1639  * If trylocking failed we can get here. We know enough to take all needed locks
1640  * in the right order and re-lookup the entry.
1641  */
1642 static int
1643 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1644     struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1645     struct mtx *blp)
1646 {
1647 	struct namecache *rncp;
1648 	struct mtx *rvlp;
1649 
1650 	cache_assert_bucket_unlocked(ncp);
1651 
1652 	cache_sort_vnodes(&dvlp, &vlp);
1653 	cache_lock_vnodes(dvlp, vlp);
1654 	mtx_lock(blp);
1655 	CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1656 		if (rncp == ncp && rncp->nc_dvp == dvp &&
1657 		    rncp->nc_nlen == cnp->cn_namelen &&
1658 		    !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1659 			break;
1660 	}
1661 
1662 	if (rncp == NULL)
1663 		goto out_mismatch;
1664 
1665 	if (!(ncp->nc_flag & NCF_NEGATIVE))
1666 		rvlp = VP2VNODELOCK(rncp->nc_vp);
1667 	else
1668 		rvlp = NULL;
1669 	if (rvlp != vlp)
1670 		goto out_mismatch;
1671 
1672 	cache_zap_locked(rncp);
1673 	mtx_unlock(blp);
1674 	cache_unlock_vnodes(dvlp, vlp);
1675 	atomic_add_long(&zap_bucket_relock_success, 1);
1676 	return (0);
1677 
1678 out_mismatch:
1679 	mtx_unlock(blp);
1680 	cache_unlock_vnodes(dvlp, vlp);
1681 	return (EAGAIN);
1682 }
1683 
1684 static int __noinline
1685 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1686     uint32_t hash, struct mtx *blp)
1687 {
1688 	struct mtx *dvlp, *vlp;
1689 	struct vnode *dvp;
1690 
1691 	cache_assert_bucket_locked(ncp);
1692 
1693 	dvlp = VP2VNODELOCK(ncp->nc_dvp);
1694 	vlp = NULL;
1695 	if (!(ncp->nc_flag & NCF_NEGATIVE))
1696 		vlp = VP2VNODELOCK(ncp->nc_vp);
1697 	if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1698 		cache_zap_locked(ncp);
1699 		mtx_unlock(blp);
1700 		cache_unlock_vnodes(dvlp, vlp);
1701 		return (0);
1702 	}
1703 
1704 	dvp = ncp->nc_dvp;
1705 	mtx_unlock(blp);
1706 	return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1707 }
1708 
1709 static __noinline int
1710 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1711 {
1712 	struct namecache *ncp;
1713 	struct mtx *blp;
1714 	struct mtx *dvlp, *dvlp2;
1715 	uint32_t hash;
1716 	int error;
1717 
1718 	if (cnp->cn_namelen == 2 &&
1719 	    cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1720 		dvlp = VP2VNODELOCK(dvp);
1721 		dvlp2 = NULL;
1722 		mtx_lock(dvlp);
1723 retry_dotdot:
1724 		ncp = dvp->v_cache_dd;
1725 		if (ncp == NULL) {
1726 			mtx_unlock(dvlp);
1727 			if (dvlp2 != NULL)
1728 				mtx_unlock(dvlp2);
1729 			SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1730 			return (0);
1731 		}
1732 		if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1733 			if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1734 				goto retry_dotdot;
1735 			MPASS(dvp->v_cache_dd == NULL);
1736 			mtx_unlock(dvlp);
1737 			if (dvlp2 != NULL)
1738 				mtx_unlock(dvlp2);
1739 			cache_free(ncp);
1740 		} else {
1741 			atomic_store_ptr(&dvp->v_cache_dd, NULL);
1742 			mtx_unlock(dvlp);
1743 			if (dvlp2 != NULL)
1744 				mtx_unlock(dvlp2);
1745 		}
1746 		SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1747 		return (1);
1748 	}
1749 
1750 	/*
1751 	 * XXX note that access here is completely unlocked with no provisions
1752 	 * to keep the hash allocated. If one is sufficiently unlucky a
1753 	 * parallel cache resize can reallocate the hash, unmap backing pages
1754 	 * and cause the empty check below to fault.
1755 	 *
1756 	 * Fixing this has epsilon priority, but can be done with no overhead
1757 	 * for this codepath with sufficient effort.
1758 	 */
1759 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1760 	blp = HASH2BUCKETLOCK(hash);
1761 retry:
1762 	if (CK_SLIST_EMPTY(NCHHASH(hash)))
1763 		goto out_no_entry;
1764 
1765 	mtx_lock(blp);
1766 
1767 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1768 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1769 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1770 			break;
1771 	}
1772 
1773 	if (ncp == NULL) {
1774 		mtx_unlock(blp);
1775 		goto out_no_entry;
1776 	}
1777 
1778 	error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1779 	if (__predict_false(error != 0)) {
1780 		atomic_add_long(&zap_bucket_fail, 1);
1781 		goto retry;
1782 	}
1783 	counter_u64_add(numposzaps, 1);
1784 	SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1785 	cache_free(ncp);
1786 	return (1);
1787 out_no_entry:
1788 	counter_u64_add(nummisszap, 1);
1789 	SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1790 	return (0);
1791 }
1792 
1793 static int __noinline
1794 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1795     struct timespec *tsp, int *ticksp)
1796 {
1797 	int ltype;
1798 
1799 	*vpp = dvp;
1800 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1801 	if (tsp != NULL)
1802 		timespecclear(tsp);
1803 	if (ticksp != NULL)
1804 		*ticksp = ticks;
1805 	vrefact(*vpp);
1806 	/*
1807 	 * When we lookup "." we still can be asked to lock it
1808 	 * differently...
1809 	 */
1810 	ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1811 	if (ltype != VOP_ISLOCKED(*vpp)) {
1812 		if (ltype == LK_EXCLUSIVE) {
1813 			vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1814 			if (VN_IS_DOOMED((*vpp))) {
1815 				/* forced unmount */
1816 				vrele(*vpp);
1817 				*vpp = NULL;
1818 				return (ENOENT);
1819 			}
1820 		} else
1821 			vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1822 	}
1823 	return (-1);
1824 }
1825 
1826 static int __noinline
1827 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1828     struct timespec *tsp, int *ticksp)
1829 {
1830 	struct namecache_ts *ncp_ts;
1831 	struct namecache *ncp;
1832 	struct mtx *dvlp;
1833 	enum vgetstate vs;
1834 	int error, ltype;
1835 	bool whiteout;
1836 
1837 	MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1838 
1839 	if ((cnp->cn_flags & MAKEENTRY) == 0) {
1840 		cache_remove_cnp(dvp, cnp);
1841 		return (0);
1842 	}
1843 
1844 retry:
1845 	dvlp = VP2VNODELOCK(dvp);
1846 	mtx_lock(dvlp);
1847 	ncp = dvp->v_cache_dd;
1848 	if (ncp == NULL) {
1849 		SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1850 		mtx_unlock(dvlp);
1851 		return (0);
1852 	}
1853 	if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1854 		if (ncp->nc_flag & NCF_NEGATIVE)
1855 			*vpp = NULL;
1856 		else
1857 			*vpp = ncp->nc_vp;
1858 	} else
1859 		*vpp = ncp->nc_dvp;
1860 	if (*vpp == NULL)
1861 		goto negative_success;
1862 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1863 	cache_out_ts(ncp, tsp, ticksp);
1864 	if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1865 	    NCF_DTS && tsp != NULL) {
1866 		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1867 		*tsp = ncp_ts->nc_dotdottime;
1868 	}
1869 
1870 	MPASS(dvp != *vpp);
1871 	ltype = VOP_ISLOCKED(dvp);
1872 	VOP_UNLOCK(dvp);
1873 	vs = vget_prep(*vpp);
1874 	mtx_unlock(dvlp);
1875 	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1876 	vn_lock(dvp, ltype | LK_RETRY);
1877 	if (VN_IS_DOOMED(dvp)) {
1878 		if (error == 0)
1879 			vput(*vpp);
1880 		*vpp = NULL;
1881 		return (ENOENT);
1882 	}
1883 	if (error) {
1884 		*vpp = NULL;
1885 		goto retry;
1886 	}
1887 	return (-1);
1888 negative_success:
1889 	if (__predict_false(cnp->cn_nameiop == CREATE)) {
1890 		if (cnp->cn_flags & ISLASTCN) {
1891 			counter_u64_add(numnegzaps, 1);
1892 			cache_zap_negative_locked_vnode_kl(ncp, dvp);
1893 			mtx_unlock(dvlp);
1894 			cache_free(ncp);
1895 			return (0);
1896 		}
1897 	}
1898 
1899 	whiteout = (ncp->nc_flag & NCF_WHITE);
1900 	cache_out_ts(ncp, tsp, ticksp);
1901 	if (cache_neg_hit_prep(ncp))
1902 		cache_neg_promote(ncp);
1903 	else
1904 		cache_neg_hit_finish(ncp);
1905 	mtx_unlock(dvlp);
1906 	if (whiteout)
1907 		cnp->cn_flags |= ISWHITEOUT;
1908 	return (ENOENT);
1909 }
1910 
1911 /**
1912  * Lookup a name in the name cache
1913  *
1914  * # Arguments
1915  *
1916  * - dvp:	Parent directory in which to search.
1917  * - vpp:	Return argument.  Will contain desired vnode on cache hit.
1918  * - cnp:	Parameters of the name search.  The most interesting bits of
1919  *   		the cn_flags field have the following meanings:
1920  *   	- MAKEENTRY:	If clear, free an entry from the cache rather than look
1921  *   			it up.
1922  *   	- ISDOTDOT:	Must be set if and only if cn_nameptr == ".."
1923  * - tsp:	Return storage for cache timestamp.  On a successful (positive
1924  *   		or negative) lookup, tsp will be filled with any timespec that
1925  *   		was stored when this cache entry was created.  However, it will
1926  *   		be clear for "." entries.
1927  * - ticks:	Return storage for alternate cache timestamp.  On a successful
1928  *   		(positive or negative) lookup, it will contain the ticks value
1929  *   		that was current when the cache entry was created, unless cnp
1930  *   		was ".".
1931  *
1932  * Either both tsp and ticks have to be provided or neither of them.
1933  *
1934  * # Returns
1935  *
1936  * - -1:	A positive cache hit.  vpp will contain the desired vnode.
1937  * - ENOENT:	A negative cache hit, or dvp was recycled out from under us due
1938  *		to a forced unmount.  vpp will not be modified.  If the entry
1939  *		is a whiteout, then the ISWHITEOUT flag will be set in
1940  *		cnp->cn_flags.
1941  * - 0:		A cache miss.  vpp will not be modified.
1942  *
1943  * # Locking
1944  *
1945  * On a cache hit, vpp will be returned locked and ref'd.  If we're looking up
1946  * .., dvp is unlocked.  If we're looking up . an extra ref is taken, but the
1947  * lock is not recursively acquired.
1948  */
1949 static int __noinline
1950 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1951     struct timespec *tsp, int *ticksp)
1952 {
1953 	struct namecache *ncp;
1954 	struct mtx *blp;
1955 	uint32_t hash;
1956 	enum vgetstate vs;
1957 	int error;
1958 	bool whiteout;
1959 
1960 	MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1961 	MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1962 
1963 retry:
1964 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1965 	blp = HASH2BUCKETLOCK(hash);
1966 	mtx_lock(blp);
1967 
1968 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1969 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1970 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1971 			break;
1972 	}
1973 
1974 	if (__predict_false(ncp == NULL)) {
1975 		mtx_unlock(blp);
1976 		SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
1977 		counter_u64_add(nummiss, 1);
1978 		return (0);
1979 	}
1980 
1981 	if (ncp->nc_flag & NCF_NEGATIVE)
1982 		goto negative_success;
1983 
1984 	counter_u64_add(numposhits, 1);
1985 	*vpp = ncp->nc_vp;
1986 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1987 	cache_out_ts(ncp, tsp, ticksp);
1988 	MPASS(dvp != *vpp);
1989 	vs = vget_prep(*vpp);
1990 	mtx_unlock(blp);
1991 	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1992 	if (error) {
1993 		*vpp = NULL;
1994 		goto retry;
1995 	}
1996 	return (-1);
1997 negative_success:
1998 	/*
1999 	 * We don't get here with regular lookup apart from corner cases.
2000 	 */
2001 	if (__predict_true(cnp->cn_nameiop == CREATE)) {
2002 		if (cnp->cn_flags & ISLASTCN) {
2003 			counter_u64_add(numnegzaps, 1);
2004 			error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2005 			if (__predict_false(error != 0)) {
2006 				atomic_add_long(&zap_bucket_fail2, 1);
2007 				goto retry;
2008 			}
2009 			cache_free(ncp);
2010 			return (0);
2011 		}
2012 	}
2013 
2014 	whiteout = (ncp->nc_flag & NCF_WHITE);
2015 	cache_out_ts(ncp, tsp, ticksp);
2016 	if (cache_neg_hit_prep(ncp))
2017 		cache_neg_promote(ncp);
2018 	else
2019 		cache_neg_hit_finish(ncp);
2020 	mtx_unlock(blp);
2021 	if (whiteout)
2022 		cnp->cn_flags |= ISWHITEOUT;
2023 	return (ENOENT);
2024 }
2025 
2026 int
2027 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2028     struct timespec *tsp, int *ticksp)
2029 {
2030 	struct namecache *ncp;
2031 	uint32_t hash;
2032 	enum vgetstate vs;
2033 	int error;
2034 	bool whiteout, neg_promote;
2035 	u_short nc_flag;
2036 
2037 	MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2038 
2039 #ifdef DEBUG_CACHE
2040 	if (__predict_false(!doingcache)) {
2041 		cnp->cn_flags &= ~MAKEENTRY;
2042 		return (0);
2043 	}
2044 #endif
2045 
2046 	if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2047 		if (cnp->cn_namelen == 1)
2048 			return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2049 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2050 			return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2051 	}
2052 
2053 	MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2054 
2055 	if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2056 		cache_remove_cnp(dvp, cnp);
2057 		return (0);
2058 	}
2059 
2060 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2061 	vfs_smr_enter();
2062 
2063 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2064 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2065 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2066 			break;
2067 	}
2068 
2069 	if (__predict_false(ncp == NULL)) {
2070 		vfs_smr_exit();
2071 		SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2072 		counter_u64_add(nummiss, 1);
2073 		return (0);
2074 	}
2075 
2076 	nc_flag = atomic_load_char(&ncp->nc_flag);
2077 	if (nc_flag & NCF_NEGATIVE)
2078 		goto negative_success;
2079 
2080 	counter_u64_add(numposhits, 1);
2081 	*vpp = ncp->nc_vp;
2082 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2083 	cache_out_ts(ncp, tsp, ticksp);
2084 	MPASS(dvp != *vpp);
2085 	if (!cache_ncp_canuse(ncp)) {
2086 		vfs_smr_exit();
2087 		*vpp = NULL;
2088 		goto out_fallback;
2089 	}
2090 	vs = vget_prep_smr(*vpp);
2091 	vfs_smr_exit();
2092 	if (__predict_false(vs == VGET_NONE)) {
2093 		*vpp = NULL;
2094 		goto out_fallback;
2095 	}
2096 	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2097 	if (error) {
2098 		*vpp = NULL;
2099 		goto out_fallback;
2100 	}
2101 	return (-1);
2102 negative_success:
2103 	if (cnp->cn_nameiop == CREATE) {
2104 		if (cnp->cn_flags & ISLASTCN) {
2105 			vfs_smr_exit();
2106 			goto out_fallback;
2107 		}
2108 	}
2109 
2110 	cache_out_ts(ncp, tsp, ticksp);
2111 	whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2112 	neg_promote = cache_neg_hit_prep(ncp);
2113 	if (!cache_ncp_canuse(ncp)) {
2114 		cache_neg_hit_abort(ncp);
2115 		vfs_smr_exit();
2116 		goto out_fallback;
2117 	}
2118 	if (neg_promote) {
2119 		vfs_smr_exit();
2120 		if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2121 			goto out_fallback;
2122 	} else {
2123 		cache_neg_hit_finish(ncp);
2124 		vfs_smr_exit();
2125 	}
2126 	if (whiteout)
2127 		cnp->cn_flags |= ISWHITEOUT;
2128 	return (ENOENT);
2129 out_fallback:
2130 	return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2131 }
2132 
2133 struct celockstate {
2134 	struct mtx *vlp[3];
2135 	struct mtx *blp[2];
2136 };
2137 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2138 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2139 
2140 static inline void
2141 cache_celockstate_init(struct celockstate *cel)
2142 {
2143 
2144 	bzero(cel, sizeof(*cel));
2145 }
2146 
2147 static void
2148 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2149     struct vnode *dvp)
2150 {
2151 	struct mtx *vlp1, *vlp2;
2152 
2153 	MPASS(cel->vlp[0] == NULL);
2154 	MPASS(cel->vlp[1] == NULL);
2155 	MPASS(cel->vlp[2] == NULL);
2156 
2157 	MPASS(vp != NULL || dvp != NULL);
2158 
2159 	vlp1 = VP2VNODELOCK(vp);
2160 	vlp2 = VP2VNODELOCK(dvp);
2161 	cache_sort_vnodes(&vlp1, &vlp2);
2162 
2163 	if (vlp1 != NULL) {
2164 		mtx_lock(vlp1);
2165 		cel->vlp[0] = vlp1;
2166 	}
2167 	mtx_lock(vlp2);
2168 	cel->vlp[1] = vlp2;
2169 }
2170 
2171 static void
2172 cache_unlock_vnodes_cel(struct celockstate *cel)
2173 {
2174 
2175 	MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2176 
2177 	if (cel->vlp[0] != NULL)
2178 		mtx_unlock(cel->vlp[0]);
2179 	if (cel->vlp[1] != NULL)
2180 		mtx_unlock(cel->vlp[1]);
2181 	if (cel->vlp[2] != NULL)
2182 		mtx_unlock(cel->vlp[2]);
2183 }
2184 
2185 static bool
2186 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2187 {
2188 	struct mtx *vlp;
2189 	bool ret;
2190 
2191 	cache_assert_vlp_locked(cel->vlp[0]);
2192 	cache_assert_vlp_locked(cel->vlp[1]);
2193 	MPASS(cel->vlp[2] == NULL);
2194 
2195 	MPASS(vp != NULL);
2196 	vlp = VP2VNODELOCK(vp);
2197 
2198 	ret = true;
2199 	if (vlp >= cel->vlp[1]) {
2200 		mtx_lock(vlp);
2201 	} else {
2202 		if (mtx_trylock(vlp))
2203 			goto out;
2204 		cache_unlock_vnodes_cel(cel);
2205 		atomic_add_long(&cache_lock_vnodes_cel_3_failures, 1);
2206 		if (vlp < cel->vlp[0]) {
2207 			mtx_lock(vlp);
2208 			mtx_lock(cel->vlp[0]);
2209 			mtx_lock(cel->vlp[1]);
2210 		} else {
2211 			if (cel->vlp[0] != NULL)
2212 				mtx_lock(cel->vlp[0]);
2213 			mtx_lock(vlp);
2214 			mtx_lock(cel->vlp[1]);
2215 		}
2216 		ret = false;
2217 	}
2218 out:
2219 	cel->vlp[2] = vlp;
2220 	return (ret);
2221 }
2222 
2223 static void
2224 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2225     struct mtx *blp2)
2226 {
2227 
2228 	MPASS(cel->blp[0] == NULL);
2229 	MPASS(cel->blp[1] == NULL);
2230 
2231 	cache_sort_vnodes(&blp1, &blp2);
2232 
2233 	if (blp1 != NULL) {
2234 		mtx_lock(blp1);
2235 		cel->blp[0] = blp1;
2236 	}
2237 	mtx_lock(blp2);
2238 	cel->blp[1] = blp2;
2239 }
2240 
2241 static void
2242 cache_unlock_buckets_cel(struct celockstate *cel)
2243 {
2244 
2245 	if (cel->blp[0] != NULL)
2246 		mtx_unlock(cel->blp[0]);
2247 	mtx_unlock(cel->blp[1]);
2248 }
2249 
2250 /*
2251  * Lock part of the cache affected by the insertion.
2252  *
2253  * This means vnodelocks for dvp, vp and the relevant bucketlock.
2254  * However, insertion can result in removal of an old entry. In this
2255  * case we have an additional vnode and bucketlock pair to lock.
2256  *
2257  * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2258  * preserving the locking order (smaller address first).
2259  */
2260 static void
2261 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2262     uint32_t hash)
2263 {
2264 	struct namecache *ncp;
2265 	struct mtx *blps[2];
2266 	u_char nc_flag;
2267 
2268 	blps[0] = HASH2BUCKETLOCK(hash);
2269 	for (;;) {
2270 		blps[1] = NULL;
2271 		cache_lock_vnodes_cel(cel, dvp, vp);
2272 		if (vp == NULL || vp->v_type != VDIR)
2273 			break;
2274 		ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2275 		if (ncp == NULL)
2276 			break;
2277 		nc_flag = atomic_load_char(&ncp->nc_flag);
2278 		if ((nc_flag & NCF_ISDOTDOT) == 0)
2279 			break;
2280 		MPASS(ncp->nc_dvp == vp);
2281 		blps[1] = NCP2BUCKETLOCK(ncp);
2282 		if ((nc_flag & NCF_NEGATIVE) != 0)
2283 			break;
2284 		if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2285 			break;
2286 		/*
2287 		 * All vnodes got re-locked. Re-validate the state and if
2288 		 * nothing changed we are done. Otherwise restart.
2289 		 */
2290 		if (ncp == vp->v_cache_dd &&
2291 		    (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2292 		    blps[1] == NCP2BUCKETLOCK(ncp) &&
2293 		    VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2294 			break;
2295 		cache_unlock_vnodes_cel(cel);
2296 		cel->vlp[0] = NULL;
2297 		cel->vlp[1] = NULL;
2298 		cel->vlp[2] = NULL;
2299 	}
2300 	cache_lock_buckets_cel(cel, blps[0], blps[1]);
2301 }
2302 
2303 static void
2304 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2305     uint32_t hash)
2306 {
2307 	struct namecache *ncp;
2308 	struct mtx *blps[2];
2309 	u_char nc_flag;
2310 
2311 	blps[0] = HASH2BUCKETLOCK(hash);
2312 	for (;;) {
2313 		blps[1] = NULL;
2314 		cache_lock_vnodes_cel(cel, dvp, vp);
2315 		ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2316 		if (ncp == NULL)
2317 			break;
2318 		nc_flag = atomic_load_char(&ncp->nc_flag);
2319 		if ((nc_flag & NCF_ISDOTDOT) == 0)
2320 			break;
2321 		MPASS(ncp->nc_dvp == dvp);
2322 		blps[1] = NCP2BUCKETLOCK(ncp);
2323 		if ((nc_flag & NCF_NEGATIVE) != 0)
2324 			break;
2325 		if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2326 			break;
2327 		if (ncp == dvp->v_cache_dd &&
2328 		    (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2329 		    blps[1] == NCP2BUCKETLOCK(ncp) &&
2330 		    VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2331 			break;
2332 		cache_unlock_vnodes_cel(cel);
2333 		cel->vlp[0] = NULL;
2334 		cel->vlp[1] = NULL;
2335 		cel->vlp[2] = NULL;
2336 	}
2337 	cache_lock_buckets_cel(cel, blps[0], blps[1]);
2338 }
2339 
2340 static void
2341 cache_enter_unlock(struct celockstate *cel)
2342 {
2343 
2344 	cache_unlock_buckets_cel(cel);
2345 	cache_unlock_vnodes_cel(cel);
2346 }
2347 
2348 static void __noinline
2349 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2350     struct componentname *cnp)
2351 {
2352 	struct celockstate cel;
2353 	struct namecache *ncp;
2354 	uint32_t hash;
2355 	int len;
2356 
2357 	if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2358 		return;
2359 	len = cnp->cn_namelen;
2360 	cache_celockstate_init(&cel);
2361 	hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2362 	cache_enter_lock_dd(&cel, dvp, vp, hash);
2363 	ncp = dvp->v_cache_dd;
2364 	if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2365 		KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2366 		cache_zap_locked(ncp);
2367 	} else {
2368 		ncp = NULL;
2369 	}
2370 	atomic_store_ptr(&dvp->v_cache_dd, NULL);
2371 	cache_enter_unlock(&cel);
2372 	if (ncp != NULL)
2373 		cache_free(ncp);
2374 }
2375 
2376 /*
2377  * Add an entry to the cache.
2378  */
2379 void
2380 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2381     struct timespec *tsp, struct timespec *dtsp)
2382 {
2383 	struct celockstate cel;
2384 	struct namecache *ncp, *n2, *ndd;
2385 	struct namecache_ts *ncp_ts;
2386 	struct nchashhead *ncpp;
2387 	uint32_t hash;
2388 	int flag;
2389 	int len;
2390 
2391 	KASSERT(cnp->cn_namelen <= NAME_MAX,
2392 	    ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2393 	    NAME_MAX));
2394 	VNPASS(!VN_IS_DOOMED(dvp), dvp);
2395 	VNPASS(dvp->v_type != VNON, dvp);
2396 	if (vp != NULL) {
2397 		VNPASS(!VN_IS_DOOMED(vp), vp);
2398 		VNPASS(vp->v_type != VNON, vp);
2399 	}
2400 	if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
2401 		KASSERT(dvp == vp,
2402 		    ("%s: different vnodes for dot entry (%p; %p)\n", __func__,
2403 		    dvp, vp));
2404 	} else {
2405 		KASSERT(dvp != vp,
2406 		    ("%s: same vnode for non-dot entry [%s] (%p)\n", __func__,
2407 		    cnp->cn_nameptr, dvp));
2408 	}
2409 
2410 #ifdef DEBUG_CACHE
2411 	if (__predict_false(!doingcache))
2412 		return;
2413 #endif
2414 
2415 	flag = 0;
2416 	if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2417 		if (cnp->cn_namelen == 1)
2418 			return;
2419 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2420 			cache_enter_dotdot_prep(dvp, vp, cnp);
2421 			flag = NCF_ISDOTDOT;
2422 		}
2423 	}
2424 
2425 	ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2426 	if (ncp == NULL)
2427 		return;
2428 
2429 	cache_celockstate_init(&cel);
2430 	ndd = NULL;
2431 	ncp_ts = NULL;
2432 
2433 	/*
2434 	 * Calculate the hash key and setup as much of the new
2435 	 * namecache entry as possible before acquiring the lock.
2436 	 */
2437 	ncp->nc_flag = flag | NCF_WIP;
2438 	ncp->nc_vp = vp;
2439 	if (vp == NULL)
2440 		cache_neg_init(ncp);
2441 	ncp->nc_dvp = dvp;
2442 	if (tsp != NULL) {
2443 		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2444 		ncp_ts->nc_time = *tsp;
2445 		ncp_ts->nc_ticks = ticks;
2446 		ncp_ts->nc_nc.nc_flag |= NCF_TS;
2447 		if (dtsp != NULL) {
2448 			ncp_ts->nc_dotdottime = *dtsp;
2449 			ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2450 		}
2451 	}
2452 	len = ncp->nc_nlen = cnp->cn_namelen;
2453 	hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2454 	memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2455 	ncp->nc_name[len] = '\0';
2456 	cache_enter_lock(&cel, dvp, vp, hash);
2457 
2458 	/*
2459 	 * See if this vnode or negative entry is already in the cache
2460 	 * with this name.  This can happen with concurrent lookups of
2461 	 * the same path name.
2462 	 */
2463 	ncpp = NCHHASH(hash);
2464 	CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2465 		if (n2->nc_dvp == dvp &&
2466 		    n2->nc_nlen == cnp->cn_namelen &&
2467 		    !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2468 			MPASS(cache_ncp_canuse(n2));
2469 			if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2470 				KASSERT(vp == NULL,
2471 				    ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2472 				    __func__, NULL, vp, cnp->cn_nameptr));
2473 			else
2474 				KASSERT(n2->nc_vp == vp,
2475 				    ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2476 				    __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2477 			/*
2478 			 * Entries are supposed to be immutable unless in the
2479 			 * process of getting destroyed. Accommodating for
2480 			 * changing timestamps is possible but not worth it.
2481 			 * This should be harmless in terms of correctness, in
2482 			 * the worst case resulting in an earlier expiration.
2483 			 * Alternatively, the found entry can be replaced
2484 			 * altogether.
2485 			 */
2486 			MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2487 #if 0
2488 			if (tsp != NULL) {
2489 				KASSERT((n2->nc_flag & NCF_TS) != 0,
2490 				    ("no NCF_TS"));
2491 				n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2492 				n2_ts->nc_time = ncp_ts->nc_time;
2493 				n2_ts->nc_ticks = ncp_ts->nc_ticks;
2494 				if (dtsp != NULL) {
2495 					n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2496 					n2_ts->nc_nc.nc_flag |= NCF_DTS;
2497 				}
2498 			}
2499 #endif
2500 			SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2501 			    vp);
2502 			goto out_unlock_free;
2503 		}
2504 	}
2505 
2506 	if (flag == NCF_ISDOTDOT) {
2507 		/*
2508 		 * See if we are trying to add .. entry, but some other lookup
2509 		 * has populated v_cache_dd pointer already.
2510 		 */
2511 		if (dvp->v_cache_dd != NULL)
2512 			goto out_unlock_free;
2513 		KASSERT(vp == NULL || vp->v_type == VDIR,
2514 		    ("wrong vnode type %p", vp));
2515 		atomic_thread_fence_rel();
2516 		atomic_store_ptr(&dvp->v_cache_dd, ncp);
2517 	}
2518 
2519 	if (vp != NULL) {
2520 		if (flag != NCF_ISDOTDOT) {
2521 			/*
2522 			 * For this case, the cache entry maps both the
2523 			 * directory name in it and the name ".." for the
2524 			 * directory's parent.
2525 			 */
2526 			if ((ndd = vp->v_cache_dd) != NULL) {
2527 				if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2528 					cache_zap_locked(ndd);
2529 				else
2530 					ndd = NULL;
2531 			}
2532 			atomic_thread_fence_rel();
2533 			atomic_store_ptr(&vp->v_cache_dd, ncp);
2534 		} else if (vp->v_type != VDIR) {
2535 			if (vp->v_cache_dd != NULL) {
2536 				atomic_store_ptr(&vp->v_cache_dd, NULL);
2537 			}
2538 		}
2539 	}
2540 
2541 	if (flag != NCF_ISDOTDOT) {
2542 		if (LIST_EMPTY(&dvp->v_cache_src)) {
2543 			cache_hold_vnode(dvp);
2544 		}
2545 		LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2546 	}
2547 
2548 	/*
2549 	 * If the entry is "negative", we place it into the
2550 	 * "negative" cache queue, otherwise, we place it into the
2551 	 * destination vnode's cache entries queue.
2552 	 */
2553 	if (vp != NULL) {
2554 		TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2555 		SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2556 		    vp);
2557 	} else {
2558 		if (cnp->cn_flags & ISWHITEOUT)
2559 			atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2560 		cache_neg_insert(ncp);
2561 		SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2562 		    ncp->nc_name);
2563 	}
2564 
2565 	/*
2566 	 * Insert the new namecache entry into the appropriate chain
2567 	 * within the cache entries table.
2568 	 */
2569 	CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2570 
2571 	atomic_thread_fence_rel();
2572 	/*
2573 	 * Mark the entry as fully constructed.
2574 	 * It is immutable past this point until its removal.
2575 	 */
2576 	atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2577 
2578 	cache_enter_unlock(&cel);
2579 	if (ndd != NULL)
2580 		cache_free(ndd);
2581 	return;
2582 out_unlock_free:
2583 	cache_enter_unlock(&cel);
2584 	cache_free(ncp);
2585 	return;
2586 }
2587 
2588 /*
2589  * A variant of the above accepting flags.
2590  *
2591  * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2592  *
2593  * TODO: this routine is a hack. It blindly removes the old entry, even if it
2594  * happens to match and it is doing it in an inefficient manner. It was added
2595  * to accommodate NFS which runs into a case where the target for a given name
2596  * may change from under it. Note this does nothing to solve the following
2597  * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2598  * the same [dvp, cnp]. It may be argued that code doing this is broken.
2599  */
2600 void
2601 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2602     struct timespec *tsp, struct timespec *dtsp, int flags)
2603 {
2604 
2605 	MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2606 
2607 	if (flags & VFS_CACHE_DROPOLD)
2608 		cache_remove_cnp(dvp, cnp);
2609 	cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2610 }
2611 
2612 static u_long
2613 cache_roundup_2(u_long val)
2614 {
2615 	u_long res;
2616 
2617 	for (res = 1; res <= val; res <<= 1)
2618 		continue;
2619 
2620 	return (res);
2621 }
2622 
2623 static struct nchashhead *
2624 nchinittbl(u_long elements, u_long *hashmask)
2625 {
2626 	struct nchashhead *hashtbl;
2627 	u_long hashsize, i;
2628 
2629 	hashsize = cache_roundup_2(elements) / 2;
2630 
2631 	hashtbl = malloc(hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2632 	for (i = 0; i < hashsize; i++)
2633 		CK_SLIST_INIT(&hashtbl[i]);
2634 	*hashmask = hashsize - 1;
2635 	return (hashtbl);
2636 }
2637 
2638 static void
2639 ncfreetbl(struct nchashhead *hashtbl)
2640 {
2641 
2642 	free(hashtbl, M_VFSCACHE);
2643 }
2644 
2645 /*
2646  * Name cache initialization, from vfs_init() when we are booting
2647  */
2648 static void
2649 nchinit(void *dummy __unused)
2650 {
2651 	u_int i;
2652 
2653 	cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2654 	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2655 	cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2656 	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2657 	cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2658 	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2659 	cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2660 	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2661 
2662 	VFS_SMR_ZONE_SET(cache_zone_small);
2663 	VFS_SMR_ZONE_SET(cache_zone_small_ts);
2664 	VFS_SMR_ZONE_SET(cache_zone_large);
2665 	VFS_SMR_ZONE_SET(cache_zone_large_ts);
2666 
2667 	ncsize = desiredvnodes * ncsizefactor;
2668 	cache_recalc_neg_min();
2669 	nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2670 	ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2671 	if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2672 		ncbuckethash = 7;
2673 	if (ncbuckethash > nchash)
2674 		ncbuckethash = nchash;
2675 	bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2676 	    M_WAITOK | M_ZERO);
2677 	for (i = 0; i < numbucketlocks; i++)
2678 		mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2679 	ncvnodehash = ncbuckethash;
2680 	vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2681 	    M_WAITOK | M_ZERO);
2682 	for (i = 0; i < numvnodelocks; i++)
2683 		mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2684 
2685 	for (i = 0; i < numneglists; i++) {
2686 		mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2687 		mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2688 		TAILQ_INIT(&neglists[i].nl_list);
2689 		TAILQ_INIT(&neglists[i].nl_hotlist);
2690 	}
2691 }
2692 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2693 
2694 void
2695 cache_vnode_init(struct vnode *vp)
2696 {
2697 
2698 	LIST_INIT(&vp->v_cache_src);
2699 	TAILQ_INIT(&vp->v_cache_dst);
2700 	vp->v_cache_dd = NULL;
2701 	cache_prehash(vp);
2702 }
2703 
2704 /*
2705  * Induce transient cache misses for lockless operation in cache_lookup() by
2706  * using a temporary hash table.
2707  *
2708  * This will force a fs lookup.
2709  *
2710  * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2711  * to observe all CPUs not performing the lookup.
2712  */
2713 static void
2714 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2715 {
2716 
2717 	MPASS(temphash < nchash);
2718 	/*
2719 	 * Change the size. The new size is smaller and can safely be used
2720 	 * against the existing table. All lookups which now hash wrong will
2721 	 * result in a cache miss, which all callers are supposed to know how
2722 	 * to handle.
2723 	 */
2724 	atomic_store_long(&nchash, temphash);
2725 	atomic_thread_fence_rel();
2726 	vfs_smr_synchronize();
2727 	/*
2728 	 * At this point everyone sees the updated hash value, but they still
2729 	 * see the old table.
2730 	 */
2731 	atomic_store_ptr(&nchashtbl, temptbl);
2732 	atomic_thread_fence_rel();
2733 	vfs_smr_synchronize();
2734 	/*
2735 	 * At this point everyone sees the updated table pointer and size pair.
2736 	 */
2737 }
2738 
2739 /*
2740  * Set the new hash table.
2741  *
2742  * Similarly to cache_changesize_set_temp(), this has to synchronize against
2743  * lockless operation in cache_lookup().
2744  */
2745 static void
2746 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2747 {
2748 
2749 	MPASS(nchash < new_hash);
2750 	/*
2751 	 * Change the pointer first. This wont result in out of bounds access
2752 	 * since the temporary table is guaranteed to be smaller.
2753 	 */
2754 	atomic_store_ptr(&nchashtbl, new_tbl);
2755 	atomic_thread_fence_rel();
2756 	vfs_smr_synchronize();
2757 	/*
2758 	 * At this point everyone sees the updated pointer value, but they
2759 	 * still see the old size.
2760 	 */
2761 	atomic_store_long(&nchash, new_hash);
2762 	atomic_thread_fence_rel();
2763 	vfs_smr_synchronize();
2764 	/*
2765 	 * At this point everyone sees the updated table pointer and size pair.
2766 	 */
2767 }
2768 
2769 void
2770 cache_changesize(u_long newmaxvnodes)
2771 {
2772 	struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2773 	u_long new_nchash, old_nchash, temphash;
2774 	struct namecache *ncp;
2775 	uint32_t hash;
2776 	u_long newncsize;
2777 	u_long i;
2778 
2779 	newncsize = newmaxvnodes * ncsizefactor;
2780 	newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2781 	if (newmaxvnodes < numbucketlocks)
2782 		newmaxvnodes = numbucketlocks;
2783 
2784 	new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2785 	/* If same hash table size, nothing to do */
2786 	if (nchash == new_nchash) {
2787 		ncfreetbl(new_nchashtbl);
2788 		return;
2789 	}
2790 
2791 	temptbl = nchinittbl(1, &temphash);
2792 
2793 	/*
2794 	 * Move everything from the old hash table to the new table.
2795 	 * None of the namecache entries in the table can be removed
2796 	 * because to do so, they have to be removed from the hash table.
2797 	 */
2798 	cache_lock_all_vnodes();
2799 	cache_lock_all_buckets();
2800 	old_nchashtbl = nchashtbl;
2801 	old_nchash = nchash;
2802 	cache_changesize_set_temp(temptbl, temphash);
2803 	for (i = 0; i <= old_nchash; i++) {
2804 		while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2805 			hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2806 			    ncp->nc_dvp);
2807 			CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2808 			CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2809 		}
2810 	}
2811 	ncsize = newncsize;
2812 	cache_recalc_neg_min();
2813 	cache_changesize_set_new(new_nchashtbl, new_nchash);
2814 	cache_unlock_all_buckets();
2815 	cache_unlock_all_vnodes();
2816 	ncfreetbl(old_nchashtbl);
2817 	ncfreetbl(temptbl);
2818 }
2819 
2820 /*
2821  * Remove all entries from and to a particular vnode.
2822  */
2823 static void
2824 cache_purge_impl(struct vnode *vp)
2825 {
2826 	struct cache_freebatch batch;
2827 	struct namecache *ncp;
2828 	struct mtx *vlp, *vlp2;
2829 
2830 	TAILQ_INIT(&batch);
2831 	vlp = VP2VNODELOCK(vp);
2832 	vlp2 = NULL;
2833 	mtx_lock(vlp);
2834 retry:
2835 	while (!LIST_EMPTY(&vp->v_cache_src)) {
2836 		ncp = LIST_FIRST(&vp->v_cache_src);
2837 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2838 			goto retry;
2839 		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2840 	}
2841 	while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2842 		ncp = TAILQ_FIRST(&vp->v_cache_dst);
2843 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2844 			goto retry;
2845 		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2846 	}
2847 	ncp = vp->v_cache_dd;
2848 	if (ncp != NULL) {
2849 		KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2850 		   ("lost dotdot link"));
2851 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2852 			goto retry;
2853 		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2854 	}
2855 	KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2856 	mtx_unlock(vlp);
2857 	if (vlp2 != NULL)
2858 		mtx_unlock(vlp2);
2859 	cache_free_batch(&batch);
2860 }
2861 
2862 /*
2863  * Opportunistic check to see if there is anything to do.
2864  */
2865 static bool
2866 cache_has_entries(struct vnode *vp)
2867 {
2868 
2869 	if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2870 	    atomic_load_ptr(&vp->v_cache_dd) == NULL)
2871 		return (false);
2872 	return (true);
2873 }
2874 
2875 void
2876 cache_purge(struct vnode *vp)
2877 {
2878 
2879 	SDT_PROBE1(vfs, namecache, purge, done, vp);
2880 	if (!cache_has_entries(vp))
2881 		return;
2882 	cache_purge_impl(vp);
2883 }
2884 
2885 /*
2886  * Only to be used by vgone.
2887  */
2888 void
2889 cache_purge_vgone(struct vnode *vp)
2890 {
2891 	struct mtx *vlp;
2892 
2893 	VNPASS(VN_IS_DOOMED(vp), vp);
2894 	if (cache_has_entries(vp)) {
2895 		cache_purge_impl(vp);
2896 		return;
2897 	}
2898 
2899 	/*
2900 	 * Serialize against a potential thread doing cache_purge.
2901 	 */
2902 	vlp = VP2VNODELOCK(vp);
2903 	mtx_wait_unlocked(vlp);
2904 	if (cache_has_entries(vp)) {
2905 		cache_purge_impl(vp);
2906 		return;
2907 	}
2908 	return;
2909 }
2910 
2911 /*
2912  * Remove all negative entries for a particular directory vnode.
2913  */
2914 void
2915 cache_purge_negative(struct vnode *vp)
2916 {
2917 	struct cache_freebatch batch;
2918 	struct namecache *ncp, *nnp;
2919 	struct mtx *vlp;
2920 
2921 	SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2922 	if (LIST_EMPTY(&vp->v_cache_src))
2923 		return;
2924 	TAILQ_INIT(&batch);
2925 	vlp = VP2VNODELOCK(vp);
2926 	mtx_lock(vlp);
2927 	LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2928 		if (!(ncp->nc_flag & NCF_NEGATIVE))
2929 			continue;
2930 		cache_zap_negative_locked_vnode_kl(ncp, vp);
2931 		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2932 	}
2933 	mtx_unlock(vlp);
2934 	cache_free_batch(&batch);
2935 }
2936 
2937 /*
2938  * Entry points for modifying VOP operations.
2939  */
2940 void
2941 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2942     struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2943 {
2944 
2945 	ASSERT_VOP_IN_SEQC(fdvp);
2946 	ASSERT_VOP_IN_SEQC(fvp);
2947 	ASSERT_VOP_IN_SEQC(tdvp);
2948 	if (tvp != NULL)
2949 		ASSERT_VOP_IN_SEQC(tvp);
2950 
2951 	cache_purge(fvp);
2952 	if (tvp != NULL) {
2953 		cache_purge(tvp);
2954 		KASSERT(!cache_remove_cnp(tdvp, tcnp),
2955 		    ("%s: lingering negative entry", __func__));
2956 	} else {
2957 		cache_remove_cnp(tdvp, tcnp);
2958 	}
2959 
2960 	/*
2961 	 * TODO
2962 	 *
2963 	 * Historically renaming was always purging all revelang entries,
2964 	 * but that's quite wasteful. In particular turns out that in many cases
2965 	 * the target file is immediately accessed after rename, inducing a cache
2966 	 * miss.
2967 	 *
2968 	 * Recode this to reduce relocking and reuse the existing entry (if any)
2969 	 * instead of just removing it above and allocating a new one here.
2970 	 */
2971 	cache_enter(tdvp, fvp, tcnp);
2972 }
2973 
2974 void
2975 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2976 {
2977 
2978 	ASSERT_VOP_IN_SEQC(dvp);
2979 	ASSERT_VOP_IN_SEQC(vp);
2980 	cache_purge(vp);
2981 }
2982 
2983 #ifdef INVARIANTS
2984 /*
2985  * Validate that if an entry exists it matches.
2986  */
2987 void
2988 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2989 {
2990 	struct namecache *ncp;
2991 	struct mtx *blp;
2992 	uint32_t hash;
2993 
2994 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2995 	if (CK_SLIST_EMPTY(NCHHASH(hash)))
2996 		return;
2997 	blp = HASH2BUCKETLOCK(hash);
2998 	mtx_lock(blp);
2999 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3000 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3001 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
3002 			if (ncp->nc_vp != vp)
3003 				panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
3004 				    __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3005 		}
3006 	}
3007 	mtx_unlock(blp);
3008 }
3009 
3010 void
3011 cache_assert_no_entries(struct vnode *vp)
3012 {
3013 
3014 	VNPASS(TAILQ_EMPTY(&vp->v_cache_dst), vp);
3015 	VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
3016 	VNPASS(vp->v_cache_dd == NULL, vp);
3017 }
3018 #endif
3019 
3020 /*
3021  * Flush all entries referencing a particular filesystem.
3022  */
3023 void
3024 cache_purgevfs(struct mount *mp)
3025 {
3026 	struct vnode *vp, *mvp;
3027 	size_t visited __sdt_used, purged __sdt_used;
3028 
3029 	visited = purged = 0;
3030 	/*
3031 	 * Somewhat wasteful iteration over all vnodes. Would be better to
3032 	 * support filtering and avoid the interlock to begin with.
3033 	 */
3034 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3035 		visited++;
3036 		if (!cache_has_entries(vp)) {
3037 			VI_UNLOCK(vp);
3038 			continue;
3039 		}
3040 		vholdl(vp);
3041 		VI_UNLOCK(vp);
3042 		cache_purge(vp);
3043 		purged++;
3044 		vdrop(vp);
3045 	}
3046 
3047 	SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3048 }
3049 
3050 /*
3051  * Perform canonical checks and cache lookup and pass on to filesystem
3052  * through the vop_cachedlookup only if needed.
3053  */
3054 
3055 int
3056 vfs_cache_lookup(struct vop_lookup_args *ap)
3057 {
3058 	struct vnode *dvp;
3059 	int error;
3060 	struct vnode **vpp = ap->a_vpp;
3061 	struct componentname *cnp = ap->a_cnp;
3062 	int flags = cnp->cn_flags;
3063 
3064 	*vpp = NULL;
3065 	dvp = ap->a_dvp;
3066 
3067 	if (dvp->v_type != VDIR)
3068 		return (ENOTDIR);
3069 
3070 	if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3071 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3072 		return (EROFS);
3073 
3074 	error = vn_dir_check_exec(dvp, cnp);
3075 	if (error != 0)
3076 		return (error);
3077 
3078 	error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3079 	if (error == 0)
3080 		return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3081 	if (error == -1)
3082 		return (0);
3083 	return (error);
3084 }
3085 
3086 /* Implementation of the getcwd syscall. */
3087 int
3088 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3089 {
3090 	char *buf, *retbuf;
3091 	size_t buflen;
3092 	int error;
3093 
3094 	buflen = uap->buflen;
3095 	if (__predict_false(buflen < 2))
3096 		return (EINVAL);
3097 	if (buflen > MAXPATHLEN)
3098 		buflen = MAXPATHLEN;
3099 
3100 	buf = uma_zalloc(namei_zone, M_WAITOK);
3101 	error = vn_getcwd(buf, &retbuf, &buflen);
3102 	if (error == 0)
3103 		error = copyout(retbuf, uap->buf, buflen);
3104 	uma_zfree(namei_zone, buf);
3105 	return (error);
3106 }
3107 
3108 int
3109 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3110 {
3111 	struct pwd *pwd;
3112 	int error;
3113 
3114 	vfs_smr_enter();
3115 	pwd = pwd_get_smr();
3116 	error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3117 	    buflen, 0);
3118 	VFS_SMR_ASSERT_NOT_ENTERED();
3119 	if (error < 0) {
3120 		pwd = pwd_hold(curthread);
3121 		error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3122 		    retbuf, buflen);
3123 		pwd_drop(pwd);
3124 	}
3125 
3126 #ifdef KTRACE
3127 	if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3128 		ktrnamei(*retbuf);
3129 #endif
3130 	return (error);
3131 }
3132 
3133 /*
3134  * Canonicalize a path by walking it forward and back.
3135  *
3136  * BUGS:
3137  * - Nothing guarantees the integrity of the entire chain. Consider the case
3138  *   where the path "foo/bar/baz/qux" is passed, but "bar" is moved out of
3139  *   "foo" into "quux" during the backwards walk. The result will be
3140  *   "quux/bar/baz/qux", which could not have been obtained by an incremental
3141  *   walk in userspace. Moreover, the path we return is inaccessible if the
3142  *   calling thread lacks permission to traverse "quux".
3143  */
3144 static int
3145 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3146     size_t size, int flags, enum uio_seg pathseg)
3147 {
3148 	struct nameidata nd;
3149 	char *retbuf, *freebuf;
3150 	int error;
3151 
3152 	if (flags != 0)
3153 		return (EINVAL);
3154 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | WANTPARENT | AUDITVNODE1,
3155 	    pathseg, path, fd, &cap_fstat_rights);
3156 	if ((error = namei(&nd)) != 0)
3157 		return (error);
3158 
3159 	if (nd.ni_vp->v_type == VREG && nd.ni_dvp->v_type != VDIR &&
3160 	    (nd.ni_vp->v_vflag & VV_ROOT) != 0) {
3161 		/*
3162 		 * This happens if vp is a file mount. The call to
3163 		 * vn_fullpath_hardlink can panic if path resolution can't be
3164 		 * handled without the directory.
3165 		 *
3166 		 * To resolve this, we find the vnode which was mounted on -
3167 		 * this should have a unique global path since we disallow
3168 		 * mounting on linked files.
3169 		 */
3170 		struct vnode *covered_vp;
3171 		error = vn_lock(nd.ni_vp, LK_SHARED);
3172 		if (error != 0)
3173 			goto out;
3174 		covered_vp = nd.ni_vp->v_mount->mnt_vnodecovered;
3175 		vref(covered_vp);
3176 		VOP_UNLOCK(nd.ni_vp);
3177 		error = vn_fullpath(covered_vp, &retbuf, &freebuf);
3178 		vrele(covered_vp);
3179 	} else {
3180 		error = vn_fullpath_hardlink(nd.ni_vp, nd.ni_dvp, nd.ni_cnd.cn_nameptr,
3181 		    nd.ni_cnd.cn_namelen, &retbuf, &freebuf, &size);
3182 	}
3183 	if (error == 0) {
3184 		error = copyout(retbuf, buf, size);
3185 		free(freebuf, M_TEMP);
3186 	}
3187 out:
3188 	vrele(nd.ni_vp);
3189 	vrele(nd.ni_dvp);
3190 	NDFREE_PNBUF(&nd);
3191 	return (error);
3192 }
3193 
3194 int
3195 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3196 {
3197 
3198 	return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3199 	    uap->flags, UIO_USERSPACE));
3200 }
3201 
3202 /*
3203  * Retrieve the full filesystem path that correspond to a vnode from the name
3204  * cache (if available)
3205  */
3206 int
3207 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3208 {
3209 	struct pwd *pwd;
3210 	char *buf;
3211 	size_t buflen;
3212 	int error;
3213 
3214 	if (__predict_false(vp == NULL))
3215 		return (EINVAL);
3216 
3217 	buflen = MAXPATHLEN;
3218 	buf = malloc(buflen, M_TEMP, M_WAITOK);
3219 	vfs_smr_enter();
3220 	pwd = pwd_get_smr();
3221 	error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3222 	VFS_SMR_ASSERT_NOT_ENTERED();
3223 	if (error < 0) {
3224 		pwd = pwd_hold(curthread);
3225 		error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3226 		pwd_drop(pwd);
3227 	}
3228 	if (error == 0)
3229 		*freebuf = buf;
3230 	else
3231 		free(buf, M_TEMP);
3232 	return (error);
3233 }
3234 
3235 /*
3236  * This function is similar to vn_fullpath, but it attempts to lookup the
3237  * pathname relative to the global root mount point.  This is required for the
3238  * auditing sub-system, as audited pathnames must be absolute, relative to the
3239  * global root mount point.
3240  */
3241 int
3242 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3243 {
3244 	char *buf;
3245 	size_t buflen;
3246 	int error;
3247 
3248 	if (__predict_false(vp == NULL))
3249 		return (EINVAL);
3250 	buflen = MAXPATHLEN;
3251 	buf = malloc(buflen, M_TEMP, M_WAITOK);
3252 	vfs_smr_enter();
3253 	error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3254 	VFS_SMR_ASSERT_NOT_ENTERED();
3255 	if (error < 0) {
3256 		error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3257 	}
3258 	if (error == 0)
3259 		*freebuf = buf;
3260 	else
3261 		free(buf, M_TEMP);
3262 	return (error);
3263 }
3264 
3265 static struct namecache *
3266 vn_dd_from_dst(struct vnode *vp)
3267 {
3268 	struct namecache *ncp;
3269 
3270 	cache_assert_vnode_locked(vp);
3271 	TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3272 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3273 			return (ncp);
3274 	}
3275 	return (NULL);
3276 }
3277 
3278 int
3279 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3280 {
3281 	struct vnode *dvp;
3282 	struct namecache *ncp;
3283 	struct mtx *vlp;
3284 	int error;
3285 
3286 	vlp = VP2VNODELOCK(*vp);
3287 	mtx_lock(vlp);
3288 	ncp = (*vp)->v_cache_dd;
3289 	if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3290 		KASSERT(ncp == vn_dd_from_dst(*vp),
3291 		    ("%s: mismatch for dd entry (%p != %p)", __func__,
3292 		    ncp, vn_dd_from_dst(*vp)));
3293 	} else {
3294 		ncp = vn_dd_from_dst(*vp);
3295 	}
3296 	if (ncp != NULL) {
3297 		if (*buflen < ncp->nc_nlen) {
3298 			mtx_unlock(vlp);
3299 			vrele(*vp);
3300 			counter_u64_add(numfullpathfail4, 1);
3301 			error = ENOMEM;
3302 			SDT_PROBE3(vfs, namecache, fullpath, return, error,
3303 			    vp, NULL);
3304 			return (error);
3305 		}
3306 		*buflen -= ncp->nc_nlen;
3307 		memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3308 		SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3309 		    ncp->nc_name, vp);
3310 		dvp = *vp;
3311 		*vp = ncp->nc_dvp;
3312 		vref(*vp);
3313 		mtx_unlock(vlp);
3314 		vrele(dvp);
3315 		return (0);
3316 	}
3317 	SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3318 
3319 	mtx_unlock(vlp);
3320 	vn_lock(*vp, LK_SHARED | LK_RETRY);
3321 	error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3322 	vput(*vp);
3323 	if (error) {
3324 		counter_u64_add(numfullpathfail2, 1);
3325 		SDT_PROBE3(vfs, namecache, fullpath, return,  error, vp, NULL);
3326 		return (error);
3327 	}
3328 
3329 	*vp = dvp;
3330 	if (VN_IS_DOOMED(dvp)) {
3331 		/* forced unmount */
3332 		vrele(dvp);
3333 		error = ENOENT;
3334 		SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3335 		return (error);
3336 	}
3337 	/*
3338 	 * *vp has its use count incremented still.
3339 	 */
3340 
3341 	return (0);
3342 }
3343 
3344 /*
3345  * Resolve a directory to a pathname.
3346  *
3347  * The name of the directory can always be found in the namecache or fetched
3348  * from the filesystem. There is also guaranteed to be only one parent, meaning
3349  * we can just follow vnodes up until we find the root.
3350  *
3351  * The vnode must be referenced.
3352  */
3353 static int
3354 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3355     size_t *len, size_t addend)
3356 {
3357 #ifdef KDTRACE_HOOKS
3358 	struct vnode *startvp = vp;
3359 #endif
3360 	struct vnode *vp1;
3361 	size_t buflen;
3362 	int error;
3363 	bool slash_prefixed;
3364 
3365 	VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3366 	VNPASS(vp->v_usecount > 0, vp);
3367 
3368 	buflen = *len;
3369 
3370 	slash_prefixed = true;
3371 	if (addend == 0) {
3372 		MPASS(*len >= 2);
3373 		buflen--;
3374 		buf[buflen] = '\0';
3375 		slash_prefixed = false;
3376 	}
3377 
3378 	error = 0;
3379 
3380 	SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3381 	counter_u64_add(numfullpathcalls, 1);
3382 	while (vp != rdir && vp != rootvnode) {
3383 		/*
3384 		 * The vp vnode must be already fully constructed,
3385 		 * since it is either found in namecache or obtained
3386 		 * from VOP_VPTOCNP().  We may test for VV_ROOT safely
3387 		 * without obtaining the vnode lock.
3388 		 */
3389 		if ((vp->v_vflag & VV_ROOT) != 0) {
3390 			vn_lock(vp, LK_RETRY | LK_SHARED);
3391 
3392 			/*
3393 			 * With the vnode locked, check for races with
3394 			 * unmount, forced or not.  Note that we
3395 			 * already verified that vp is not equal to
3396 			 * the root vnode, which means that
3397 			 * mnt_vnodecovered can be NULL only for the
3398 			 * case of unmount.
3399 			 */
3400 			if (VN_IS_DOOMED(vp) ||
3401 			    (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3402 			    vp1->v_mountedhere != vp->v_mount) {
3403 				vput(vp);
3404 				error = ENOENT;
3405 				SDT_PROBE3(vfs, namecache, fullpath, return,
3406 				    error, vp, NULL);
3407 				break;
3408 			}
3409 
3410 			vref(vp1);
3411 			vput(vp);
3412 			vp = vp1;
3413 			continue;
3414 		}
3415 		VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3416 		error = vn_vptocnp(&vp, buf, &buflen);
3417 		if (error)
3418 			break;
3419 		if (buflen == 0) {
3420 			vrele(vp);
3421 			error = ENOMEM;
3422 			SDT_PROBE3(vfs, namecache, fullpath, return, error,
3423 			    startvp, NULL);
3424 			break;
3425 		}
3426 		buf[--buflen] = '/';
3427 		slash_prefixed = true;
3428 	}
3429 	if (error)
3430 		return (error);
3431 	if (!slash_prefixed) {
3432 		if (buflen == 0) {
3433 			vrele(vp);
3434 			counter_u64_add(numfullpathfail4, 1);
3435 			SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3436 			    startvp, NULL);
3437 			return (ENOMEM);
3438 		}
3439 		buf[--buflen] = '/';
3440 	}
3441 	counter_u64_add(numfullpathfound, 1);
3442 	vrele(vp);
3443 
3444 	*retbuf = buf + buflen;
3445 	SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3446 	*len -= buflen;
3447 	*len += addend;
3448 	return (0);
3449 }
3450 
3451 /*
3452  * Resolve an arbitrary vnode to a pathname.
3453  *
3454  * Note 2 caveats:
3455  * - hardlinks are not tracked, thus if the vnode is not a directory this can
3456  *   resolve to a different path than the one used to find it
3457  * - namecache is not mandatory, meaning names are not guaranteed to be added
3458  *   (in which case resolving fails)
3459  */
3460 static void __inline
3461 cache_rev_failed_impl(int *reason, int line)
3462 {
3463 
3464 	*reason = line;
3465 }
3466 #define cache_rev_failed(var)	cache_rev_failed_impl((var), __LINE__)
3467 
3468 static int
3469 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3470     char **retbuf, size_t *buflen, size_t addend)
3471 {
3472 #ifdef KDTRACE_HOOKS
3473 	struct vnode *startvp = vp;
3474 #endif
3475 	struct vnode *tvp;
3476 	struct mount *mp;
3477 	struct namecache *ncp;
3478 	size_t orig_buflen;
3479 	int reason;
3480 	int error;
3481 #ifdef KDTRACE_HOOKS
3482 	int i;
3483 #endif
3484 	seqc_t vp_seqc, tvp_seqc;
3485 	u_char nc_flag;
3486 
3487 	VFS_SMR_ASSERT_ENTERED();
3488 
3489 	if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3490 		vfs_smr_exit();
3491 		return (-1);
3492 	}
3493 
3494 	orig_buflen = *buflen;
3495 
3496 	if (addend == 0) {
3497 		MPASS(*buflen >= 2);
3498 		*buflen -= 1;
3499 		buf[*buflen] = '\0';
3500 	}
3501 
3502 	if (vp == rdir || vp == rootvnode) {
3503 		if (addend == 0) {
3504 			*buflen -= 1;
3505 			buf[*buflen] = '/';
3506 		}
3507 		goto out_ok;
3508 	}
3509 
3510 #ifdef KDTRACE_HOOKS
3511 	i = 0;
3512 #endif
3513 	error = -1;
3514 	ncp = NULL; /* for sdt probe down below */
3515 	vp_seqc = vn_seqc_read_any(vp);
3516 	if (seqc_in_modify(vp_seqc)) {
3517 		cache_rev_failed(&reason);
3518 		goto out_abort;
3519 	}
3520 
3521 	for (;;) {
3522 #ifdef KDTRACE_HOOKS
3523 		i++;
3524 #endif
3525 		if ((vp->v_vflag & VV_ROOT) != 0) {
3526 			mp = atomic_load_ptr(&vp->v_mount);
3527 			if (mp == NULL) {
3528 				cache_rev_failed(&reason);
3529 				goto out_abort;
3530 			}
3531 			tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3532 			tvp_seqc = vn_seqc_read_any(tvp);
3533 			if (seqc_in_modify(tvp_seqc)) {
3534 				cache_rev_failed(&reason);
3535 				goto out_abort;
3536 			}
3537 			if (!vn_seqc_consistent(vp, vp_seqc)) {
3538 				cache_rev_failed(&reason);
3539 				goto out_abort;
3540 			}
3541 			vp = tvp;
3542 			vp_seqc = tvp_seqc;
3543 			continue;
3544 		}
3545 		ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3546 		if (ncp == NULL) {
3547 			cache_rev_failed(&reason);
3548 			goto out_abort;
3549 		}
3550 		nc_flag = atomic_load_char(&ncp->nc_flag);
3551 		if ((nc_flag & NCF_ISDOTDOT) != 0) {
3552 			cache_rev_failed(&reason);
3553 			goto out_abort;
3554 		}
3555 		if (ncp->nc_nlen >= *buflen) {
3556 			cache_rev_failed(&reason);
3557 			error = ENOMEM;
3558 			goto out_abort;
3559 		}
3560 		*buflen -= ncp->nc_nlen;
3561 		memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3562 		*buflen -= 1;
3563 		buf[*buflen] = '/';
3564 		tvp = ncp->nc_dvp;
3565 		tvp_seqc = vn_seqc_read_any(tvp);
3566 		if (seqc_in_modify(tvp_seqc)) {
3567 			cache_rev_failed(&reason);
3568 			goto out_abort;
3569 		}
3570 		if (!vn_seqc_consistent(vp, vp_seqc)) {
3571 			cache_rev_failed(&reason);
3572 			goto out_abort;
3573 		}
3574 		/*
3575 		 * Acquire fence provided by vn_seqc_read_any above.
3576 		 */
3577 		if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3578 			cache_rev_failed(&reason);
3579 			goto out_abort;
3580 		}
3581 		if (!cache_ncp_canuse(ncp)) {
3582 			cache_rev_failed(&reason);
3583 			goto out_abort;
3584 		}
3585 		vp = tvp;
3586 		vp_seqc = tvp_seqc;
3587 		if (vp == rdir || vp == rootvnode)
3588 			break;
3589 	}
3590 out_ok:
3591 	vfs_smr_exit();
3592 	*retbuf = buf + *buflen;
3593 	*buflen = orig_buflen - *buflen + addend;
3594 	SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3595 	return (0);
3596 
3597 out_abort:
3598 	*buflen = orig_buflen;
3599 	SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3600 	vfs_smr_exit();
3601 	return (error);
3602 }
3603 
3604 static int
3605 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3606     size_t *buflen)
3607 {
3608 	size_t orig_buflen, addend;
3609 	int error;
3610 
3611 	if (*buflen < 2)
3612 		return (EINVAL);
3613 
3614 	orig_buflen = *buflen;
3615 
3616 	vref(vp);
3617 	addend = 0;
3618 	if (vp->v_type != VDIR) {
3619 		*buflen -= 1;
3620 		buf[*buflen] = '\0';
3621 		error = vn_vptocnp(&vp, buf, buflen);
3622 		if (error)
3623 			return (error);
3624 		if (*buflen == 0) {
3625 			vrele(vp);
3626 			return (ENOMEM);
3627 		}
3628 		*buflen -= 1;
3629 		buf[*buflen] = '/';
3630 		addend = orig_buflen - *buflen;
3631 	}
3632 
3633 	return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3634 }
3635 
3636 /*
3637  * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3638  *
3639  * Since the namecache does not track hardlinks, the caller is expected to
3640  * first look up the target vnode with WANTPARENT flag passed to namei to get
3641  * dvp and vp.
3642  *
3643  * Then we have 2 cases:
3644  * - if the found vnode is a directory, the path can be constructed just by
3645  *   following names up the chain
3646  * - otherwise we populate the buffer with the saved name and start resolving
3647  *   from the parent
3648  */
3649 int
3650 vn_fullpath_hardlink(struct vnode *vp, struct vnode *dvp,
3651     const char *hrdl_name, size_t hrdl_name_length,
3652     char **retbuf, char **freebuf, size_t *buflen)
3653 {
3654 	char *buf, *tmpbuf;
3655 	struct pwd *pwd;
3656 	size_t addend;
3657 	int error;
3658 	__enum_uint8(vtype) type;
3659 
3660 	if (*buflen < 2)
3661 		return (EINVAL);
3662 	if (*buflen > MAXPATHLEN)
3663 		*buflen = MAXPATHLEN;
3664 
3665 	buf = malloc(*buflen, M_TEMP, M_WAITOK);
3666 
3667 	addend = 0;
3668 
3669 	/*
3670 	 * Check for VBAD to work around the vp_crossmp bug in lookup().
3671 	 *
3672 	 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3673 	 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3674 	 * If the type is VDIR (like in this very case) we can skip looking
3675 	 * at ni_dvp in the first place. However, since vnodes get passed here
3676 	 * unlocked the target may transition to doomed state (type == VBAD)
3677 	 * before we get to evaluate the condition. If this happens, we will
3678 	 * populate part of the buffer and descend to vn_fullpath_dir with
3679 	 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3680 	 */
3681 	type = atomic_load_8(&vp->v_type);
3682 	if (type == VBAD) {
3683 		error = ENOENT;
3684 		goto out_bad;
3685 	}
3686 	if (type != VDIR) {
3687 		addend = hrdl_name_length + 2;
3688 		if (*buflen < addend) {
3689 			error = ENOMEM;
3690 			goto out_bad;
3691 		}
3692 		*buflen -= addend;
3693 		tmpbuf = buf + *buflen;
3694 		tmpbuf[0] = '/';
3695 		memcpy(&tmpbuf[1], hrdl_name, hrdl_name_length);
3696 		tmpbuf[addend - 1] = '\0';
3697 		vp = dvp;
3698 	}
3699 
3700 	vfs_smr_enter();
3701 	pwd = pwd_get_smr();
3702 	error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3703 	    addend);
3704 	VFS_SMR_ASSERT_NOT_ENTERED();
3705 	if (error < 0) {
3706 		pwd = pwd_hold(curthread);
3707 		vref(vp);
3708 		error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3709 		    addend);
3710 		pwd_drop(pwd);
3711 	}
3712 	if (error != 0)
3713 		goto out_bad;
3714 
3715 	*freebuf = buf;
3716 
3717 	return (0);
3718 out_bad:
3719 	free(buf, M_TEMP);
3720 	return (error);
3721 }
3722 
3723 struct vnode *
3724 vn_dir_dd_ino(struct vnode *vp)
3725 {
3726 	struct namecache *ncp;
3727 	struct vnode *ddvp;
3728 	struct mtx *vlp;
3729 	enum vgetstate vs;
3730 
3731 	ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3732 	vlp = VP2VNODELOCK(vp);
3733 	mtx_lock(vlp);
3734 	TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3735 		if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3736 			continue;
3737 		ddvp = ncp->nc_dvp;
3738 		vs = vget_prep(ddvp);
3739 		mtx_unlock(vlp);
3740 		if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3741 			return (NULL);
3742 		return (ddvp);
3743 	}
3744 	mtx_unlock(vlp);
3745 	return (NULL);
3746 }
3747 
3748 int
3749 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3750 {
3751 	struct namecache *ncp;
3752 	struct mtx *vlp;
3753 	int l;
3754 
3755 	vlp = VP2VNODELOCK(vp);
3756 	mtx_lock(vlp);
3757 	TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3758 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3759 			break;
3760 	if (ncp == NULL) {
3761 		mtx_unlock(vlp);
3762 		return (ENOENT);
3763 	}
3764 	l = min(ncp->nc_nlen, buflen - 1);
3765 	memcpy(buf, ncp->nc_name, l);
3766 	mtx_unlock(vlp);
3767 	buf[l] = '\0';
3768 	return (0);
3769 }
3770 
3771 /*
3772  * This function updates path string to vnode's full global path
3773  * and checks the size of the new path string against the pathlen argument.
3774  *
3775  * Requires a locked, referenced vnode.
3776  * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3777  *
3778  * If vp is a directory, the call to vn_fullpath_global() always succeeds
3779  * because it falls back to the ".." lookup if the namecache lookup fails.
3780  */
3781 int
3782 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3783     u_int pathlen)
3784 {
3785 	struct nameidata nd;
3786 	struct vnode *vp1;
3787 	char *rpath, *fbuf;
3788 	int error;
3789 
3790 	ASSERT_VOP_ELOCKED(vp, __func__);
3791 
3792 	/* Construct global filesystem path from vp. */
3793 	VOP_UNLOCK(vp);
3794 	error = vn_fullpath_global(vp, &rpath, &fbuf);
3795 
3796 	if (error != 0) {
3797 		vrele(vp);
3798 		return (error);
3799 	}
3800 
3801 	if (strlen(rpath) >= pathlen) {
3802 		vrele(vp);
3803 		error = ENAMETOOLONG;
3804 		goto out;
3805 	}
3806 
3807 	/*
3808 	 * Re-lookup the vnode by path to detect a possible rename.
3809 	 * As a side effect, the vnode is relocked.
3810 	 * If vnode was renamed, return ENOENT.
3811 	 */
3812 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3813 	error = namei(&nd);
3814 	if (error != 0) {
3815 		vrele(vp);
3816 		goto out;
3817 	}
3818 	NDFREE_PNBUF(&nd);
3819 	vp1 = nd.ni_vp;
3820 	vrele(vp);
3821 	if (vp1 == vp)
3822 		strcpy(path, rpath);
3823 	else {
3824 		vput(vp1);
3825 		error = ENOENT;
3826 	}
3827 
3828 out:
3829 	free(fbuf, M_TEMP);
3830 	return (error);
3831 }
3832 
3833 /*
3834  * This is similar to vn_path_to_global_path but allows for regular
3835  * files which may not be present in the cache.
3836  *
3837  * Requires a locked, referenced vnode.
3838  * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3839  */
3840 int
3841 vn_path_to_global_path_hardlink(struct thread *td, struct vnode *vp,
3842     struct vnode *dvp, char *path, u_int pathlen, const char *leaf_name,
3843     size_t leaf_length)
3844 {
3845 	struct nameidata nd;
3846 	struct vnode *vp1;
3847 	char *rpath, *fbuf;
3848 	size_t len;
3849 	int error;
3850 
3851 	ASSERT_VOP_ELOCKED(vp, __func__);
3852 
3853 	/*
3854 	 * Construct global filesystem path from dvp, vp and leaf
3855 	 * name.
3856 	 */
3857 	VOP_UNLOCK(vp);
3858 	len = pathlen;
3859 	error = vn_fullpath_hardlink(vp, dvp, leaf_name, leaf_length,
3860 	    &rpath, &fbuf, &len);
3861 
3862 	if (error != 0) {
3863 		vrele(vp);
3864 		return (error);
3865 	}
3866 
3867 	if (strlen(rpath) >= pathlen) {
3868 		vrele(vp);
3869 		error = ENAMETOOLONG;
3870 		goto out;
3871 	}
3872 
3873 	/*
3874 	 * Re-lookup the vnode by path to detect a possible rename.
3875 	 * As a side effect, the vnode is relocked.
3876 	 * If vnode was renamed, return ENOENT.
3877 	 */
3878 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path);
3879 	error = namei(&nd);
3880 	if (error != 0) {
3881 		vrele(vp);
3882 		goto out;
3883 	}
3884 	NDFREE_PNBUF(&nd);
3885 	vp1 = nd.ni_vp;
3886 	vrele(vp);
3887 	if (vp1 == vp)
3888 		strcpy(path, rpath);
3889 	else {
3890 		vput(vp1);
3891 		error = ENOENT;
3892 	}
3893 
3894 out:
3895 	free(fbuf, M_TEMP);
3896 	return (error);
3897 }
3898 
3899 #ifdef DDB
3900 static void
3901 db_print_vpath(struct vnode *vp)
3902 {
3903 
3904 	while (vp != NULL) {
3905 		db_printf("%p: ", vp);
3906 		if (vp == rootvnode) {
3907 			db_printf("/");
3908 			vp = NULL;
3909 		} else {
3910 			if (vp->v_vflag & VV_ROOT) {
3911 				db_printf("<mount point>");
3912 				vp = vp->v_mount->mnt_vnodecovered;
3913 			} else {
3914 				struct namecache *ncp;
3915 				char *ncn;
3916 				int i;
3917 
3918 				ncp = TAILQ_FIRST(&vp->v_cache_dst);
3919 				if (ncp != NULL) {
3920 					ncn = ncp->nc_name;
3921 					for (i = 0; i < ncp->nc_nlen; i++)
3922 						db_printf("%c", *ncn++);
3923 					vp = ncp->nc_dvp;
3924 				} else {
3925 					vp = NULL;
3926 				}
3927 			}
3928 		}
3929 		db_printf("\n");
3930 	}
3931 
3932 	return;
3933 }
3934 
3935 DB_SHOW_COMMAND(vpath, db_show_vpath)
3936 {
3937 	struct vnode *vp;
3938 
3939 	if (!have_addr) {
3940 		db_printf("usage: show vpath <struct vnode *>\n");
3941 		return;
3942 	}
3943 
3944 	vp = (struct vnode *)addr;
3945 	db_print_vpath(vp);
3946 }
3947 
3948 #endif
3949 
3950 static int cache_fast_lookup = 1;
3951 
3952 #define CACHE_FPL_FAILED	-2020
3953 
3954 static int
3955 cache_vop_bad_vexec(struct vop_fplookup_vexec_args *v)
3956 {
3957 	vn_printf(v->a_vp, "no proper vop_fplookup_vexec\n");
3958 	panic("no proper vop_fplookup_vexec");
3959 }
3960 
3961 static int
3962 cache_vop_bad_symlink(struct vop_fplookup_symlink_args *v)
3963 {
3964 	vn_printf(v->a_vp, "no proper vop_fplookup_symlink\n");
3965 	panic("no proper vop_fplookup_symlink");
3966 }
3967 
3968 void
3969 cache_vop_vector_register(struct vop_vector *v)
3970 {
3971 	size_t ops;
3972 
3973 	ops = 0;
3974 	if (v->vop_fplookup_vexec != NULL) {
3975 		ops++;
3976 	}
3977 	if (v->vop_fplookup_symlink != NULL) {
3978 		ops++;
3979 	}
3980 
3981 	if (ops == 2) {
3982 		return;
3983 	}
3984 
3985 	if (ops == 0) {
3986 		v->vop_fplookup_vexec = cache_vop_bad_vexec;
3987 		v->vop_fplookup_symlink = cache_vop_bad_symlink;
3988 		return;
3989 	}
3990 
3991 	printf("%s: invalid vop vector %p -- either all or none fplookup vops "
3992 	    "need to be provided",  __func__, v);
3993 	if (v->vop_fplookup_vexec == NULL) {
3994 		printf("%s: missing vop_fplookup_vexec\n", __func__);
3995 	}
3996 	if (v->vop_fplookup_symlink == NULL) {
3997 		printf("%s: missing vop_fplookup_symlink\n", __func__);
3998 	}
3999 	panic("bad vop vector %p", v);
4000 }
4001 
4002 #ifdef INVARIANTS
4003 void
4004 cache_validate_vop_vector(struct mount *mp, struct vop_vector *vops)
4005 {
4006 	if (mp == NULL)
4007 		return;
4008 
4009 	if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4010 		return;
4011 
4012 	if (vops->vop_fplookup_vexec == NULL ||
4013 	    vops->vop_fplookup_vexec == cache_vop_bad_vexec)
4014 		panic("bad vop_fplookup_vexec on vector %p for filesystem %s",
4015 		    vops, mp->mnt_vfc->vfc_name);
4016 
4017 	if (vops->vop_fplookup_symlink == NULL ||
4018 	    vops->vop_fplookup_symlink == cache_vop_bad_symlink)
4019 		panic("bad vop_fplookup_symlink on vector %p for filesystem %s",
4020 		    vops, mp->mnt_vfc->vfc_name);
4021 }
4022 #endif
4023 
4024 void
4025 cache_fast_lookup_enabled_recalc(void)
4026 {
4027 	int lookup_flag;
4028 	int mac_on;
4029 
4030 #ifdef MAC
4031 	mac_on = mac_vnode_check_lookup_enabled();
4032 	mac_on |= mac_vnode_check_readlink_enabled();
4033 #else
4034 	mac_on = 0;
4035 #endif
4036 
4037 	lookup_flag = atomic_load_int(&cache_fast_lookup);
4038 	if (lookup_flag && !mac_on) {
4039 		atomic_store_char(&cache_fast_lookup_enabled, true);
4040 	} else {
4041 		atomic_store_char(&cache_fast_lookup_enabled, false);
4042 	}
4043 }
4044 
4045 static int
4046 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
4047 {
4048 	int error, old;
4049 
4050 	old = atomic_load_int(&cache_fast_lookup);
4051 	error = sysctl_handle_int(oidp, arg1, arg2, req);
4052 	if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
4053 		cache_fast_lookup_enabled_recalc();
4054 	return (error);
4055 }
4056 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
4057     &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
4058 
4059 /*
4060  * Components of nameidata (or objects it can point to) which may
4061  * need restoring in case fast path lookup fails.
4062  */
4063 struct nameidata_outer {
4064 	size_t ni_pathlen;
4065 	int cn_flags;
4066 };
4067 
4068 struct nameidata_saved {
4069 #ifdef INVARIANTS
4070 	char *cn_nameptr;
4071 	size_t ni_pathlen;
4072 #endif
4073 };
4074 
4075 #ifdef INVARIANTS
4076 struct cache_fpl_debug {
4077 	size_t ni_pathlen;
4078 };
4079 #endif
4080 
4081 struct cache_fpl {
4082 	struct nameidata *ndp;
4083 	struct componentname *cnp;
4084 	char *nulchar;
4085 	struct vnode *dvp;
4086 	struct vnode *tvp;
4087 	seqc_t dvp_seqc;
4088 	seqc_t tvp_seqc;
4089 	uint32_t hash;
4090 	struct nameidata_saved snd;
4091 	struct nameidata_outer snd_outer;
4092 	int line;
4093 	enum cache_fpl_status status:8;
4094 	bool in_smr;
4095 	bool fsearch;
4096 	struct pwd **pwd;
4097 #ifdef INVARIANTS
4098 	struct cache_fpl_debug debug;
4099 #endif
4100 };
4101 
4102 static bool cache_fplookup_mp_supported(struct mount *mp);
4103 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
4104 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
4105 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
4106 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
4107 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
4108 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
4109 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
4110 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
4111 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
4112 
4113 static void
4114 cache_fpl_cleanup_cnp(struct componentname *cnp)
4115 {
4116 
4117 	uma_zfree(namei_zone, cnp->cn_pnbuf);
4118 	cnp->cn_pnbuf = NULL;
4119 	cnp->cn_nameptr = NULL;
4120 }
4121 
4122 static struct vnode *
4123 cache_fpl_handle_root(struct cache_fpl *fpl)
4124 {
4125 	struct nameidata *ndp;
4126 	struct componentname *cnp;
4127 
4128 	ndp = fpl->ndp;
4129 	cnp = fpl->cnp;
4130 
4131 	MPASS(*(cnp->cn_nameptr) == '/');
4132 	cnp->cn_nameptr++;
4133 	cache_fpl_pathlen_dec(fpl);
4134 
4135 	if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4136 		do {
4137 			cnp->cn_nameptr++;
4138 			cache_fpl_pathlen_dec(fpl);
4139 		} while (*(cnp->cn_nameptr) == '/');
4140 	}
4141 
4142 	return (ndp->ni_rootdir);
4143 }
4144 
4145 static void
4146 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
4147 {
4148 
4149 	fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
4150 	fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
4151 }
4152 
4153 static void
4154 cache_fpl_checkpoint(struct cache_fpl *fpl)
4155 {
4156 
4157 #ifdef INVARIANTS
4158 	fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
4159 	fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4160 #endif
4161 }
4162 
4163 static void
4164 cache_fpl_restore_partial(struct cache_fpl *fpl)
4165 {
4166 
4167 	fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4168 #ifdef INVARIANTS
4169 	fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4170 #endif
4171 }
4172 
4173 static void
4174 cache_fpl_restore_abort(struct cache_fpl *fpl)
4175 {
4176 
4177 	cache_fpl_restore_partial(fpl);
4178 	/*
4179 	 * It is 0 on entry by API contract.
4180 	 */
4181 	fpl->ndp->ni_resflags = 0;
4182 	fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4183 	fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4184 }
4185 
4186 #ifdef INVARIANTS
4187 #define cache_fpl_smr_assert_entered(fpl) ({			\
4188 	struct cache_fpl *_fpl = (fpl);				\
4189 	MPASS(_fpl->in_smr == true);				\
4190 	VFS_SMR_ASSERT_ENTERED();				\
4191 })
4192 #define cache_fpl_smr_assert_not_entered(fpl) ({		\
4193 	struct cache_fpl *_fpl = (fpl);				\
4194 	MPASS(_fpl->in_smr == false);				\
4195 	VFS_SMR_ASSERT_NOT_ENTERED();				\
4196 })
4197 static void
4198 cache_fpl_assert_status(struct cache_fpl *fpl)
4199 {
4200 
4201 	switch (fpl->status) {
4202 	case CACHE_FPL_STATUS_UNSET:
4203 		__assert_unreachable();
4204 		break;
4205 	case CACHE_FPL_STATUS_DESTROYED:
4206 	case CACHE_FPL_STATUS_ABORTED:
4207 	case CACHE_FPL_STATUS_PARTIAL:
4208 	case CACHE_FPL_STATUS_HANDLED:
4209 		break;
4210 	}
4211 }
4212 #else
4213 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4214 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4215 #define cache_fpl_assert_status(fpl) do { } while (0)
4216 #endif
4217 
4218 #define cache_fpl_smr_enter_initial(fpl) ({			\
4219 	struct cache_fpl *_fpl = (fpl);				\
4220 	vfs_smr_enter();					\
4221 	_fpl->in_smr = true;					\
4222 })
4223 
4224 #define cache_fpl_smr_enter(fpl) ({				\
4225 	struct cache_fpl *_fpl = (fpl);				\
4226 	MPASS(_fpl->in_smr == false);				\
4227 	vfs_smr_enter();					\
4228 	_fpl->in_smr = true;					\
4229 })
4230 
4231 #define cache_fpl_smr_exit(fpl) ({				\
4232 	struct cache_fpl *_fpl = (fpl);				\
4233 	MPASS(_fpl->in_smr == true);				\
4234 	vfs_smr_exit();						\
4235 	_fpl->in_smr = false;					\
4236 })
4237 
4238 static int
4239 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4240 {
4241 
4242 	if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4243 		KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4244 		    ("%s: converting to abort from %d at %d, set at %d\n",
4245 		    __func__, fpl->status, line, fpl->line));
4246 	}
4247 	cache_fpl_smr_assert_not_entered(fpl);
4248 	fpl->status = CACHE_FPL_STATUS_ABORTED;
4249 	fpl->line = line;
4250 	return (CACHE_FPL_FAILED);
4251 }
4252 
4253 #define cache_fpl_aborted_early(x)	cache_fpl_aborted_early_impl((x), __LINE__)
4254 
4255 static int __noinline
4256 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4257 {
4258 	struct nameidata *ndp;
4259 	struct componentname *cnp;
4260 
4261 	ndp = fpl->ndp;
4262 	cnp = fpl->cnp;
4263 
4264 	if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4265 		KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4266 		    ("%s: converting to abort from %d at %d, set at %d\n",
4267 		    __func__, fpl->status, line, fpl->line));
4268 	}
4269 	fpl->status = CACHE_FPL_STATUS_ABORTED;
4270 	fpl->line = line;
4271 	if (fpl->in_smr)
4272 		cache_fpl_smr_exit(fpl);
4273 	cache_fpl_restore_abort(fpl);
4274 	/*
4275 	 * Resolving symlinks overwrites data passed by the caller.
4276 	 * Let namei know.
4277 	 */
4278 	if (ndp->ni_loopcnt > 0) {
4279 		fpl->status = CACHE_FPL_STATUS_DESTROYED;
4280 		cache_fpl_cleanup_cnp(cnp);
4281 	}
4282 	return (CACHE_FPL_FAILED);
4283 }
4284 
4285 #define cache_fpl_aborted(x)	cache_fpl_aborted_impl((x), __LINE__)
4286 
4287 static int __noinline
4288 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4289 {
4290 
4291 	KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4292 	    ("%s: setting to partial at %d, but already set to %d at %d\n",
4293 	    __func__, line, fpl->status, fpl->line));
4294 	cache_fpl_smr_assert_entered(fpl);
4295 	fpl->status = CACHE_FPL_STATUS_PARTIAL;
4296 	fpl->line = line;
4297 	return (cache_fplookup_partial_setup(fpl));
4298 }
4299 
4300 #define cache_fpl_partial(x)	cache_fpl_partial_impl((x), __LINE__)
4301 
4302 static int
4303 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4304 {
4305 
4306 	KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4307 	    ("%s: setting to handled at %d, but already set to %d at %d\n",
4308 	    __func__, line, fpl->status, fpl->line));
4309 	cache_fpl_smr_assert_not_entered(fpl);
4310 	fpl->status = CACHE_FPL_STATUS_HANDLED;
4311 	fpl->line = line;
4312 	return (0);
4313 }
4314 
4315 #define cache_fpl_handled(x)	cache_fpl_handled_impl((x), __LINE__)
4316 
4317 static int
4318 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4319 {
4320 
4321 	KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4322 	    ("%s: setting to handled at %d, but already set to %d at %d\n",
4323 	    __func__, line, fpl->status, fpl->line));
4324 	MPASS(error != 0);
4325 	MPASS(error != CACHE_FPL_FAILED);
4326 	cache_fpl_smr_assert_not_entered(fpl);
4327 	fpl->status = CACHE_FPL_STATUS_HANDLED;
4328 	fpl->line = line;
4329 	fpl->dvp = NULL;
4330 	fpl->tvp = NULL;
4331 	return (error);
4332 }
4333 
4334 #define cache_fpl_handled_error(x, e)	cache_fpl_handled_error_impl((x), (e), __LINE__)
4335 
4336 static bool
4337 cache_fpl_terminated(struct cache_fpl *fpl)
4338 {
4339 
4340 	return (fpl->status != CACHE_FPL_STATUS_UNSET);
4341 }
4342 
4343 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4344 	(NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4345 	 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | ISRESTARTED | WILLBEDIR | \
4346 	 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | OPENREAD | \
4347 	 OPENWRITE | WANTIOCTLCAPS)
4348 
4349 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4350 	(ISDOTDOT | MAKEENTRY | ISLASTCN)
4351 
4352 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4353     "supported and internal flags overlap");
4354 
4355 static bool
4356 cache_fpl_islastcn(struct nameidata *ndp)
4357 {
4358 
4359 	return (*ndp->ni_next == 0);
4360 }
4361 
4362 static bool
4363 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4364 {
4365 
4366 	MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4367 	return (*(fpl->nulchar - 1) == '/');
4368 }
4369 
4370 static bool
4371 cache_fpl_isdotdot(struct componentname *cnp)
4372 {
4373 
4374 	if (cnp->cn_namelen == 2 &&
4375 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4376 		return (true);
4377 	return (false);
4378 }
4379 
4380 static bool
4381 cache_can_fplookup(struct cache_fpl *fpl)
4382 {
4383 	struct nameidata *ndp;
4384 	struct componentname *cnp;
4385 	struct thread *td;
4386 
4387 	ndp = fpl->ndp;
4388 	cnp = fpl->cnp;
4389 	td = curthread;
4390 
4391 	if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4392 		cache_fpl_aborted_early(fpl);
4393 		return (false);
4394 	}
4395 	if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4396 		cache_fpl_aborted_early(fpl);
4397 		return (false);
4398 	}
4399 	if (IN_CAPABILITY_MODE(td)) {
4400 		cache_fpl_aborted_early(fpl);
4401 		return (false);
4402 	}
4403 	if (AUDITING_TD(td)) {
4404 		cache_fpl_aborted_early(fpl);
4405 		return (false);
4406 	}
4407 	if (ndp->ni_startdir != NULL) {
4408 		cache_fpl_aborted_early(fpl);
4409 		return (false);
4410 	}
4411 	return (true);
4412 }
4413 
4414 static int __noinline
4415 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4416 {
4417 	struct nameidata *ndp;
4418 	struct componentname *cnp;
4419 	int error;
4420 	bool fsearch;
4421 
4422 	ndp = fpl->ndp;
4423 	cnp = fpl->cnp;
4424 
4425 	error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4426 	if (__predict_false(error != 0)) {
4427 		return (cache_fpl_aborted(fpl));
4428 	}
4429 	fpl->fsearch = fsearch;
4430 	if ((*vpp)->v_type != VDIR) {
4431 		if (!((cnp->cn_flags & EMPTYPATH) != 0 && cnp->cn_pnbuf[0] == '\0')) {
4432 			cache_fpl_smr_exit(fpl);
4433 			return (cache_fpl_handled_error(fpl, ENOTDIR));
4434 		}
4435 	}
4436 	return (0);
4437 }
4438 
4439 static int __noinline
4440 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4441     uint32_t hash)
4442 {
4443 	struct componentname *cnp;
4444 	struct vnode *dvp;
4445 
4446 	cnp = fpl->cnp;
4447 	dvp = fpl->dvp;
4448 
4449 	cache_fpl_smr_exit(fpl);
4450 	if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4451 		return (cache_fpl_handled_error(fpl, ENOENT));
4452 	else
4453 		return (cache_fpl_aborted(fpl));
4454 }
4455 
4456 /*
4457  * The target vnode is not supported, prepare for the slow path to take over.
4458  */
4459 static int __noinline
4460 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4461 {
4462 	struct nameidata *ndp;
4463 	struct componentname *cnp;
4464 	enum vgetstate dvs;
4465 	struct vnode *dvp;
4466 	struct pwd *pwd;
4467 	seqc_t dvp_seqc;
4468 
4469 	ndp = fpl->ndp;
4470 	cnp = fpl->cnp;
4471 	pwd = *(fpl->pwd);
4472 	dvp = fpl->dvp;
4473 	dvp_seqc = fpl->dvp_seqc;
4474 
4475 	if (!pwd_hold_smr(pwd)) {
4476 		return (cache_fpl_aborted(fpl));
4477 	}
4478 
4479 	/*
4480 	 * Note that seqc is checked before the vnode is locked, so by
4481 	 * the time regular lookup gets to it it may have moved.
4482 	 *
4483 	 * Ultimately this does not affect correctness, any lookup errors
4484 	 * are userspace racing with itself. It is guaranteed that any
4485 	 * path which ultimately gets found could also have been found
4486 	 * by regular lookup going all the way in absence of concurrent
4487 	 * modifications.
4488 	 */
4489 	dvs = vget_prep_smr(dvp);
4490 	cache_fpl_smr_exit(fpl);
4491 	if (__predict_false(dvs == VGET_NONE)) {
4492 		pwd_drop(pwd);
4493 		return (cache_fpl_aborted(fpl));
4494 	}
4495 
4496 	vget_finish_ref(dvp, dvs);
4497 	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4498 		vrele(dvp);
4499 		pwd_drop(pwd);
4500 		return (cache_fpl_aborted(fpl));
4501 	}
4502 
4503 	cache_fpl_restore_partial(fpl);
4504 #ifdef INVARIANTS
4505 	if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4506 		panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4507 		    cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4508 	}
4509 #endif
4510 
4511 	ndp->ni_startdir = dvp;
4512 	cnp->cn_flags |= MAKEENTRY;
4513 	if (cache_fpl_islastcn(ndp))
4514 		cnp->cn_flags |= ISLASTCN;
4515 	if (cache_fpl_isdotdot(cnp))
4516 		cnp->cn_flags |= ISDOTDOT;
4517 
4518 	/*
4519 	 * Skip potential extra slashes parsing did not take care of.
4520 	 * cache_fplookup_skip_slashes explains the mechanism.
4521 	 */
4522 	if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4523 		do {
4524 			cnp->cn_nameptr++;
4525 			cache_fpl_pathlen_dec(fpl);
4526 		} while (*(cnp->cn_nameptr) == '/');
4527 	}
4528 
4529 	ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4530 #ifdef INVARIANTS
4531 	if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4532 		panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4533 		    __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4534 		    cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4535 	}
4536 #endif
4537 	return (0);
4538 }
4539 
4540 static int
4541 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4542 {
4543 	struct componentname *cnp;
4544 	struct vnode *tvp;
4545 	seqc_t tvp_seqc;
4546 	int error, lkflags;
4547 
4548 	cnp = fpl->cnp;
4549 	tvp = fpl->tvp;
4550 	tvp_seqc = fpl->tvp_seqc;
4551 
4552 	if ((cnp->cn_flags & LOCKLEAF) != 0) {
4553 		lkflags = LK_SHARED;
4554 		if ((cnp->cn_flags & LOCKSHARED) == 0)
4555 			lkflags = LK_EXCLUSIVE;
4556 		error = vget_finish(tvp, lkflags, tvs);
4557 		if (__predict_false(error != 0)) {
4558 			return (cache_fpl_aborted(fpl));
4559 		}
4560 	} else {
4561 		vget_finish_ref(tvp, tvs);
4562 	}
4563 
4564 	if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4565 		if ((cnp->cn_flags & LOCKLEAF) != 0)
4566 			vput(tvp);
4567 		else
4568 			vrele(tvp);
4569 		return (cache_fpl_aborted(fpl));
4570 	}
4571 
4572 	return (cache_fpl_handled(fpl));
4573 }
4574 
4575 /*
4576  * They want to possibly modify the state of the namecache.
4577  */
4578 static int __noinline
4579 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4580 {
4581 	struct nameidata *ndp __diagused;
4582 	struct componentname *cnp;
4583 	enum vgetstate dvs;
4584 	struct vnode *dvp, *tvp;
4585 	struct mount *mp;
4586 	seqc_t dvp_seqc;
4587 	int error;
4588 	bool docache;
4589 
4590 	ndp = fpl->ndp;
4591 	cnp = fpl->cnp;
4592 	dvp = fpl->dvp;
4593 	dvp_seqc = fpl->dvp_seqc;
4594 
4595 	MPASS(*(cnp->cn_nameptr) != '/');
4596 	MPASS(cache_fpl_islastcn(ndp));
4597 	if ((cnp->cn_flags & LOCKPARENT) == 0)
4598 		MPASS((cnp->cn_flags & WANTPARENT) != 0);
4599 	MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4600 	MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4601 	    cnp->cn_nameiop == RENAME);
4602 	MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4603 	MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4604 
4605 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4606 	if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4607 		docache = false;
4608 
4609 	/*
4610 	 * Regular lookup nulifies the slash, which we don't do here.
4611 	 * Don't take chances with filesystem routines seeing it for
4612 	 * the last entry.
4613 	 */
4614 	if (cache_fpl_istrailingslash(fpl)) {
4615 		return (cache_fpl_partial(fpl));
4616 	}
4617 
4618 	mp = atomic_load_ptr(&dvp->v_mount);
4619 	if (__predict_false(mp == NULL)) {
4620 		return (cache_fpl_aborted(fpl));
4621 	}
4622 
4623 	if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4624 		cache_fpl_smr_exit(fpl);
4625 		/*
4626 		 * Original code keeps not checking for CREATE which
4627 		 * might be a bug. For now let the old lookup decide.
4628 		 */
4629 		if (cnp->cn_nameiop == CREATE) {
4630 			return (cache_fpl_aborted(fpl));
4631 		}
4632 		return (cache_fpl_handled_error(fpl, EROFS));
4633 	}
4634 
4635 	if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4636 		cache_fpl_smr_exit(fpl);
4637 		return (cache_fpl_handled_error(fpl, EEXIST));
4638 	}
4639 
4640 	/*
4641 	 * Secure access to dvp; check cache_fplookup_partial_setup for
4642 	 * reasoning.
4643 	 *
4644 	 * XXX At least UFS requires its lookup routine to be called for
4645 	 * the last path component, which leads to some level of complication
4646 	 * and inefficiency:
4647 	 * - the target routine always locks the target vnode, but our caller
4648 	 *   may not need it locked
4649 	 * - some of the VOP machinery asserts that the parent is locked, which
4650 	 *   once more may be not required
4651 	 *
4652 	 * TODO: add a flag for filesystems which don't need this.
4653 	 */
4654 	dvs = vget_prep_smr(dvp);
4655 	cache_fpl_smr_exit(fpl);
4656 	if (__predict_false(dvs == VGET_NONE)) {
4657 		return (cache_fpl_aborted(fpl));
4658 	}
4659 
4660 	vget_finish_ref(dvp, dvs);
4661 	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4662 		vrele(dvp);
4663 		return (cache_fpl_aborted(fpl));
4664 	}
4665 
4666 	error = vn_lock(dvp, LK_EXCLUSIVE);
4667 	if (__predict_false(error != 0)) {
4668 		vrele(dvp);
4669 		return (cache_fpl_aborted(fpl));
4670 	}
4671 
4672 	tvp = NULL;
4673 	cnp->cn_flags |= ISLASTCN;
4674 	if (docache)
4675 		cnp->cn_flags |= MAKEENTRY;
4676 	if (cache_fpl_isdotdot(cnp))
4677 		cnp->cn_flags |= ISDOTDOT;
4678 	cnp->cn_lkflags = LK_EXCLUSIVE;
4679 	error = VOP_LOOKUP(dvp, &tvp, cnp);
4680 	switch (error) {
4681 	case EJUSTRETURN:
4682 	case 0:
4683 		break;
4684 	case ENOTDIR:
4685 	case ENOENT:
4686 		vput(dvp);
4687 		return (cache_fpl_handled_error(fpl, error));
4688 	default:
4689 		vput(dvp);
4690 		return (cache_fpl_aborted(fpl));
4691 	}
4692 
4693 	fpl->tvp = tvp;
4694 
4695 	if (tvp == NULL) {
4696 		MPASS(error == EJUSTRETURN);
4697 		if ((cnp->cn_flags & LOCKPARENT) == 0) {
4698 			VOP_UNLOCK(dvp);
4699 		}
4700 		return (cache_fpl_handled(fpl));
4701 	}
4702 
4703 	/*
4704 	 * There are very hairy corner cases concerning various flag combinations
4705 	 * and locking state. In particular here we only hold one lock instead of
4706 	 * two.
4707 	 *
4708 	 * Skip the complexity as it is of no significance for normal workloads.
4709 	 */
4710 	if (__predict_false(tvp == dvp)) {
4711 		vput(dvp);
4712 		vrele(tvp);
4713 		return (cache_fpl_aborted(fpl));
4714 	}
4715 
4716 	/*
4717 	 * If they want the symlink itself we are fine, but if they want to
4718 	 * follow it regular lookup has to be engaged.
4719 	 */
4720 	if (tvp->v_type == VLNK) {
4721 		if ((cnp->cn_flags & FOLLOW) != 0) {
4722 			vput(dvp);
4723 			vput(tvp);
4724 			return (cache_fpl_aborted(fpl));
4725 		}
4726 	}
4727 
4728 	/*
4729 	 * Since we expect this to be the terminal vnode it should almost never
4730 	 * be a mount point.
4731 	 */
4732 	if (__predict_false(cache_fplookup_is_mp(fpl))) {
4733 		vput(dvp);
4734 		vput(tvp);
4735 		return (cache_fpl_aborted(fpl));
4736 	}
4737 
4738 	if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4739 		vput(dvp);
4740 		vput(tvp);
4741 		return (cache_fpl_handled_error(fpl, EEXIST));
4742 	}
4743 
4744 	if ((cnp->cn_flags & LOCKLEAF) == 0) {
4745 		VOP_UNLOCK(tvp);
4746 	}
4747 
4748 	if ((cnp->cn_flags & LOCKPARENT) == 0) {
4749 		VOP_UNLOCK(dvp);
4750 	}
4751 
4752 	return (cache_fpl_handled(fpl));
4753 }
4754 
4755 static int __noinline
4756 cache_fplookup_modifying(struct cache_fpl *fpl)
4757 {
4758 	struct nameidata *ndp;
4759 
4760 	ndp = fpl->ndp;
4761 
4762 	if (!cache_fpl_islastcn(ndp)) {
4763 		return (cache_fpl_partial(fpl));
4764 	}
4765 	return (cache_fplookup_final_modifying(fpl));
4766 }
4767 
4768 static int __noinline
4769 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4770 {
4771 	struct componentname *cnp;
4772 	enum vgetstate dvs, tvs;
4773 	struct vnode *dvp, *tvp;
4774 	seqc_t dvp_seqc;
4775 	int error;
4776 
4777 	cnp = fpl->cnp;
4778 	dvp = fpl->dvp;
4779 	dvp_seqc = fpl->dvp_seqc;
4780 	tvp = fpl->tvp;
4781 
4782 	MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4783 
4784 	/*
4785 	 * This is less efficient than it can be for simplicity.
4786 	 */
4787 	dvs = vget_prep_smr(dvp);
4788 	if (__predict_false(dvs == VGET_NONE)) {
4789 		return (cache_fpl_aborted(fpl));
4790 	}
4791 	tvs = vget_prep_smr(tvp);
4792 	if (__predict_false(tvs == VGET_NONE)) {
4793 		cache_fpl_smr_exit(fpl);
4794 		vget_abort(dvp, dvs);
4795 		return (cache_fpl_aborted(fpl));
4796 	}
4797 
4798 	cache_fpl_smr_exit(fpl);
4799 
4800 	if ((cnp->cn_flags & LOCKPARENT) != 0) {
4801 		error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4802 		if (__predict_false(error != 0)) {
4803 			vget_abort(tvp, tvs);
4804 			return (cache_fpl_aborted(fpl));
4805 		}
4806 	} else {
4807 		vget_finish_ref(dvp, dvs);
4808 	}
4809 
4810 	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4811 		vget_abort(tvp, tvs);
4812 		if ((cnp->cn_flags & LOCKPARENT) != 0)
4813 			vput(dvp);
4814 		else
4815 			vrele(dvp);
4816 		return (cache_fpl_aborted(fpl));
4817 	}
4818 
4819 	error = cache_fplookup_final_child(fpl, tvs);
4820 	if (__predict_false(error != 0)) {
4821 		MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4822 		    fpl->status == CACHE_FPL_STATUS_DESTROYED);
4823 		if ((cnp->cn_flags & LOCKPARENT) != 0)
4824 			vput(dvp);
4825 		else
4826 			vrele(dvp);
4827 		return (error);
4828 	}
4829 
4830 	MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4831 	return (0);
4832 }
4833 
4834 static int
4835 cache_fplookup_final(struct cache_fpl *fpl)
4836 {
4837 	struct componentname *cnp;
4838 	enum vgetstate tvs;
4839 	struct vnode *dvp, *tvp;
4840 	seqc_t dvp_seqc;
4841 
4842 	cnp = fpl->cnp;
4843 	dvp = fpl->dvp;
4844 	dvp_seqc = fpl->dvp_seqc;
4845 	tvp = fpl->tvp;
4846 
4847 	MPASS(*(cnp->cn_nameptr) != '/');
4848 
4849 	if (cnp->cn_nameiop != LOOKUP) {
4850 		return (cache_fplookup_final_modifying(fpl));
4851 	}
4852 
4853 	if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4854 		return (cache_fplookup_final_withparent(fpl));
4855 
4856 	tvs = vget_prep_smr(tvp);
4857 	if (__predict_false(tvs == VGET_NONE)) {
4858 		return (cache_fpl_partial(fpl));
4859 	}
4860 
4861 	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4862 		cache_fpl_smr_exit(fpl);
4863 		vget_abort(tvp, tvs);
4864 		return (cache_fpl_aborted(fpl));
4865 	}
4866 
4867 	cache_fpl_smr_exit(fpl);
4868 	return (cache_fplookup_final_child(fpl, tvs));
4869 }
4870 
4871 /*
4872  * Comment from locked lookup:
4873  * Check for degenerate name (e.g. / or "") which is a way of talking about a
4874  * directory, e.g. like "/." or ".".
4875  */
4876 static int __noinline
4877 cache_fplookup_degenerate(struct cache_fpl *fpl)
4878 {
4879 	struct componentname *cnp;
4880 	struct vnode *dvp;
4881 	enum vgetstate dvs;
4882 	int error, lkflags;
4883 #ifdef INVARIANTS
4884 	char *cp;
4885 #endif
4886 
4887 	fpl->tvp = fpl->dvp;
4888 	fpl->tvp_seqc = fpl->dvp_seqc;
4889 
4890 	cnp = fpl->cnp;
4891 	dvp = fpl->dvp;
4892 
4893 #ifdef INVARIANTS
4894 	for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4895 		KASSERT(*cp == '/',
4896 		    ("%s: encountered non-slash; string [%s]\n", __func__,
4897 		    cnp->cn_pnbuf));
4898 	}
4899 #endif
4900 
4901 	if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4902 		cache_fpl_smr_exit(fpl);
4903 		return (cache_fpl_handled_error(fpl, EISDIR));
4904 	}
4905 
4906 	if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4907 		return (cache_fplookup_final_withparent(fpl));
4908 	}
4909 
4910 	dvs = vget_prep_smr(dvp);
4911 	cache_fpl_smr_exit(fpl);
4912 	if (__predict_false(dvs == VGET_NONE)) {
4913 		return (cache_fpl_aborted(fpl));
4914 	}
4915 
4916 	if ((cnp->cn_flags & LOCKLEAF) != 0) {
4917 		lkflags = LK_SHARED;
4918 		if ((cnp->cn_flags & LOCKSHARED) == 0)
4919 			lkflags = LK_EXCLUSIVE;
4920 		error = vget_finish(dvp, lkflags, dvs);
4921 		if (__predict_false(error != 0)) {
4922 			return (cache_fpl_aborted(fpl));
4923 		}
4924 	} else {
4925 		vget_finish_ref(dvp, dvs);
4926 	}
4927 	return (cache_fpl_handled(fpl));
4928 }
4929 
4930 static int __noinline
4931 cache_fplookup_emptypath(struct cache_fpl *fpl)
4932 {
4933 	struct nameidata *ndp;
4934 	struct componentname *cnp;
4935 	enum vgetstate tvs;
4936 	struct vnode *tvp;
4937 	int error, lkflags;
4938 
4939 	fpl->tvp = fpl->dvp;
4940 	fpl->tvp_seqc = fpl->dvp_seqc;
4941 
4942 	ndp = fpl->ndp;
4943 	cnp = fpl->cnp;
4944 	tvp = fpl->tvp;
4945 
4946 	MPASS(*cnp->cn_pnbuf == '\0');
4947 
4948 	if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
4949 		cache_fpl_smr_exit(fpl);
4950 		return (cache_fpl_handled_error(fpl, ENOENT));
4951 	}
4952 
4953 	MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
4954 
4955 	tvs = vget_prep_smr(tvp);
4956 	cache_fpl_smr_exit(fpl);
4957 	if (__predict_false(tvs == VGET_NONE)) {
4958 		return (cache_fpl_aborted(fpl));
4959 	}
4960 
4961 	if ((cnp->cn_flags & LOCKLEAF) != 0) {
4962 		lkflags = LK_SHARED;
4963 		if ((cnp->cn_flags & LOCKSHARED) == 0)
4964 			lkflags = LK_EXCLUSIVE;
4965 		error = vget_finish(tvp, lkflags, tvs);
4966 		if (__predict_false(error != 0)) {
4967 			return (cache_fpl_aborted(fpl));
4968 		}
4969 	} else {
4970 		vget_finish_ref(tvp, tvs);
4971 	}
4972 
4973 	ndp->ni_resflags |= NIRES_EMPTYPATH;
4974 	return (cache_fpl_handled(fpl));
4975 }
4976 
4977 static int __noinline
4978 cache_fplookup_noentry(struct cache_fpl *fpl)
4979 {
4980 	struct nameidata *ndp;
4981 	struct componentname *cnp;
4982 	enum vgetstate dvs;
4983 	struct vnode *dvp, *tvp;
4984 	seqc_t dvp_seqc;
4985 	int error;
4986 
4987 	ndp = fpl->ndp;
4988 	cnp = fpl->cnp;
4989 	dvp = fpl->dvp;
4990 	dvp_seqc = fpl->dvp_seqc;
4991 
4992 	MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4993 	MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4994 	if (cnp->cn_nameiop == LOOKUP)
4995 		MPASS((cnp->cn_flags & NOCACHE) == 0);
4996 	MPASS(!cache_fpl_isdotdot(cnp));
4997 
4998 	/*
4999 	 * Hack: delayed name len checking.
5000 	 */
5001 	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5002 		cache_fpl_smr_exit(fpl);
5003 		return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5004 	}
5005 
5006 	if (cnp->cn_nameptr[0] == '/') {
5007 		return (cache_fplookup_skip_slashes(fpl));
5008 	}
5009 
5010 	if (cnp->cn_pnbuf[0] == '\0') {
5011 		return (cache_fplookup_emptypath(fpl));
5012 	}
5013 
5014 	if (cnp->cn_nameptr[0] == '\0') {
5015 		if (fpl->tvp == NULL) {
5016 			return (cache_fplookup_degenerate(fpl));
5017 		}
5018 		return (cache_fplookup_trailingslash(fpl));
5019 	}
5020 
5021 	if (cnp->cn_nameiop != LOOKUP) {
5022 		fpl->tvp = NULL;
5023 		return (cache_fplookup_modifying(fpl));
5024 	}
5025 
5026 	/*
5027 	 * Only try to fill in the component if it is the last one,
5028 	 * otherwise not only there may be several to handle but the
5029 	 * walk may be complicated.
5030 	 */
5031 	if (!cache_fpl_islastcn(ndp)) {
5032 		return (cache_fpl_partial(fpl));
5033 	}
5034 
5035 	/*
5036 	 * Regular lookup nulifies the slash, which we don't do here.
5037 	 * Don't take chances with filesystem routines seeing it for
5038 	 * the last entry.
5039 	 */
5040 	if (cache_fpl_istrailingslash(fpl)) {
5041 		return (cache_fpl_partial(fpl));
5042 	}
5043 
5044 	/*
5045 	 * Secure access to dvp; check cache_fplookup_partial_setup for
5046 	 * reasoning.
5047 	 */
5048 	dvs = vget_prep_smr(dvp);
5049 	cache_fpl_smr_exit(fpl);
5050 	if (__predict_false(dvs == VGET_NONE)) {
5051 		return (cache_fpl_aborted(fpl));
5052 	}
5053 
5054 	vget_finish_ref(dvp, dvs);
5055 	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5056 		vrele(dvp);
5057 		return (cache_fpl_aborted(fpl));
5058 	}
5059 
5060 	error = vn_lock(dvp, LK_SHARED);
5061 	if (__predict_false(error != 0)) {
5062 		vrele(dvp);
5063 		return (cache_fpl_aborted(fpl));
5064 	}
5065 
5066 	tvp = NULL;
5067 	/*
5068 	 * TODO: provide variants which don't require locking either vnode.
5069 	 */
5070 	cnp->cn_flags |= ISLASTCN | MAKEENTRY;
5071 	cnp->cn_lkflags = LK_SHARED;
5072 	if ((cnp->cn_flags & LOCKSHARED) == 0) {
5073 		cnp->cn_lkflags = LK_EXCLUSIVE;
5074 	}
5075 	error = VOP_LOOKUP(dvp, &tvp, cnp);
5076 	switch (error) {
5077 	case EJUSTRETURN:
5078 	case 0:
5079 		break;
5080 	case ENOTDIR:
5081 	case ENOENT:
5082 		vput(dvp);
5083 		return (cache_fpl_handled_error(fpl, error));
5084 	default:
5085 		vput(dvp);
5086 		return (cache_fpl_aborted(fpl));
5087 	}
5088 
5089 	fpl->tvp = tvp;
5090 
5091 	if (tvp == NULL) {
5092 		MPASS(error == EJUSTRETURN);
5093 		if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5094 			vput(dvp);
5095 		} else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5096 			VOP_UNLOCK(dvp);
5097 		}
5098 		return (cache_fpl_handled(fpl));
5099 	}
5100 
5101 	if (tvp->v_type == VLNK) {
5102 		if ((cnp->cn_flags & FOLLOW) != 0) {
5103 			vput(dvp);
5104 			vput(tvp);
5105 			return (cache_fpl_aborted(fpl));
5106 		}
5107 	}
5108 
5109 	if (__predict_false(cache_fplookup_is_mp(fpl))) {
5110 		vput(dvp);
5111 		vput(tvp);
5112 		return (cache_fpl_aborted(fpl));
5113 	}
5114 
5115 	if ((cnp->cn_flags & LOCKLEAF) == 0) {
5116 		VOP_UNLOCK(tvp);
5117 	}
5118 
5119 	if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5120 		vput(dvp);
5121 	} else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5122 		VOP_UNLOCK(dvp);
5123 	}
5124 	return (cache_fpl_handled(fpl));
5125 }
5126 
5127 static int __noinline
5128 cache_fplookup_dot(struct cache_fpl *fpl)
5129 {
5130 	int error;
5131 
5132 	MPASS(!seqc_in_modify(fpl->dvp_seqc));
5133 
5134 	if (__predict_false(fpl->dvp->v_type != VDIR)) {
5135 		cache_fpl_smr_exit(fpl);
5136 		return (cache_fpl_handled_error(fpl, ENOTDIR));
5137 	}
5138 
5139 	/*
5140 	 * Just re-assign the value. seqc will be checked later for the first
5141 	 * non-dot path component in line and/or before deciding to return the
5142 	 * vnode.
5143 	 */
5144 	fpl->tvp = fpl->dvp;
5145 	fpl->tvp_seqc = fpl->dvp_seqc;
5146 
5147 	SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
5148 
5149 	error = 0;
5150 	if (cache_fplookup_is_mp(fpl)) {
5151 		error = cache_fplookup_cross_mount(fpl);
5152 	}
5153 	return (error);
5154 }
5155 
5156 static int __noinline
5157 cache_fplookup_dotdot(struct cache_fpl *fpl)
5158 {
5159 	struct nameidata *ndp;
5160 	struct componentname *cnp;
5161 	struct namecache *ncp;
5162 	struct vnode *dvp;
5163 	struct prison *pr;
5164 	u_char nc_flag;
5165 
5166 	ndp = fpl->ndp;
5167 	cnp = fpl->cnp;
5168 	dvp = fpl->dvp;
5169 
5170 	MPASS(cache_fpl_isdotdot(cnp));
5171 
5172 	/*
5173 	 * XXX this is racy the same way regular lookup is
5174 	 */
5175 	for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5176 	    pr = pr->pr_parent)
5177 		if (dvp == pr->pr_root)
5178 			break;
5179 
5180 	if (dvp == ndp->ni_rootdir ||
5181 	    dvp == ndp->ni_topdir ||
5182 	    dvp == rootvnode ||
5183 	    pr != NULL) {
5184 		fpl->tvp = dvp;
5185 		fpl->tvp_seqc = vn_seqc_read_any(dvp);
5186 		if (seqc_in_modify(fpl->tvp_seqc)) {
5187 			return (cache_fpl_aborted(fpl));
5188 		}
5189 		return (0);
5190 	}
5191 
5192 	if ((dvp->v_vflag & VV_ROOT) != 0) {
5193 		/*
5194 		 * TODO
5195 		 * The opposite of climb mount is needed here.
5196 		 */
5197 		return (cache_fpl_partial(fpl));
5198 	}
5199 
5200 	if (__predict_false(dvp->v_type != VDIR)) {
5201 		cache_fpl_smr_exit(fpl);
5202 		return (cache_fpl_handled_error(fpl, ENOTDIR));
5203 	}
5204 
5205 	ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5206 	if (ncp == NULL) {
5207 		return (cache_fpl_aborted(fpl));
5208 	}
5209 
5210 	nc_flag = atomic_load_char(&ncp->nc_flag);
5211 	if ((nc_flag & NCF_ISDOTDOT) != 0) {
5212 		if ((nc_flag & NCF_NEGATIVE) != 0)
5213 			return (cache_fpl_aborted(fpl));
5214 		fpl->tvp = ncp->nc_vp;
5215 	} else {
5216 		fpl->tvp = ncp->nc_dvp;
5217 	}
5218 
5219 	fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5220 	if (seqc_in_modify(fpl->tvp_seqc)) {
5221 		return (cache_fpl_partial(fpl));
5222 	}
5223 
5224 	/*
5225 	 * Acquire fence provided by vn_seqc_read_any above.
5226 	 */
5227 	if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5228 		return (cache_fpl_aborted(fpl));
5229 	}
5230 
5231 	if (!cache_ncp_canuse(ncp)) {
5232 		return (cache_fpl_aborted(fpl));
5233 	}
5234 
5235 	return (0);
5236 }
5237 
5238 static int __noinline
5239 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5240 {
5241 	u_char nc_flag __diagused;
5242 	bool neg_promote;
5243 
5244 #ifdef INVARIANTS
5245 	nc_flag = atomic_load_char(&ncp->nc_flag);
5246 	MPASS((nc_flag & NCF_NEGATIVE) != 0);
5247 #endif
5248 	/*
5249 	 * If they want to create an entry we need to replace this one.
5250 	 */
5251 	if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5252 		fpl->tvp = NULL;
5253 		return (cache_fplookup_modifying(fpl));
5254 	}
5255 	neg_promote = cache_neg_hit_prep(ncp);
5256 	if (!cache_fpl_neg_ncp_canuse(ncp)) {
5257 		cache_neg_hit_abort(ncp);
5258 		return (cache_fpl_partial(fpl));
5259 	}
5260 	if (neg_promote) {
5261 		return (cache_fplookup_negative_promote(fpl, ncp, hash));
5262 	}
5263 	cache_neg_hit_finish(ncp);
5264 	cache_fpl_smr_exit(fpl);
5265 	return (cache_fpl_handled_error(fpl, ENOENT));
5266 }
5267 
5268 /*
5269  * Resolve a symlink. Called by filesystem-specific routines.
5270  *
5271  * Code flow is:
5272  * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5273  */
5274 int
5275 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5276 {
5277 	struct nameidata *ndp;
5278 	struct componentname *cnp;
5279 	size_t adjust;
5280 
5281 	ndp = fpl->ndp;
5282 	cnp = fpl->cnp;
5283 
5284 	if (__predict_false(len == 0)) {
5285 		return (ENOENT);
5286 	}
5287 
5288 	if (__predict_false(len > MAXPATHLEN - 2)) {
5289 		if (cache_fpl_istrailingslash(fpl)) {
5290 			return (EAGAIN);
5291 		}
5292 	}
5293 
5294 	ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5295 #ifdef INVARIANTS
5296 	if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5297 		panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5298 		    __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5299 		    cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5300 	}
5301 #endif
5302 
5303 	if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5304 		return (ENAMETOOLONG);
5305 	}
5306 
5307 	if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5308 		return (ELOOP);
5309 	}
5310 
5311 	adjust = len;
5312 	if (ndp->ni_pathlen > 1) {
5313 		bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5314 	} else {
5315 		if (cache_fpl_istrailingslash(fpl)) {
5316 			adjust = len + 1;
5317 			cnp->cn_pnbuf[len] = '/';
5318 			cnp->cn_pnbuf[len + 1] = '\0';
5319 		} else {
5320 			cnp->cn_pnbuf[len] = '\0';
5321 		}
5322 	}
5323 	bcopy(string, cnp->cn_pnbuf, len);
5324 
5325 	ndp->ni_pathlen += adjust;
5326 	cache_fpl_pathlen_add(fpl, adjust);
5327 	cnp->cn_nameptr = cnp->cn_pnbuf;
5328 	fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5329 	fpl->tvp = NULL;
5330 	return (0);
5331 }
5332 
5333 static int __noinline
5334 cache_fplookup_symlink(struct cache_fpl *fpl)
5335 {
5336 	struct mount *mp;
5337 	struct nameidata *ndp;
5338 	struct componentname *cnp;
5339 	struct vnode *dvp, *tvp;
5340 	struct pwd *pwd;
5341 	int error;
5342 
5343 	ndp = fpl->ndp;
5344 	cnp = fpl->cnp;
5345 	dvp = fpl->dvp;
5346 	tvp = fpl->tvp;
5347 	pwd = *(fpl->pwd);
5348 
5349 	if (cache_fpl_islastcn(ndp)) {
5350 		if ((cnp->cn_flags & FOLLOW) == 0) {
5351 			return (cache_fplookup_final(fpl));
5352 		}
5353 	}
5354 
5355 	mp = atomic_load_ptr(&dvp->v_mount);
5356 	if (__predict_false(mp == NULL)) {
5357 		return (cache_fpl_aborted(fpl));
5358 	}
5359 
5360 	/*
5361 	 * Note this check races against setting the flag just like regular
5362 	 * lookup.
5363 	 */
5364 	if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5365 		cache_fpl_smr_exit(fpl);
5366 		return (cache_fpl_handled_error(fpl, EACCES));
5367 	}
5368 
5369 	error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5370 	if (__predict_false(error != 0)) {
5371 		switch (error) {
5372 		case EAGAIN:
5373 			return (cache_fpl_partial(fpl));
5374 		case ENOENT:
5375 		case ENAMETOOLONG:
5376 		case ELOOP:
5377 			cache_fpl_smr_exit(fpl);
5378 			return (cache_fpl_handled_error(fpl, error));
5379 		default:
5380 			return (cache_fpl_aborted(fpl));
5381 		}
5382 	}
5383 
5384 	if (*(cnp->cn_nameptr) == '/') {
5385 		fpl->dvp = cache_fpl_handle_root(fpl);
5386 		fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5387 		if (seqc_in_modify(fpl->dvp_seqc)) {
5388 			return (cache_fpl_aborted(fpl));
5389 		}
5390 		/*
5391 		 * The main loop assumes that ->dvp points to a vnode belonging
5392 		 * to a filesystem which can do lockless lookup, but the absolute
5393 		 * symlink can be wandering off to one which does not.
5394 		 */
5395 		mp = atomic_load_ptr(&fpl->dvp->v_mount);
5396 		if (__predict_false(mp == NULL)) {
5397 			return (cache_fpl_aborted(fpl));
5398 		}
5399 		if (!cache_fplookup_mp_supported(mp)) {
5400 			cache_fpl_checkpoint(fpl);
5401 			return (cache_fpl_partial(fpl));
5402 		}
5403 		if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir)) {
5404 			return (cache_fpl_aborted(fpl));
5405 		}
5406 	}
5407 	return (0);
5408 }
5409 
5410 static int
5411 cache_fplookup_next(struct cache_fpl *fpl)
5412 {
5413 	struct componentname *cnp;
5414 	struct namecache *ncp;
5415 	struct vnode *dvp, *tvp;
5416 	u_char nc_flag;
5417 	uint32_t hash;
5418 	int error;
5419 
5420 	cnp = fpl->cnp;
5421 	dvp = fpl->dvp;
5422 	hash = fpl->hash;
5423 
5424 	if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5425 		if (cnp->cn_namelen == 1) {
5426 			return (cache_fplookup_dot(fpl));
5427 		}
5428 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5429 			return (cache_fplookup_dotdot(fpl));
5430 		}
5431 	}
5432 
5433 	MPASS(!cache_fpl_isdotdot(cnp));
5434 
5435 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5436 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5437 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5438 			break;
5439 	}
5440 
5441 	if (__predict_false(ncp == NULL)) {
5442 		return (cache_fplookup_noentry(fpl));
5443 	}
5444 
5445 	tvp = atomic_load_ptr(&ncp->nc_vp);
5446 	nc_flag = atomic_load_char(&ncp->nc_flag);
5447 	if ((nc_flag & NCF_NEGATIVE) != 0) {
5448 		return (cache_fplookup_neg(fpl, ncp, hash));
5449 	}
5450 
5451 	if (!cache_ncp_canuse(ncp)) {
5452 		return (cache_fpl_partial(fpl));
5453 	}
5454 
5455 	fpl->tvp = tvp;
5456 	fpl->tvp_seqc = vn_seqc_read_any(tvp);
5457 	if (seqc_in_modify(fpl->tvp_seqc)) {
5458 		return (cache_fpl_partial(fpl));
5459 	}
5460 
5461 	counter_u64_add(numposhits, 1);
5462 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5463 
5464 	error = 0;
5465 	if (cache_fplookup_is_mp(fpl)) {
5466 		error = cache_fplookup_cross_mount(fpl);
5467 	}
5468 	return (error);
5469 }
5470 
5471 static bool
5472 cache_fplookup_mp_supported(struct mount *mp)
5473 {
5474 
5475 	MPASS(mp != NULL);
5476 	if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5477 		return (false);
5478 	return (true);
5479 }
5480 
5481 /*
5482  * Walk up the mount stack (if any).
5483  *
5484  * Correctness is provided in the following ways:
5485  * - all vnodes are protected from freeing with SMR
5486  * - struct mount objects are type stable making them always safe to access
5487  * - stability of the particular mount is provided by busying it
5488  * - relationship between the vnode which is mounted on and the mount is
5489  *   verified with the vnode sequence counter after busying
5490  * - association between root vnode of the mount and the mount is protected
5491  *   by busy
5492  *
5493  * From that point on we can read the sequence counter of the root vnode
5494  * and get the next mount on the stack (if any) using the same protection.
5495  *
5496  * By the end of successful walk we are guaranteed the reached state was
5497  * indeed present at least at some point which matches the regular lookup.
5498  */
5499 static int __noinline
5500 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5501 {
5502 	struct mount *mp, *prev_mp;
5503 	struct mount_pcpu *mpcpu, *prev_mpcpu;
5504 	struct vnode *vp;
5505 	seqc_t vp_seqc;
5506 
5507 	vp = fpl->tvp;
5508 	vp_seqc = fpl->tvp_seqc;
5509 
5510 	VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5511 	mp = atomic_load_ptr(&vp->v_mountedhere);
5512 	if (__predict_false(mp == NULL)) {
5513 		return (0);
5514 	}
5515 
5516 	prev_mp = NULL;
5517 	for (;;) {
5518 		if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5519 			if (prev_mp != NULL)
5520 				vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5521 			return (cache_fpl_partial(fpl));
5522 		}
5523 		if (prev_mp != NULL)
5524 			vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5525 		if (!vn_seqc_consistent(vp, vp_seqc)) {
5526 			vfs_op_thread_exit_crit(mp, mpcpu);
5527 			return (cache_fpl_partial(fpl));
5528 		}
5529 		if (!cache_fplookup_mp_supported(mp)) {
5530 			vfs_op_thread_exit_crit(mp, mpcpu);
5531 			return (cache_fpl_partial(fpl));
5532 		}
5533 		vp = atomic_load_ptr(&mp->mnt_rootvnode);
5534 		if (vp == NULL) {
5535 			vfs_op_thread_exit_crit(mp, mpcpu);
5536 			return (cache_fpl_partial(fpl));
5537 		}
5538 		vp_seqc = vn_seqc_read_any(vp);
5539 		if (seqc_in_modify(vp_seqc)) {
5540 			vfs_op_thread_exit_crit(mp, mpcpu);
5541 			return (cache_fpl_partial(fpl));
5542 		}
5543 		prev_mp = mp;
5544 		prev_mpcpu = mpcpu;
5545 		mp = atomic_load_ptr(&vp->v_mountedhere);
5546 		if (mp == NULL)
5547 			break;
5548 	}
5549 
5550 	vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5551 	fpl->tvp = vp;
5552 	fpl->tvp_seqc = vp_seqc;
5553 	return (0);
5554 }
5555 
5556 static int __noinline
5557 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5558 {
5559 	struct mount *mp;
5560 	struct mount_pcpu *mpcpu;
5561 	struct vnode *vp;
5562 	seqc_t vp_seqc;
5563 
5564 	vp = fpl->tvp;
5565 	vp_seqc = fpl->tvp_seqc;
5566 
5567 	VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5568 	mp = atomic_load_ptr(&vp->v_mountedhere);
5569 	if (__predict_false(mp == NULL)) {
5570 		return (0);
5571 	}
5572 
5573 	if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5574 		return (cache_fpl_partial(fpl));
5575 	}
5576 	if (!vn_seqc_consistent(vp, vp_seqc)) {
5577 		vfs_op_thread_exit_crit(mp, mpcpu);
5578 		return (cache_fpl_partial(fpl));
5579 	}
5580 	if (!cache_fplookup_mp_supported(mp)) {
5581 		vfs_op_thread_exit_crit(mp, mpcpu);
5582 		return (cache_fpl_partial(fpl));
5583 	}
5584 	vp = atomic_load_ptr(&mp->mnt_rootvnode);
5585 	if (__predict_false(vp == NULL)) {
5586 		vfs_op_thread_exit_crit(mp, mpcpu);
5587 		return (cache_fpl_partial(fpl));
5588 	}
5589 	vp_seqc = vn_seqc_read_any(vp);
5590 	vfs_op_thread_exit_crit(mp, mpcpu);
5591 	if (seqc_in_modify(vp_seqc)) {
5592 		return (cache_fpl_partial(fpl));
5593 	}
5594 	mp = atomic_load_ptr(&vp->v_mountedhere);
5595 	if (__predict_false(mp != NULL)) {
5596 		/*
5597 		 * There are possibly more mount points on top.
5598 		 * Normally this does not happen so for simplicity just start
5599 		 * over.
5600 		 */
5601 		return (cache_fplookup_climb_mount(fpl));
5602 	}
5603 
5604 	fpl->tvp = vp;
5605 	fpl->tvp_seqc = vp_seqc;
5606 	return (0);
5607 }
5608 
5609 /*
5610  * Check if a vnode is mounted on.
5611  */
5612 static bool
5613 cache_fplookup_is_mp(struct cache_fpl *fpl)
5614 {
5615 	struct vnode *vp;
5616 
5617 	vp = fpl->tvp;
5618 	return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5619 }
5620 
5621 /*
5622  * Parse the path.
5623  *
5624  * The code was originally copy-pasted from regular lookup and despite
5625  * clean ups leaves performance on the table. Any modifications here
5626  * must take into account that in case off fallback the resulting
5627  * nameidata state has to be compatible with the original.
5628  */
5629 
5630 /*
5631  * Debug ni_pathlen tracking.
5632  */
5633 #ifdef INVARIANTS
5634 static void
5635 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5636 {
5637 
5638 	fpl->debug.ni_pathlen += n;
5639 	KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5640 	    ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5641 }
5642 
5643 static void
5644 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5645 {
5646 
5647 	fpl->debug.ni_pathlen -= n;
5648 	KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5649 	    ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5650 }
5651 
5652 static void
5653 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5654 {
5655 
5656 	cache_fpl_pathlen_add(fpl, 1);
5657 }
5658 
5659 static void
5660 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5661 {
5662 
5663 	cache_fpl_pathlen_sub(fpl, 1);
5664 }
5665 #else
5666 static void
5667 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5668 {
5669 }
5670 
5671 static void
5672 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5673 {
5674 }
5675 
5676 static void
5677 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5678 {
5679 }
5680 
5681 static void
5682 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5683 {
5684 }
5685 #endif
5686 
5687 static void
5688 cache_fplookup_parse(struct cache_fpl *fpl)
5689 {
5690 	struct nameidata *ndp;
5691 	struct componentname *cnp;
5692 	struct vnode *dvp;
5693 	char *cp;
5694 	uint32_t hash;
5695 
5696 	ndp = fpl->ndp;
5697 	cnp = fpl->cnp;
5698 	dvp = fpl->dvp;
5699 
5700 	/*
5701 	 * Find the end of this path component, it is either / or nul.
5702 	 *
5703 	 * Store / as a temporary sentinel so that we only have one character
5704 	 * to test for. Pathnames tend to be short so this should not be
5705 	 * resulting in cache misses.
5706 	 *
5707 	 * TODO: fix this to be word-sized.
5708 	 */
5709 	MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5710 	KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5711 	    ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5712 	    __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5713 	    fpl->nulchar, cnp->cn_pnbuf));
5714 	KASSERT(*fpl->nulchar == '\0',
5715 	    ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5716 	    cnp->cn_pnbuf));
5717 	hash = cache_get_hash_iter_start(dvp);
5718 	*fpl->nulchar = '/';
5719 	for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5720 		KASSERT(*cp != '\0',
5721 		    ("%s: encountered unexpected nul; string [%s]\n", __func__,
5722 		    cnp->cn_nameptr));
5723 		hash = cache_get_hash_iter(*cp, hash);
5724 		continue;
5725 	}
5726 	*fpl->nulchar = '\0';
5727 	fpl->hash = cache_get_hash_iter_finish(hash);
5728 
5729 	cnp->cn_namelen = cp - cnp->cn_nameptr;
5730 	cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5731 
5732 #ifdef INVARIANTS
5733 	/*
5734 	 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5735 	 * we are going to fail this lookup with ENAMETOOLONG (see below).
5736 	 */
5737 	if (cnp->cn_namelen <= NAME_MAX) {
5738 		if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5739 			panic("%s: mismatched hash for [%s] len %ld", __func__,
5740 			    cnp->cn_nameptr, cnp->cn_namelen);
5741 		}
5742 	}
5743 #endif
5744 
5745 	/*
5746 	 * Hack: we have to check if the found path component's length exceeds
5747 	 * NAME_MAX. However, the condition is very rarely true and check can
5748 	 * be elided in the common case -- if an entry was found in the cache,
5749 	 * then it could not have been too long to begin with.
5750 	 */
5751 	ndp->ni_next = cp;
5752 }
5753 
5754 static void
5755 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5756 {
5757 	struct nameidata *ndp;
5758 	struct componentname *cnp;
5759 
5760 	ndp = fpl->ndp;
5761 	cnp = fpl->cnp;
5762 
5763 	cnp->cn_nameptr = ndp->ni_next;
5764 	KASSERT(*(cnp->cn_nameptr) == '/',
5765 	    ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5766 	    cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5767 	cnp->cn_nameptr++;
5768 	cache_fpl_pathlen_dec(fpl);
5769 }
5770 
5771 /*
5772  * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5773  *
5774  * Lockless lookup tries to elide checking for spurious slashes and should they
5775  * be present is guaranteed to fail to find an entry. In this case the caller
5776  * must check if the name starts with a slash and call this routine.  It is
5777  * going to fast forward across the spurious slashes and set the state up for
5778  * retry.
5779  */
5780 static int __noinline
5781 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5782 {
5783 	struct nameidata *ndp;
5784 	struct componentname *cnp;
5785 
5786 	ndp = fpl->ndp;
5787 	cnp = fpl->cnp;
5788 
5789 	MPASS(*(cnp->cn_nameptr) == '/');
5790 	do {
5791 		cnp->cn_nameptr++;
5792 		cache_fpl_pathlen_dec(fpl);
5793 	} while (*(cnp->cn_nameptr) == '/');
5794 
5795 	/*
5796 	 * Go back to one slash so that cache_fplookup_parse_advance has
5797 	 * something to skip.
5798 	 */
5799 	cnp->cn_nameptr--;
5800 	cache_fpl_pathlen_inc(fpl);
5801 
5802 	/*
5803 	 * cache_fplookup_parse_advance starts from ndp->ni_next
5804 	 */
5805 	ndp->ni_next = cnp->cn_nameptr;
5806 
5807 	/*
5808 	 * See cache_fplookup_dot.
5809 	 */
5810 	fpl->tvp = fpl->dvp;
5811 	fpl->tvp_seqc = fpl->dvp_seqc;
5812 
5813 	return (0);
5814 }
5815 
5816 /*
5817  * Handle trailing slashes (e.g., "foo/").
5818  *
5819  * If a trailing slash is found the terminal vnode must be a directory.
5820  * Regular lookup shortens the path by nulifying the first trailing slash and
5821  * sets the TRAILINGSLASH flag to denote this took place. There are several
5822  * checks on it performed later.
5823  *
5824  * Similarly to spurious slashes, lockless lookup handles this in a speculative
5825  * manner relying on an invariant that a non-directory vnode will get a miss.
5826  * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5827  *
5828  * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5829  * and denotes this is the last path component, which avoids looping back.
5830  *
5831  * Only plain lookups are supported for now to restrict corner cases to handle.
5832  */
5833 static int __noinline
5834 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5835 {
5836 #ifdef INVARIANTS
5837 	size_t ni_pathlen;
5838 #endif
5839 	struct nameidata *ndp;
5840 	struct componentname *cnp;
5841 	struct namecache *ncp;
5842 	struct vnode *tvp;
5843 	char *cn_nameptr_orig, *cn_nameptr_slash;
5844 	seqc_t tvp_seqc;
5845 	u_char nc_flag;
5846 
5847 	ndp = fpl->ndp;
5848 	cnp = fpl->cnp;
5849 	tvp = fpl->tvp;
5850 	tvp_seqc = fpl->tvp_seqc;
5851 
5852 	MPASS(fpl->dvp == fpl->tvp);
5853 	KASSERT(cache_fpl_istrailingslash(fpl),
5854 	    ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5855 	    cnp->cn_pnbuf));
5856 	KASSERT(cnp->cn_nameptr[0] == '\0',
5857 	    ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5858 	    cnp->cn_pnbuf));
5859 	KASSERT(cnp->cn_namelen == 0,
5860 	    ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5861 	    cnp->cn_pnbuf));
5862 	MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5863 
5864 	if (cnp->cn_nameiop != LOOKUP) {
5865 		return (cache_fpl_aborted(fpl));
5866 	}
5867 
5868 	if (__predict_false(tvp->v_type != VDIR)) {
5869 		if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5870 			return (cache_fpl_aborted(fpl));
5871 		}
5872 		cache_fpl_smr_exit(fpl);
5873 		return (cache_fpl_handled_error(fpl, ENOTDIR));
5874 	}
5875 
5876 	/*
5877 	 * Denote the last component.
5878 	 */
5879 	ndp->ni_next = &cnp->cn_nameptr[0];
5880 	MPASS(cache_fpl_islastcn(ndp));
5881 
5882 	/*
5883 	 * Unwind trailing slashes.
5884 	 */
5885 	cn_nameptr_orig = cnp->cn_nameptr;
5886 	while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5887 		cnp->cn_nameptr--;
5888 		if (cnp->cn_nameptr[0] != '/') {
5889 			break;
5890 		}
5891 	}
5892 
5893 	/*
5894 	 * Unwind to the beginning of the path component.
5895 	 *
5896 	 * Note the path may or may not have started with a slash.
5897 	 */
5898 	cn_nameptr_slash = cnp->cn_nameptr;
5899 	while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5900 		cnp->cn_nameptr--;
5901 		if (cnp->cn_nameptr[0] == '/') {
5902 			break;
5903 		}
5904 	}
5905 	if (cnp->cn_nameptr[0] == '/') {
5906 		cnp->cn_nameptr++;
5907 	}
5908 
5909 	cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5910 	cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5911 	cache_fpl_checkpoint(fpl);
5912 
5913 #ifdef INVARIANTS
5914 	ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5915 	if (ni_pathlen != fpl->debug.ni_pathlen) {
5916 		panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5917 		    __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5918 		    cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5919 	}
5920 #endif
5921 
5922 	/*
5923 	 * If this was a "./" lookup the parent directory is already correct.
5924 	 */
5925 	if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5926 		return (0);
5927 	}
5928 
5929 	/*
5930 	 * Otherwise we need to look it up.
5931 	 */
5932 	tvp = fpl->tvp;
5933 	ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5934 	if (__predict_false(ncp == NULL)) {
5935 		return (cache_fpl_aborted(fpl));
5936 	}
5937 	nc_flag = atomic_load_char(&ncp->nc_flag);
5938 	if ((nc_flag & NCF_ISDOTDOT) != 0) {
5939 		return (cache_fpl_aborted(fpl));
5940 	}
5941 	fpl->dvp = ncp->nc_dvp;
5942 	fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5943 	if (seqc_in_modify(fpl->dvp_seqc)) {
5944 		return (cache_fpl_aborted(fpl));
5945 	}
5946 	return (0);
5947 }
5948 
5949 /*
5950  * See the API contract for VOP_FPLOOKUP_VEXEC.
5951  */
5952 static int __noinline
5953 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5954 {
5955 	struct componentname *cnp;
5956 	struct vnode *dvp;
5957 	seqc_t dvp_seqc;
5958 
5959 	cnp = fpl->cnp;
5960 	dvp = fpl->dvp;
5961 	dvp_seqc = fpl->dvp_seqc;
5962 
5963 	/*
5964 	 * Hack: delayed empty path checking.
5965 	 */
5966 	if (cnp->cn_pnbuf[0] == '\0') {
5967 		return (cache_fplookup_emptypath(fpl));
5968 	}
5969 
5970 	/*
5971 	 * TODO: Due to ignoring trailing slashes lookup will perform a
5972 	 * permission check on the last dir when it should not be doing it.  It
5973 	 * may fail, but said failure should be ignored. It is possible to fix
5974 	 * it up fully without resorting to regular lookup, but for now just
5975 	 * abort.
5976 	 */
5977 	if (cache_fpl_istrailingslash(fpl)) {
5978 		return (cache_fpl_aborted(fpl));
5979 	}
5980 
5981 	/*
5982 	 * Hack: delayed degenerate path checking.
5983 	 */
5984 	if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5985 		return (cache_fplookup_degenerate(fpl));
5986 	}
5987 
5988 	/*
5989 	 * Hack: delayed name len checking.
5990 	 */
5991 	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5992 		cache_fpl_smr_exit(fpl);
5993 		return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5994 	}
5995 
5996 	/*
5997 	 * Hack: they may be looking up foo/bar, where foo is not a directory.
5998 	 * In such a case we need to return ENOTDIR, but we may happen to get
5999 	 * here with a different error.
6000 	 */
6001 	if (dvp->v_type != VDIR) {
6002 		error = ENOTDIR;
6003 	}
6004 
6005 	/*
6006 	 * Hack: handle O_SEARCH.
6007 	 *
6008 	 * Open Group Base Specifications Issue 7, 2018 edition states:
6009 	 * <quote>
6010 	 * If the access mode of the open file description associated with the
6011 	 * file descriptor is not O_SEARCH, the function shall check whether
6012 	 * directory searches are permitted using the current permissions of
6013 	 * the directory underlying the file descriptor. If the access mode is
6014 	 * O_SEARCH, the function shall not perform the check.
6015 	 * </quote>
6016 	 *
6017 	 * Regular lookup tests for the NOEXECCHECK flag for every path
6018 	 * component to decide whether to do the permission check. However,
6019 	 * since most lookups never have the flag (and when they do it is only
6020 	 * present for the first path component), lockless lookup only acts on
6021 	 * it if there is a permission problem. Here the flag is represented
6022 	 * with a boolean so that we don't have to clear it on the way out.
6023 	 *
6024 	 * For simplicity this always aborts.
6025 	 * TODO: check if this is the first lookup and ignore the permission
6026 	 * problem. Note the flag has to survive fallback (if it happens to be
6027 	 * performed).
6028 	 */
6029 	if (fpl->fsearch) {
6030 		return (cache_fpl_aborted(fpl));
6031 	}
6032 
6033 	switch (error) {
6034 	case EAGAIN:
6035 		if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6036 			error = cache_fpl_aborted(fpl);
6037 		} else {
6038 			cache_fpl_partial(fpl);
6039 		}
6040 		break;
6041 	default:
6042 		if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6043 			error = cache_fpl_aborted(fpl);
6044 		} else {
6045 			cache_fpl_smr_exit(fpl);
6046 			cache_fpl_handled_error(fpl, error);
6047 		}
6048 		break;
6049 	}
6050 	return (error);
6051 }
6052 
6053 static int
6054 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
6055 {
6056 	struct nameidata *ndp;
6057 	struct componentname *cnp;
6058 	struct mount *mp;
6059 	int error;
6060 
6061 	ndp = fpl->ndp;
6062 	cnp = fpl->cnp;
6063 
6064 	cache_fpl_checkpoint(fpl);
6065 
6066 	/*
6067 	 * The vnode at hand is almost always stable, skip checking for it.
6068 	 * Worst case this postpones the check towards the end of the iteration
6069 	 * of the main loop.
6070 	 */
6071 	fpl->dvp = dvp;
6072 	fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
6073 
6074 	mp = atomic_load_ptr(&dvp->v_mount);
6075 	if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
6076 		return (cache_fpl_aborted(fpl));
6077 	}
6078 
6079 	MPASS(fpl->tvp == NULL);
6080 
6081 	for (;;) {
6082 		cache_fplookup_parse(fpl);
6083 
6084 		error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
6085 		if (__predict_false(error != 0)) {
6086 			error = cache_fplookup_failed_vexec(fpl, error);
6087 			break;
6088 		}
6089 
6090 		error = cache_fplookup_next(fpl);
6091 		if (__predict_false(cache_fpl_terminated(fpl))) {
6092 			break;
6093 		}
6094 
6095 		VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
6096 
6097 		if (fpl->tvp->v_type == VLNK) {
6098 			error = cache_fplookup_symlink(fpl);
6099 			if (cache_fpl_terminated(fpl)) {
6100 				break;
6101 			}
6102 		} else {
6103 			if (cache_fpl_islastcn(ndp)) {
6104 				error = cache_fplookup_final(fpl);
6105 				break;
6106 			}
6107 
6108 			if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
6109 				error = cache_fpl_aborted(fpl);
6110 				break;
6111 			}
6112 
6113 			fpl->dvp = fpl->tvp;
6114 			fpl->dvp_seqc = fpl->tvp_seqc;
6115 			cache_fplookup_parse_advance(fpl);
6116 		}
6117 
6118 		cache_fpl_checkpoint(fpl);
6119 	}
6120 
6121 	return (error);
6122 }
6123 
6124 /*
6125  * Fast path lookup protected with SMR and sequence counters.
6126  *
6127  * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
6128  *
6129  * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
6130  * outlined below.
6131  *
6132  * Traditional vnode lookup conceptually looks like this:
6133  *
6134  * vn_lock(current);
6135  * for (;;) {
6136  *	next = find();
6137  *	vn_lock(next);
6138  *	vn_unlock(current);
6139  *	current = next;
6140  *	if (last)
6141  *	    break;
6142  * }
6143  * return (current);
6144  *
6145  * Each jump to the next vnode is safe memory-wise and atomic with respect to
6146  * any modifications thanks to holding respective locks.
6147  *
6148  * The same guarantee can be provided with a combination of safe memory
6149  * reclamation and sequence counters instead. If all operations which affect
6150  * the relationship between the current vnode and the one we are looking for
6151  * also modify the counter, we can verify whether all the conditions held as
6152  * we made the jump. This includes things like permissions, mount points etc.
6153  * Counter modification is provided by enclosing relevant places in
6154  * vn_seqc_write_begin()/end() calls.
6155  *
6156  * Thus this translates to:
6157  *
6158  * vfs_smr_enter();
6159  * dvp_seqc = seqc_read_any(dvp);
6160  * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
6161  *     abort();
6162  * for (;;) {
6163  * 	tvp = find();
6164  * 	tvp_seqc = seqc_read_any(tvp);
6165  * 	if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6166  * 	    abort();
6167  * 	if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6168  * 	    abort();
6169  * 	dvp = tvp; // we know nothing of importance has changed
6170  * 	dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6171  * 	if (last)
6172  * 	    break;
6173  * }
6174  * vget(); // secure the vnode
6175  * if (!seqc_consistent(tvp, tvp_seqc) // final check
6176  * 	    abort();
6177  * // at this point we know nothing has changed for any parent<->child pair
6178  * // as they were crossed during the lookup, meaning we matched the guarantee
6179  * // of the locked variant
6180  * return (tvp);
6181  *
6182  * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6183  * - they are called while within vfs_smr protection which they must never exit
6184  * - EAGAIN can be returned to denote checking could not be performed, it is
6185  *   always valid to return it
6186  * - if the sequence counter has not changed the result must be valid
6187  * - if the sequence counter has changed both false positives and false negatives
6188  *   are permitted (since the result will be rejected later)
6189  * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6190  *
6191  * Caveats to watch out for:
6192  * - vnodes are passed unlocked and unreferenced with nothing stopping
6193  *   VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6194  *   to use atomic_load_ptr to fetch it.
6195  * - the aforementioned object can also get freed, meaning absent other means it
6196  *   should be protected with vfs_smr
6197  * - either safely checking permissions as they are modified or guaranteeing
6198  *   their stability is left to the routine
6199  */
6200 int
6201 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6202     struct pwd **pwdp)
6203 {
6204 	struct cache_fpl fpl;
6205 	struct pwd *pwd;
6206 	struct vnode *dvp;
6207 	struct componentname *cnp;
6208 	int error;
6209 
6210 	fpl.status = CACHE_FPL_STATUS_UNSET;
6211 	fpl.in_smr = false;
6212 	fpl.ndp = ndp;
6213 	fpl.cnp = cnp = &ndp->ni_cnd;
6214 	MPASS(ndp->ni_lcf == 0);
6215 	KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6216 	    ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6217 	    cnp->cn_flags));
6218 	MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6219 	MPASS(ndp->ni_resflags == 0);
6220 
6221 	if (__predict_false(!cache_can_fplookup(&fpl))) {
6222 		*status = fpl.status;
6223 		SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6224 		return (EOPNOTSUPP);
6225 	}
6226 
6227 	cache_fpl_checkpoint_outer(&fpl);
6228 
6229 	cache_fpl_smr_enter_initial(&fpl);
6230 #ifdef INVARIANTS
6231 	fpl.debug.ni_pathlen = ndp->ni_pathlen;
6232 #endif
6233 	fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6234 	fpl.fsearch = false;
6235 	fpl.tvp = NULL; /* for degenerate path handling */
6236 	fpl.pwd = pwdp;
6237 	pwd = pwd_get_smr();
6238 	*(fpl.pwd) = pwd;
6239 	namei_setup_rootdir(ndp, cnp, pwd);
6240 	ndp->ni_topdir = pwd->pwd_jdir;
6241 
6242 	if (cnp->cn_pnbuf[0] == '/') {
6243 		dvp = cache_fpl_handle_root(&fpl);
6244 		ndp->ni_resflags = NIRES_ABS;
6245 	} else {
6246 		if (ndp->ni_dirfd == AT_FDCWD) {
6247 			dvp = pwd->pwd_cdir;
6248 		} else {
6249 			error = cache_fplookup_dirfd(&fpl, &dvp);
6250 			if (__predict_false(error != 0)) {
6251 				goto out;
6252 			}
6253 		}
6254 	}
6255 
6256 	SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6257 	error = cache_fplookup_impl(dvp, &fpl);
6258 out:
6259 	cache_fpl_smr_assert_not_entered(&fpl);
6260 	cache_fpl_assert_status(&fpl);
6261 	*status = fpl.status;
6262 	if (SDT_PROBES_ENABLED()) {
6263 		SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6264 		if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6265 			SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6266 			    ndp);
6267 	}
6268 
6269 	if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6270 		MPASS(error != CACHE_FPL_FAILED);
6271 		if (error != 0) {
6272 			cache_fpl_cleanup_cnp(fpl.cnp);
6273 			MPASS(fpl.dvp == NULL);
6274 			MPASS(fpl.tvp == NULL);
6275 		}
6276 		ndp->ni_dvp = fpl.dvp;
6277 		ndp->ni_vp = fpl.tvp;
6278 	}
6279 	return (error);
6280 }
6281