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