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