xref: /freebsd/sys/kern/vfs_cache.c (revision 3b216bfb6cce24aa84519315138be8d23ac5d613)
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 
71 #include <sys/capsicum.h>
72 
73 #include <security/audit/audit.h>
74 #include <security/mac/mac_framework.h>
75 
76 #ifdef DDB
77 #include <ddb/ddb.h>
78 #endif
79 
80 #include <vm/uma.h>
81 
82 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
83     "Name cache");
84 
85 SDT_PROVIDER_DECLARE(vfs);
86 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
87     "struct vnode *");
88 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
89     "struct vnode *");
90 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
91     "char *");
92 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
93     "const char *");
94 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
95     "struct namecache *", "int", "int");
96 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
97 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
98     "char *", "struct vnode *");
99 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
100 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
101     "struct vnode *", "char *");
102 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
103     "struct vnode *");
104 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
105     "struct vnode *", "char *");
106 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
107     "char *");
108 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
109     "struct componentname *");
110 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
111     "struct componentname *");
112 SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
113 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
114 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
115 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
116 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
117     "struct vnode *");
118 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
119     "char *");
120 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
121     "char *");
122 
123 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
124 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
125 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
126 
127 /*
128  * This structure describes the elements in the cache of recent
129  * names looked up by namei.
130  */
131 struct negstate {
132 	u_char neg_flag;
133 	u_char neg_hit;
134 };
135 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
136     "the state must fit in a union with a pointer without growing it");
137 
138 struct	namecache {
139 	LIST_ENTRY(namecache) nc_src;	/* source vnode list */
140 	TAILQ_ENTRY(namecache) nc_dst;	/* destination vnode list */
141 	CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
142 	struct	vnode *nc_dvp;		/* vnode of parent of name */
143 	union {
144 		struct	vnode *nu_vp;	/* vnode the name refers to */
145 		struct	negstate nu_neg;/* negative entry state */
146 	} n_un;
147 	u_char	nc_flag;		/* flag bits */
148 	u_char	nc_nlen;		/* length of name */
149 	char	nc_name[0];		/* segment name + nul */
150 };
151 
152 /*
153  * struct namecache_ts repeats struct namecache layout up to the
154  * nc_nlen member.
155  * struct namecache_ts is used in place of struct namecache when time(s) need
156  * to be stored.  The nc_dotdottime field is used when a cache entry is mapping
157  * both a non-dotdot directory name plus dotdot for the directory's
158  * parent.
159  *
160  * See below for alignment requirement.
161  */
162 struct	namecache_ts {
163 	struct	timespec nc_time;	/* timespec provided by fs */
164 	struct	timespec nc_dotdottime;	/* dotdot timespec provided by fs */
165 	int	nc_ticks;		/* ticks value when entry was added */
166 	int	nc_pad;
167 	struct namecache nc_nc;
168 };
169 
170 TAILQ_HEAD(cache_freebatch, namecache);
171 
172 /*
173  * At least mips n32 performs 64-bit accesses to timespec as found
174  * in namecache_ts and requires them to be aligned. Since others
175  * may be in the same spot suffer a little bit and enforce the
176  * alignment for everyone. Note this is a nop for 64-bit platforms.
177  */
178 #define CACHE_ZONE_ALIGNMENT	UMA_ALIGNOF(time_t)
179 
180 /*
181  * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
182  * 4.4 BSD codebase. Later on struct namecache was tweaked to become
183  * smaller and the value was bumped to retain the total size, but it
184  * was never re-evaluated for suitability. A simple test counting
185  * lengths during package building shows that the value of 45 covers
186  * about 86% of all added entries, reaching 99% at 65.
187  *
188  * Regardless of the above, use of dedicated zones instead of malloc may be
189  * inducing additional waste. This may be hard to address as said zones are
190  * tied to VFS SMR. Even if retaining them, the current split should be
191  * re-evaluated.
192  */
193 #ifdef __LP64__
194 #define	CACHE_PATH_CUTOFF	45
195 #define	CACHE_LARGE_PAD		6
196 #else
197 #define	CACHE_PATH_CUTOFF	41
198 #define	CACHE_LARGE_PAD		2
199 #endif
200 
201 #define CACHE_ZONE_SMALL_SIZE		(offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
202 #define CACHE_ZONE_SMALL_TS_SIZE	(offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
203 #define CACHE_ZONE_LARGE_SIZE		(offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
204 #define CACHE_ZONE_LARGE_TS_SIZE	(offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
205 
206 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
207 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
208 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
209 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
210 
211 #define	nc_vp		n_un.nu_vp
212 #define	nc_neg		n_un.nu_neg
213 
214 /*
215  * Flags in namecache.nc_flag
216  */
217 #define NCF_WHITE	0x01
218 #define NCF_ISDOTDOT	0x02
219 #define	NCF_TS		0x04
220 #define	NCF_DTS		0x08
221 #define	NCF_DVDROP	0x10
222 #define	NCF_NEGATIVE	0x20
223 #define	NCF_INVALID	0x40
224 #define	NCF_WIP		0x80
225 
226 /*
227  * Flags in negstate.neg_flag
228  */
229 #define NEG_HOT		0x01
230 
231 static bool	cache_neg_evict_cond(u_long lnumcache);
232 
233 /*
234  * Mark an entry as invalid.
235  *
236  * This is called before it starts getting deconstructed.
237  */
238 static void
239 cache_ncp_invalidate(struct namecache *ncp)
240 {
241 
242 	KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
243 	    ("%s: entry %p already invalid", __func__, ncp));
244 	atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
245 	atomic_thread_fence_rel();
246 }
247 
248 /*
249  * Check whether the entry can be safely used.
250  *
251  * All places which elide locks are supposed to call this after they are
252  * done with reading from an entry.
253  */
254 #define cache_ncp_canuse(ncp)	({					\
255 	struct namecache *_ncp = (ncp);					\
256 	u_char _nc_flag;						\
257 									\
258 	atomic_thread_fence_acq();					\
259 	_nc_flag = atomic_load_char(&_ncp->nc_flag);			\
260 	__predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0);	\
261 })
262 
263 /*
264  * Name caching works as follows:
265  *
266  * Names found by directory scans are retained in a cache
267  * for future reference.  It is managed LRU, so frequently
268  * used names will hang around.  Cache is indexed by hash value
269  * obtained from (dvp, name) where dvp refers to the directory
270  * containing name.
271  *
272  * If it is a "negative" entry, (i.e. for a name that is known NOT to
273  * exist) the vnode pointer will be NULL.
274  *
275  * Upon reaching the last segment of a path, if the reference
276  * is for DELETE, or NOCACHE is set (rewrite), and the
277  * name is located in the cache, it will be dropped.
278  *
279  * These locks are used (in the order in which they can be taken):
280  * NAME		TYPE	ROLE
281  * vnodelock	mtx	vnode lists and v_cache_dd field protection
282  * bucketlock	mtx	for access to given set of hash buckets
283  * neglist	mtx	negative entry LRU management
284  *
285  * It is legal to take multiple vnodelock and bucketlock locks. The locking
286  * order is lower address first. Both are recursive.
287  *
288  * "." lookups are lockless.
289  *
290  * ".." and vnode -> name lookups require vnodelock.
291  *
292  * name -> vnode lookup requires the relevant bucketlock to be held for reading.
293  *
294  * Insertions and removals of entries require involved vnodes and bucketlocks
295  * to be locked to provide safe operation against other threads modifying the
296  * cache.
297  *
298  * Some lookups result in removal of the found entry (e.g. getting rid of a
299  * negative entry with the intent to create a positive one), which poses a
300  * problem when multiple threads reach the state. Similarly, two different
301  * threads can purge two different vnodes and try to remove the same name.
302  *
303  * If the already held vnode lock is lower than the second required lock, we
304  * can just take the other lock. However, in the opposite case, this could
305  * deadlock. As such, this is resolved by trylocking and if that fails unlocking
306  * the first node, locking everything in order and revalidating the state.
307  */
308 
309 VFS_SMR_DECLARE;
310 
311 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
312     "Name cache parameters");
313 
314 static u_int __read_mostly	ncsize; /* the size as computed on creation or resizing */
315 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
316     "Total namecache capacity");
317 
318 u_int ncsizefactor = 2;
319 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
320     "Size factor for namecache");
321 
322 static u_long __read_mostly	ncnegfactor = 5; /* ratio of negative entries */
323 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
324     "Ratio of negative namecache entries");
325 
326 /*
327  * Negative entry % of namecache capacity above which automatic eviction is allowed.
328  *
329  * Check cache_neg_evict_cond for details.
330  */
331 static u_int ncnegminpct = 3;
332 
333 static u_int __read_mostly     neg_min; /* the above recomputed against ncsize */
334 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
335     "Negative entry count above which automatic eviction is allowed");
336 
337 /*
338  * Structures associated with name caching.
339  */
340 #define NCHHASH(hash) \
341 	(&nchashtbl[(hash) & nchash])
342 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
343 static u_long __read_mostly	nchash;			/* size of hash table */
344 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
345     "Size of namecache hash table");
346 static u_long __exclusive_cache_line	numneg;	/* number of negative entries allocated */
347 static u_long __exclusive_cache_line	numcache;/* number of cache entries allocated */
348 
349 struct nchstats	nchstats;		/* cache effectiveness statistics */
350 
351 static bool __read_frequently cache_fast_revlookup = true;
352 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
353     &cache_fast_revlookup, 0, "");
354 
355 static u_int __exclusive_cache_line neg_cycle;
356 
357 #define ncneghash	3
358 #define	numneglists	(ncneghash + 1)
359 
360 struct neglist {
361 	struct mtx		nl_evict_lock;
362 	struct mtx		nl_lock __aligned(CACHE_LINE_SIZE);
363 	TAILQ_HEAD(, namecache) nl_list;
364 	TAILQ_HEAD(, namecache) nl_hotlist;
365 	u_long			nl_hotnum;
366 } __aligned(CACHE_LINE_SIZE);
367 
368 static struct neglist neglists[numneglists];
369 
370 static inline struct neglist *
371 NCP2NEGLIST(struct namecache *ncp)
372 {
373 
374 	return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
375 }
376 
377 static inline struct negstate *
378 NCP2NEGSTATE(struct namecache *ncp)
379 {
380 
381 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
382 	return (&ncp->nc_neg);
383 }
384 
385 #define	numbucketlocks (ncbuckethash + 1)
386 static u_int __read_mostly  ncbuckethash;
387 static struct mtx_padalign __read_mostly  *bucketlocks;
388 #define	HASH2BUCKETLOCK(hash) \
389 	((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
390 
391 #define	numvnodelocks (ncvnodehash + 1)
392 static u_int __read_mostly  ncvnodehash;
393 static struct mtx __read_mostly *vnodelocks;
394 static inline struct mtx *
395 VP2VNODELOCK(struct vnode *vp)
396 {
397 
398 	return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
399 }
400 
401 static void
402 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
403 {
404 	struct namecache_ts *ncp_ts;
405 
406 	KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
407 	    (tsp == NULL && ticksp == NULL),
408 	    ("No NCF_TS"));
409 
410 	if (tsp == NULL)
411 		return;
412 
413 	ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
414 	*tsp = ncp_ts->nc_time;
415 	*ticksp = ncp_ts->nc_ticks;
416 }
417 
418 #ifdef DEBUG_CACHE
419 static int __read_mostly	doingcache = 1;	/* 1 => enable the cache */
420 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
421     "VFS namecache enabled");
422 #endif
423 
424 /* Export size information to userland */
425 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
426     sizeof(struct namecache), "sizeof(struct namecache)");
427 
428 /*
429  * The new name cache statistics
430  */
431 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
432     "Name cache statistics");
433 
434 #define STATNODE_ULONG(name, varname, descr)					\
435 	SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
436 #define STATNODE_COUNTER(name, varname, descr)					\
437 	static COUNTER_U64_DEFINE_EARLY(varname);				\
438 	SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
439 	    descr);
440 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
441 STATNODE_ULONG(count, numcache, "Number of cache entries");
442 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
443 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
444 STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
445 STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
446 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
447 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
448 STATNODE_COUNTER(posszaps, numposzaps,
449     "Number of cache hits (positive) we do not want to cache");
450 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
451 STATNODE_COUNTER(negzaps, numnegzaps,
452     "Number of cache hits (negative) we do not want to cache");
453 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
454 /* These count for vn_getcwd(), too. */
455 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
456 STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
457 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
458     "Number of fullpath search errors (VOP_VPTOCNP failures)");
459 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
460 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
461 
462 /*
463  * Debug or developer statistics.
464  */
465 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
466     "Name cache debugging");
467 #define DEBUGNODE_ULONG(name, varname, descr)					\
468 	SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
469 #define DEBUGNODE_COUNTER(name, varname, descr)					\
470 	static COUNTER_U64_DEFINE_EARLY(varname);				\
471 	SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
472 	    descr);
473 DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
474     "Number of successful removals after relocking");
475 static long zap_bucket_fail;
476 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
477 static long zap_bucket_fail2;
478 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
479 static long cache_lock_vnodes_cel_3_failures;
480 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
481     "Number of times 3-way vnode locking failed");
482 
483 static void cache_zap_locked(struct namecache *ncp);
484 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
485     char **freebuf, size_t *buflen);
486 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
487     char **retbuf, size_t *buflen, size_t addend);
488 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
489     char **retbuf, size_t *buflen);
490 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
491     char **retbuf, size_t *len, size_t addend);
492 
493 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
494 
495 static inline void
496 cache_assert_vlp_locked(struct mtx *vlp)
497 {
498 
499 	if (vlp != NULL)
500 		mtx_assert(vlp, MA_OWNED);
501 }
502 
503 static inline void
504 cache_assert_vnode_locked(struct vnode *vp)
505 {
506 	struct mtx *vlp;
507 
508 	vlp = VP2VNODELOCK(vp);
509 	cache_assert_vlp_locked(vlp);
510 }
511 
512 /*
513  * Directory vnodes with entries are held for two reasons:
514  * 1. make them less of a target for reclamation in vnlru
515  * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
516  *
517  * It will be feasible to stop doing it altogether if all filesystems start
518  * supporting lockless lookup.
519  */
520 static void
521 cache_hold_vnode(struct vnode *vp)
522 {
523 
524 	cache_assert_vnode_locked(vp);
525 	VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
526 	vhold(vp);
527 	counter_u64_add(numcachehv, 1);
528 }
529 
530 static void
531 cache_drop_vnode(struct vnode *vp)
532 {
533 
534 	/*
535 	 * Called after all locks are dropped, meaning we can't assert
536 	 * on the state of v_cache_src.
537 	 */
538 	vdrop(vp);
539 	counter_u64_add(numcachehv, -1);
540 }
541 
542 /*
543  * UMA zones.
544  */
545 static uma_zone_t __read_mostly cache_zone_small;
546 static uma_zone_t __read_mostly cache_zone_small_ts;
547 static uma_zone_t __read_mostly cache_zone_large;
548 static uma_zone_t __read_mostly cache_zone_large_ts;
549 
550 static struct namecache *
551 cache_alloc_uma(int len, bool ts)
552 {
553 	struct namecache_ts *ncp_ts;
554 	struct namecache *ncp;
555 
556 	if (__predict_false(ts)) {
557 		if (len <= CACHE_PATH_CUTOFF)
558 			ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
559 		else
560 			ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
561 		ncp = &ncp_ts->nc_nc;
562 	} else {
563 		if (len <= CACHE_PATH_CUTOFF)
564 			ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
565 		else
566 			ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
567 	}
568 	return (ncp);
569 }
570 
571 static void
572 cache_free_uma(struct namecache *ncp)
573 {
574 	struct namecache_ts *ncp_ts;
575 
576 	if (__predict_false(ncp->nc_flag & NCF_TS)) {
577 		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
578 		if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
579 			uma_zfree_smr(cache_zone_small_ts, ncp_ts);
580 		else
581 			uma_zfree_smr(cache_zone_large_ts, ncp_ts);
582 	} else {
583 		if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
584 			uma_zfree_smr(cache_zone_small, ncp);
585 		else
586 			uma_zfree_smr(cache_zone_large, ncp);
587 	}
588 }
589 
590 static struct namecache *
591 cache_alloc(int len, bool ts)
592 {
593 	u_long lnumcache;
594 
595 	/*
596 	 * Avoid blowout in namecache entries.
597 	 *
598 	 * Bugs:
599 	 * 1. filesystems may end up trying to add an already existing entry
600 	 * (for example this can happen after a cache miss during concurrent
601 	 * lookup), in which case we will call cache_neg_evict despite not
602 	 * adding anything.
603 	 * 2. the routine may fail to free anything and no provisions are made
604 	 * to make it try harder (see the inside for failure modes)
605 	 * 3. it only ever looks at negative entries.
606 	 */
607 	lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
608 	if (cache_neg_evict_cond(lnumcache)) {
609 		lnumcache = atomic_load_long(&numcache);
610 	}
611 	if (__predict_false(lnumcache >= ncsize)) {
612 		atomic_subtract_long(&numcache, 1);
613 		counter_u64_add(numdrops, 1);
614 		return (NULL);
615 	}
616 	return (cache_alloc_uma(len, ts));
617 }
618 
619 static void
620 cache_free(struct namecache *ncp)
621 {
622 
623 	MPASS(ncp != NULL);
624 	if ((ncp->nc_flag & NCF_DVDROP) != 0) {
625 		cache_drop_vnode(ncp->nc_dvp);
626 	}
627 	cache_free_uma(ncp);
628 	atomic_subtract_long(&numcache, 1);
629 }
630 
631 static void
632 cache_free_batch(struct cache_freebatch *batch)
633 {
634 	struct namecache *ncp, *nnp;
635 	int i;
636 
637 	i = 0;
638 	if (TAILQ_EMPTY(batch))
639 		goto out;
640 	TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
641 		if ((ncp->nc_flag & NCF_DVDROP) != 0) {
642 			cache_drop_vnode(ncp->nc_dvp);
643 		}
644 		cache_free_uma(ncp);
645 		i++;
646 	}
647 	atomic_subtract_long(&numcache, i);
648 out:
649 	SDT_PROBE1(vfs, namecache, purge, batch, i);
650 }
651 
652 /*
653  * TODO: With the value stored we can do better than computing the hash based
654  * on the address. The choice of FNV should also be revisited.
655  */
656 static void
657 cache_prehash(struct vnode *vp)
658 {
659 
660 	vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
661 }
662 
663 static uint32_t
664 cache_get_hash(char *name, u_char len, struct vnode *dvp)
665 {
666 
667 	return (fnv_32_buf(name, len, dvp->v_nchash));
668 }
669 
670 static inline struct nchashhead *
671 NCP2BUCKET(struct namecache *ncp)
672 {
673 	uint32_t hash;
674 
675 	hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
676 	return (NCHHASH(hash));
677 }
678 
679 static inline struct mtx *
680 NCP2BUCKETLOCK(struct namecache *ncp)
681 {
682 	uint32_t hash;
683 
684 	hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
685 	return (HASH2BUCKETLOCK(hash));
686 }
687 
688 #ifdef INVARIANTS
689 static void
690 cache_assert_bucket_locked(struct namecache *ncp)
691 {
692 	struct mtx *blp;
693 
694 	blp = NCP2BUCKETLOCK(ncp);
695 	mtx_assert(blp, MA_OWNED);
696 }
697 
698 static void
699 cache_assert_bucket_unlocked(struct namecache *ncp)
700 {
701 	struct mtx *blp;
702 
703 	blp = NCP2BUCKETLOCK(ncp);
704 	mtx_assert(blp, MA_NOTOWNED);
705 }
706 #else
707 #define cache_assert_bucket_locked(x) do { } while (0)
708 #define cache_assert_bucket_unlocked(x) do { } while (0)
709 #endif
710 
711 #define cache_sort_vnodes(x, y)	_cache_sort_vnodes((void **)(x), (void **)(y))
712 static void
713 _cache_sort_vnodes(void **p1, void **p2)
714 {
715 	void *tmp;
716 
717 	MPASS(*p1 != NULL || *p2 != NULL);
718 
719 	if (*p1 > *p2) {
720 		tmp = *p2;
721 		*p2 = *p1;
722 		*p1 = tmp;
723 	}
724 }
725 
726 static void
727 cache_lock_all_buckets(void)
728 {
729 	u_int i;
730 
731 	for (i = 0; i < numbucketlocks; i++)
732 		mtx_lock(&bucketlocks[i]);
733 }
734 
735 static void
736 cache_unlock_all_buckets(void)
737 {
738 	u_int i;
739 
740 	for (i = 0; i < numbucketlocks; i++)
741 		mtx_unlock(&bucketlocks[i]);
742 }
743 
744 static void
745 cache_lock_all_vnodes(void)
746 {
747 	u_int i;
748 
749 	for (i = 0; i < numvnodelocks; i++)
750 		mtx_lock(&vnodelocks[i]);
751 }
752 
753 static void
754 cache_unlock_all_vnodes(void)
755 {
756 	u_int i;
757 
758 	for (i = 0; i < numvnodelocks; i++)
759 		mtx_unlock(&vnodelocks[i]);
760 }
761 
762 static int
763 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
764 {
765 
766 	cache_sort_vnodes(&vlp1, &vlp2);
767 
768 	if (vlp1 != NULL) {
769 		if (!mtx_trylock(vlp1))
770 			return (EAGAIN);
771 	}
772 	if (!mtx_trylock(vlp2)) {
773 		if (vlp1 != NULL)
774 			mtx_unlock(vlp1);
775 		return (EAGAIN);
776 	}
777 
778 	return (0);
779 }
780 
781 static void
782 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
783 {
784 
785 	MPASS(vlp1 != NULL || vlp2 != NULL);
786 	MPASS(vlp1 <= vlp2);
787 
788 	if (vlp1 != NULL)
789 		mtx_lock(vlp1);
790 	if (vlp2 != NULL)
791 		mtx_lock(vlp2);
792 }
793 
794 static void
795 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
796 {
797 
798 	MPASS(vlp1 != NULL || vlp2 != NULL);
799 
800 	if (vlp1 != NULL)
801 		mtx_unlock(vlp1);
802 	if (vlp2 != NULL)
803 		mtx_unlock(vlp2);
804 }
805 
806 static int
807 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
808 {
809 	struct nchstats snap;
810 
811 	if (req->oldptr == NULL)
812 		return (SYSCTL_OUT(req, 0, sizeof(snap)));
813 
814 	snap = nchstats;
815 	snap.ncs_goodhits = counter_u64_fetch(numposhits);
816 	snap.ncs_neghits = counter_u64_fetch(numneghits);
817 	snap.ncs_badhits = counter_u64_fetch(numposzaps) +
818 	    counter_u64_fetch(numnegzaps);
819 	snap.ncs_miss = counter_u64_fetch(nummisszap) +
820 	    counter_u64_fetch(nummiss);
821 
822 	return (SYSCTL_OUT(req, &snap, sizeof(snap)));
823 }
824 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
825     CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
826     "VFS cache effectiveness statistics");
827 
828 static void
829 cache_recalc_neg_min(u_int val)
830 {
831 
832 	neg_min = (ncsize * val) / 100;
833 }
834 
835 static int
836 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
837 {
838 	u_int val;
839 	int error;
840 
841 	val = ncnegminpct;
842 	error = sysctl_handle_int(oidp, &val, 0, req);
843 	if (error != 0 || req->newptr == NULL)
844 		return (error);
845 
846 	if (val == ncnegminpct)
847 		return (0);
848 	if (val < 0 || val > 99)
849 		return (EINVAL);
850 	ncnegminpct = val;
851 	cache_recalc_neg_min(val);
852 	return (0);
853 }
854 
855 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
856     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
857     "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
858 
859 #ifdef DIAGNOSTIC
860 /*
861  * Grab an atomic snapshot of the name cache hash chain lengths
862  */
863 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
864     CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
865     "hash table stats");
866 
867 static int
868 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
869 {
870 	struct nchashhead *ncpp;
871 	struct namecache *ncp;
872 	int i, error, n_nchash, *cntbuf;
873 
874 retry:
875 	n_nchash = nchash + 1;	/* nchash is max index, not count */
876 	if (req->oldptr == NULL)
877 		return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
878 	cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
879 	cache_lock_all_buckets();
880 	if (n_nchash != nchash + 1) {
881 		cache_unlock_all_buckets();
882 		free(cntbuf, M_TEMP);
883 		goto retry;
884 	}
885 	/* Scan hash tables counting entries */
886 	for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
887 		CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
888 			cntbuf[i]++;
889 	cache_unlock_all_buckets();
890 	for (error = 0, i = 0; i < n_nchash; i++)
891 		if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
892 			break;
893 	free(cntbuf, M_TEMP);
894 	return (error);
895 }
896 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
897     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
898     "nchash chain lengths");
899 
900 static int
901 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
902 {
903 	int error;
904 	struct nchashhead *ncpp;
905 	struct namecache *ncp;
906 	int n_nchash;
907 	int count, maxlength, used, pct;
908 
909 	if (!req->oldptr)
910 		return SYSCTL_OUT(req, 0, 4 * sizeof(int));
911 
912 	cache_lock_all_buckets();
913 	n_nchash = nchash + 1;	/* nchash is max index, not count */
914 	used = 0;
915 	maxlength = 0;
916 
917 	/* Scan hash tables for applicable entries */
918 	for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
919 		count = 0;
920 		CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
921 			count++;
922 		}
923 		if (count)
924 			used++;
925 		if (maxlength < count)
926 			maxlength = count;
927 	}
928 	n_nchash = nchash + 1;
929 	cache_unlock_all_buckets();
930 	pct = (used * 100) / (n_nchash / 100);
931 	error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
932 	if (error)
933 		return (error);
934 	error = SYSCTL_OUT(req, &used, sizeof(used));
935 	if (error)
936 		return (error);
937 	error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
938 	if (error)
939 		return (error);
940 	error = SYSCTL_OUT(req, &pct, sizeof(pct));
941 	if (error)
942 		return (error);
943 	return (0);
944 }
945 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
946     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
947     "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
948 #endif
949 
950 /*
951  * Negative entries management
952  *
953  * Various workloads create plenty of negative entries and barely use them
954  * afterwards. Moreover malicious users can keep performing bogus lookups
955  * adding even more entries. For example "make tinderbox" as of writing this
956  * comment ends up with 2.6M namecache entries in total, 1.2M of which are
957  * negative.
958  *
959  * As such, a rather aggressive eviction method is needed. The currently
960  * employed method is a placeholder.
961  *
962  * Entries are split over numneglists separate lists, each of which is further
963  * split into hot and cold entries. Entries get promoted after getting a hit.
964  * Eviction happens on addition of new entry.
965  */
966 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
967     "Name cache negative entry statistics");
968 
969 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
970     "Number of negative cache entries");
971 
972 static COUNTER_U64_DEFINE_EARLY(neg_created);
973 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
974     "Number of created negative entries");
975 
976 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
977 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
978     "Number of evicted negative entries");
979 
980 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
981 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
982     &neg_evict_skipped_empty,
983     "Number of times evicting failed due to lack of entries");
984 
985 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
986 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
987     &neg_evict_skipped_missed,
988     "Number of times evicting failed due to target entry disappearing");
989 
990 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
991 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
992     &neg_evict_skipped_contended,
993     "Number of times evicting failed due to contention");
994 
995 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
996     "Number of cache hits (negative)");
997 
998 static int
999 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1000 {
1001 	int i, out;
1002 
1003 	out = 0;
1004 	for (i = 0; i < numneglists; i++)
1005 		out += neglists[i].nl_hotnum;
1006 
1007 	return (SYSCTL_OUT(req, &out, sizeof(out)));
1008 }
1009 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1010     CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1011     "Number of hot negative entries");
1012 
1013 static void
1014 cache_neg_init(struct namecache *ncp)
1015 {
1016 	struct negstate *ns;
1017 
1018 	ncp->nc_flag |= NCF_NEGATIVE;
1019 	ns = NCP2NEGSTATE(ncp);
1020 	ns->neg_flag = 0;
1021 	ns->neg_hit = 0;
1022 	counter_u64_add(neg_created, 1);
1023 }
1024 
1025 #define CACHE_NEG_PROMOTION_THRESH 2
1026 
1027 static bool
1028 cache_neg_hit_prep(struct namecache *ncp)
1029 {
1030 	struct negstate *ns;
1031 	u_char n;
1032 
1033 	ns = NCP2NEGSTATE(ncp);
1034 	n = atomic_load_char(&ns->neg_hit);
1035 	for (;;) {
1036 		if (n >= CACHE_NEG_PROMOTION_THRESH)
1037 			return (false);
1038 		if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1039 			break;
1040 	}
1041 	return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1042 }
1043 
1044 /*
1045  * Nothing to do here but it is provided for completeness as some
1046  * cache_neg_hit_prep callers may end up returning without even
1047  * trying to promote.
1048  */
1049 #define cache_neg_hit_abort(ncp)	do { } while (0)
1050 
1051 static void
1052 cache_neg_hit_finish(struct namecache *ncp)
1053 {
1054 
1055 	SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1056 	counter_u64_add(numneghits, 1);
1057 }
1058 
1059 /*
1060  * Move a negative entry to the hot list.
1061  */
1062 static void
1063 cache_neg_promote_locked(struct namecache *ncp)
1064 {
1065 	struct neglist *nl;
1066 	struct negstate *ns;
1067 
1068 	ns = NCP2NEGSTATE(ncp);
1069 	nl = NCP2NEGLIST(ncp);
1070 	mtx_assert(&nl->nl_lock, MA_OWNED);
1071 	if ((ns->neg_flag & NEG_HOT) == 0) {
1072 		TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1073 		TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1074 		nl->nl_hotnum++;
1075 		ns->neg_flag |= NEG_HOT;
1076 	}
1077 }
1078 
1079 /*
1080  * Move a hot negative entry to the cold list.
1081  */
1082 static void
1083 cache_neg_demote_locked(struct namecache *ncp)
1084 {
1085 	struct neglist *nl;
1086 	struct negstate *ns;
1087 
1088 	ns = NCP2NEGSTATE(ncp);
1089 	nl = NCP2NEGLIST(ncp);
1090 	mtx_assert(&nl->nl_lock, MA_OWNED);
1091 	MPASS(ns->neg_flag & NEG_HOT);
1092 	TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1093 	TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1094 	nl->nl_hotnum--;
1095 	ns->neg_flag &= ~NEG_HOT;
1096 	atomic_store_char(&ns->neg_hit, 0);
1097 }
1098 
1099 /*
1100  * Move a negative entry to the hot list if it matches the lookup.
1101  *
1102  * We have to take locks, but they may be contended and in the worst
1103  * case we may need to go off CPU. We don't want to spin within the
1104  * smr section and we can't block with it. Exiting the section means
1105  * the found entry could have been evicted. We are going to look it
1106  * up again.
1107  */
1108 static bool
1109 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1110     struct namecache *oncp, uint32_t hash)
1111 {
1112 	struct namecache *ncp;
1113 	struct neglist *nl;
1114 	u_char nc_flag;
1115 
1116 	nl = NCP2NEGLIST(oncp);
1117 
1118 	mtx_lock(&nl->nl_lock);
1119 	/*
1120 	 * For hash iteration.
1121 	 */
1122 	vfs_smr_enter();
1123 
1124 	/*
1125 	 * Avoid all surprises by only succeeding if we got the same entry and
1126 	 * bailing completely otherwise.
1127 	 * XXX There are no provisions to keep the vnode around, meaning we may
1128 	 * end up promoting a negative entry for a *new* vnode and returning
1129 	 * ENOENT on its account. This is the error we want to return anyway
1130 	 * and promotion is harmless.
1131 	 *
1132 	 * In particular at this point there can be a new ncp which matches the
1133 	 * search but hashes to a different neglist.
1134 	 */
1135 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1136 		if (ncp == oncp)
1137 			break;
1138 	}
1139 
1140 	/*
1141 	 * No match to begin with.
1142 	 */
1143 	if (__predict_false(ncp == NULL)) {
1144 		goto out_abort;
1145 	}
1146 
1147 	/*
1148 	 * The newly found entry may be something different...
1149 	 */
1150 	if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1151 	    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1152 		goto out_abort;
1153 	}
1154 
1155 	/*
1156 	 * ... and not even negative.
1157 	 */
1158 	nc_flag = atomic_load_char(&ncp->nc_flag);
1159 	if ((nc_flag & NCF_NEGATIVE) == 0) {
1160 		goto out_abort;
1161 	}
1162 
1163 	if (!cache_ncp_canuse(ncp)) {
1164 		goto out_abort;
1165 	}
1166 
1167 	cache_neg_promote_locked(ncp);
1168 	cache_neg_hit_finish(ncp);
1169 	vfs_smr_exit();
1170 	mtx_unlock(&nl->nl_lock);
1171 	return (true);
1172 out_abort:
1173 	vfs_smr_exit();
1174 	mtx_unlock(&nl->nl_lock);
1175 	return (false);
1176 }
1177 
1178 static void
1179 cache_neg_promote(struct namecache *ncp)
1180 {
1181 	struct neglist *nl;
1182 
1183 	nl = NCP2NEGLIST(ncp);
1184 	mtx_lock(&nl->nl_lock);
1185 	cache_neg_promote_locked(ncp);
1186 	mtx_unlock(&nl->nl_lock);
1187 }
1188 
1189 static void
1190 cache_neg_insert(struct namecache *ncp)
1191 {
1192 	struct neglist *nl;
1193 
1194 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
1195 	cache_assert_bucket_locked(ncp);
1196 	nl = NCP2NEGLIST(ncp);
1197 	mtx_lock(&nl->nl_lock);
1198 	TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1199 	mtx_unlock(&nl->nl_lock);
1200 	atomic_add_long(&numneg, 1);
1201 }
1202 
1203 static void
1204 cache_neg_remove(struct namecache *ncp)
1205 {
1206 	struct neglist *nl;
1207 	struct negstate *ns;
1208 
1209 	cache_assert_bucket_locked(ncp);
1210 	nl = NCP2NEGLIST(ncp);
1211 	ns = NCP2NEGSTATE(ncp);
1212 	mtx_lock(&nl->nl_lock);
1213 	if ((ns->neg_flag & NEG_HOT) != 0) {
1214 		TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1215 		nl->nl_hotnum--;
1216 	} else {
1217 		TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1218 	}
1219 	mtx_unlock(&nl->nl_lock);
1220 	atomic_subtract_long(&numneg, 1);
1221 }
1222 
1223 static struct neglist *
1224 cache_neg_evict_select_list(void)
1225 {
1226 	struct neglist *nl;
1227 	u_int c;
1228 
1229 	c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1230 	nl = &neglists[c % numneglists];
1231 	if (!mtx_trylock(&nl->nl_evict_lock)) {
1232 		counter_u64_add(neg_evict_skipped_contended, 1);
1233 		return (NULL);
1234 	}
1235 	return (nl);
1236 }
1237 
1238 static struct namecache *
1239 cache_neg_evict_select_entry(struct neglist *nl)
1240 {
1241 	struct namecache *ncp, *lncp;
1242 	struct negstate *ns, *lns;
1243 	int i;
1244 
1245 	mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1246 	mtx_assert(&nl->nl_lock, MA_OWNED);
1247 	ncp = TAILQ_FIRST(&nl->nl_list);
1248 	if (ncp == NULL)
1249 		return (NULL);
1250 	lncp = ncp;
1251 	lns = NCP2NEGSTATE(lncp);
1252 	for (i = 1; i < 4; i++) {
1253 		ncp = TAILQ_NEXT(ncp, nc_dst);
1254 		if (ncp == NULL)
1255 			break;
1256 		ns = NCP2NEGSTATE(ncp);
1257 		if (ns->neg_hit < lns->neg_hit) {
1258 			lncp = ncp;
1259 			lns = ns;
1260 		}
1261 	}
1262 	return (lncp);
1263 }
1264 
1265 static bool
1266 cache_neg_evict(void)
1267 {
1268 	struct namecache *ncp, *ncp2;
1269 	struct neglist *nl;
1270 	struct vnode *dvp;
1271 	struct mtx *dvlp;
1272 	struct mtx *blp;
1273 	uint32_t hash;
1274 	u_char nlen;
1275 	bool evicted;
1276 
1277 	nl = cache_neg_evict_select_list();
1278 	if (nl == NULL) {
1279 		return (false);
1280 	}
1281 
1282 	mtx_lock(&nl->nl_lock);
1283 	ncp = TAILQ_FIRST(&nl->nl_hotlist);
1284 	if (ncp != NULL) {
1285 		cache_neg_demote_locked(ncp);
1286 	}
1287 	ncp = cache_neg_evict_select_entry(nl);
1288 	if (ncp == NULL) {
1289 		counter_u64_add(neg_evict_skipped_empty, 1);
1290 		mtx_unlock(&nl->nl_lock);
1291 		mtx_unlock(&nl->nl_evict_lock);
1292 		return (false);
1293 	}
1294 	nlen = ncp->nc_nlen;
1295 	dvp = ncp->nc_dvp;
1296 	hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1297 	dvlp = VP2VNODELOCK(dvp);
1298 	blp = HASH2BUCKETLOCK(hash);
1299 	mtx_unlock(&nl->nl_lock);
1300 	mtx_unlock(&nl->nl_evict_lock);
1301 	mtx_lock(dvlp);
1302 	mtx_lock(blp);
1303 	/*
1304 	 * Note that since all locks were dropped above, the entry may be
1305 	 * gone or reallocated to be something else.
1306 	 */
1307 	CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1308 		if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1309 		    ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1310 			break;
1311 	}
1312 	if (ncp2 == NULL) {
1313 		counter_u64_add(neg_evict_skipped_missed, 1);
1314 		ncp = NULL;
1315 		evicted = false;
1316 	} else {
1317 		MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1318 		MPASS(blp == NCP2BUCKETLOCK(ncp));
1319 		SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1320 		    ncp->nc_name);
1321 		cache_zap_locked(ncp);
1322 		counter_u64_add(neg_evicted, 1);
1323 		evicted = true;
1324 	}
1325 	mtx_unlock(blp);
1326 	mtx_unlock(dvlp);
1327 	if (ncp != NULL)
1328 		cache_free(ncp);
1329 	return (evicted);
1330 }
1331 
1332 /*
1333  * Maybe evict a negative entry to create more room.
1334  *
1335  * The ncnegfactor parameter limits what fraction of the total count
1336  * can comprise of negative entries. However, if the cache is just
1337  * warming up this leads to excessive evictions.  As such, ncnegminpct
1338  * (recomputed to neg_min) dictates whether the above should be
1339  * applied.
1340  *
1341  * Try evicting if the cache is close to full capacity regardless of
1342  * other considerations.
1343  */
1344 static bool
1345 cache_neg_evict_cond(u_long lnumcache)
1346 {
1347 	u_long lnumneg;
1348 
1349 	if (ncsize - 1000 < lnumcache)
1350 		goto out_evict;
1351 	lnumneg = atomic_load_long(&numneg);
1352 	if (lnumneg < neg_min)
1353 		return (false);
1354 	if (lnumneg * ncnegfactor < lnumcache)
1355 		return (false);
1356 out_evict:
1357 	return (cache_neg_evict());
1358 }
1359 
1360 /*
1361  * cache_zap_locked():
1362  *
1363  *   Removes a namecache entry from cache, whether it contains an actual
1364  *   pointer to a vnode or if it is just a negative cache entry.
1365  */
1366 static void
1367 cache_zap_locked(struct namecache *ncp)
1368 {
1369 	struct nchashhead *ncpp;
1370 
1371 	if (!(ncp->nc_flag & NCF_NEGATIVE))
1372 		cache_assert_vnode_locked(ncp->nc_vp);
1373 	cache_assert_vnode_locked(ncp->nc_dvp);
1374 	cache_assert_bucket_locked(ncp);
1375 
1376 	cache_ncp_invalidate(ncp);
1377 
1378 	ncpp = NCP2BUCKET(ncp);
1379 	CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1380 	if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1381 		SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
1382 		    ncp->nc_name, ncp->nc_vp);
1383 		TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
1384 		if (ncp == ncp->nc_vp->v_cache_dd) {
1385 			vn_seqc_write_begin_unheld(ncp->nc_vp);
1386 			ncp->nc_vp->v_cache_dd = NULL;
1387 			vn_seqc_write_end(ncp->nc_vp);
1388 		}
1389 	} else {
1390 		SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
1391 		    ncp->nc_name);
1392 		cache_neg_remove(ncp);
1393 	}
1394 	if (ncp->nc_flag & NCF_ISDOTDOT) {
1395 		if (ncp == ncp->nc_dvp->v_cache_dd) {
1396 			vn_seqc_write_begin_unheld(ncp->nc_dvp);
1397 			ncp->nc_dvp->v_cache_dd = NULL;
1398 			vn_seqc_write_end(ncp->nc_dvp);
1399 		}
1400 	} else {
1401 		LIST_REMOVE(ncp, nc_src);
1402 		if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
1403 			ncp->nc_flag |= NCF_DVDROP;
1404 		}
1405 	}
1406 }
1407 
1408 static void
1409 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1410 {
1411 	struct mtx *blp;
1412 
1413 	MPASS(ncp->nc_dvp == vp);
1414 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
1415 	cache_assert_vnode_locked(vp);
1416 
1417 	blp = NCP2BUCKETLOCK(ncp);
1418 	mtx_lock(blp);
1419 	cache_zap_locked(ncp);
1420 	mtx_unlock(blp);
1421 }
1422 
1423 static bool
1424 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1425     struct mtx **vlpp)
1426 {
1427 	struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1428 	struct mtx *blp;
1429 
1430 	MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1431 	cache_assert_vnode_locked(vp);
1432 
1433 	if (ncp->nc_flag & NCF_NEGATIVE) {
1434 		if (*vlpp != NULL) {
1435 			mtx_unlock(*vlpp);
1436 			*vlpp = NULL;
1437 		}
1438 		cache_zap_negative_locked_vnode_kl(ncp, vp);
1439 		return (true);
1440 	}
1441 
1442 	pvlp = VP2VNODELOCK(vp);
1443 	blp = NCP2BUCKETLOCK(ncp);
1444 	vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1445 	vlp2 = VP2VNODELOCK(ncp->nc_vp);
1446 
1447 	if (*vlpp == vlp1 || *vlpp == vlp2) {
1448 		to_unlock = *vlpp;
1449 		*vlpp = NULL;
1450 	} else {
1451 		if (*vlpp != NULL) {
1452 			mtx_unlock(*vlpp);
1453 			*vlpp = NULL;
1454 		}
1455 		cache_sort_vnodes(&vlp1, &vlp2);
1456 		if (vlp1 == pvlp) {
1457 			mtx_lock(vlp2);
1458 			to_unlock = vlp2;
1459 		} else {
1460 			if (!mtx_trylock(vlp1))
1461 				goto out_relock;
1462 			to_unlock = vlp1;
1463 		}
1464 	}
1465 	mtx_lock(blp);
1466 	cache_zap_locked(ncp);
1467 	mtx_unlock(blp);
1468 	if (to_unlock != NULL)
1469 		mtx_unlock(to_unlock);
1470 	return (true);
1471 
1472 out_relock:
1473 	mtx_unlock(vlp2);
1474 	mtx_lock(vlp1);
1475 	mtx_lock(vlp2);
1476 	MPASS(*vlpp == NULL);
1477 	*vlpp = vlp1;
1478 	return (false);
1479 }
1480 
1481 /*
1482  * If trylocking failed we can get here. We know enough to take all needed locks
1483  * in the right order and re-lookup the entry.
1484  */
1485 static int
1486 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1487     struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1488     struct mtx *blp)
1489 {
1490 	struct namecache *rncp;
1491 
1492 	cache_assert_bucket_unlocked(ncp);
1493 
1494 	cache_sort_vnodes(&dvlp, &vlp);
1495 	cache_lock_vnodes(dvlp, vlp);
1496 	mtx_lock(blp);
1497 	CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1498 		if (rncp == ncp && rncp->nc_dvp == dvp &&
1499 		    rncp->nc_nlen == cnp->cn_namelen &&
1500 		    !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1501 			break;
1502 	}
1503 	if (rncp != NULL) {
1504 		cache_zap_locked(rncp);
1505 		mtx_unlock(blp);
1506 		cache_unlock_vnodes(dvlp, vlp);
1507 		counter_u64_add(zap_bucket_relock_success, 1);
1508 		return (0);
1509 	}
1510 
1511 	mtx_unlock(blp);
1512 	cache_unlock_vnodes(dvlp, vlp);
1513 	return (EAGAIN);
1514 }
1515 
1516 static int __noinline
1517 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1518     uint32_t hash, struct mtx *blp)
1519 {
1520 	struct mtx *dvlp, *vlp;
1521 	struct vnode *dvp;
1522 
1523 	cache_assert_bucket_locked(ncp);
1524 
1525 	dvlp = VP2VNODELOCK(ncp->nc_dvp);
1526 	vlp = NULL;
1527 	if (!(ncp->nc_flag & NCF_NEGATIVE))
1528 		vlp = VP2VNODELOCK(ncp->nc_vp);
1529 	if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1530 		cache_zap_locked(ncp);
1531 		mtx_unlock(blp);
1532 		cache_unlock_vnodes(dvlp, vlp);
1533 		return (0);
1534 	}
1535 
1536 	dvp = ncp->nc_dvp;
1537 	mtx_unlock(blp);
1538 	return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1539 }
1540 
1541 static __noinline int
1542 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1543 {
1544 	struct namecache *ncp;
1545 	struct mtx *blp;
1546 	struct mtx *dvlp, *dvlp2;
1547 	uint32_t hash;
1548 	int error;
1549 
1550 	if (cnp->cn_namelen == 2 &&
1551 	    cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1552 		dvlp = VP2VNODELOCK(dvp);
1553 		dvlp2 = NULL;
1554 		mtx_lock(dvlp);
1555 retry_dotdot:
1556 		ncp = dvp->v_cache_dd;
1557 		if (ncp == NULL) {
1558 			mtx_unlock(dvlp);
1559 			if (dvlp2 != NULL)
1560 				mtx_unlock(dvlp2);
1561 			SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1562 			return (0);
1563 		}
1564 		if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1565 			if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1566 				goto retry_dotdot;
1567 			MPASS(dvp->v_cache_dd == NULL);
1568 			mtx_unlock(dvlp);
1569 			if (dvlp2 != NULL)
1570 				mtx_unlock(dvlp2);
1571 			cache_free(ncp);
1572 		} else {
1573 			vn_seqc_write_begin(dvp);
1574 			dvp->v_cache_dd = NULL;
1575 			vn_seqc_write_end(dvp);
1576 			mtx_unlock(dvlp);
1577 			if (dvlp2 != NULL)
1578 				mtx_unlock(dvlp2);
1579 		}
1580 		SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1581 		return (1);
1582 	}
1583 
1584 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1585 	blp = HASH2BUCKETLOCK(hash);
1586 retry:
1587 	if (CK_SLIST_EMPTY(NCHHASH(hash)))
1588 		goto out_no_entry;
1589 
1590 	mtx_lock(blp);
1591 
1592 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1593 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1594 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1595 			break;
1596 	}
1597 
1598 	if (ncp == NULL) {
1599 		mtx_unlock(blp);
1600 		goto out_no_entry;
1601 	}
1602 
1603 	error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1604 	if (__predict_false(error != 0)) {
1605 		zap_bucket_fail++;
1606 		goto retry;
1607 	}
1608 	counter_u64_add(numposzaps, 1);
1609 	SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1610 	cache_free(ncp);
1611 	return (1);
1612 out_no_entry:
1613 	counter_u64_add(nummisszap, 1);
1614 	SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1615 	return (0);
1616 }
1617 
1618 static int __noinline
1619 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1620     struct timespec *tsp, int *ticksp)
1621 {
1622 	int ltype;
1623 
1624 	*vpp = dvp;
1625 	counter_u64_add(dothits, 1);
1626 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1627 	if (tsp != NULL)
1628 		timespecclear(tsp);
1629 	if (ticksp != NULL)
1630 		*ticksp = ticks;
1631 	vrefact(*vpp);
1632 	/*
1633 	 * When we lookup "." we still can be asked to lock it
1634 	 * differently...
1635 	 */
1636 	ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1637 	if (ltype != VOP_ISLOCKED(*vpp)) {
1638 		if (ltype == LK_EXCLUSIVE) {
1639 			vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1640 			if (VN_IS_DOOMED((*vpp))) {
1641 				/* forced unmount */
1642 				vrele(*vpp);
1643 				*vpp = NULL;
1644 				return (ENOENT);
1645 			}
1646 		} else
1647 			vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1648 	}
1649 	return (-1);
1650 }
1651 
1652 static int __noinline
1653 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1654     struct timespec *tsp, int *ticksp)
1655 {
1656 	struct namecache_ts *ncp_ts;
1657 	struct namecache *ncp;
1658 	struct mtx *dvlp;
1659 	enum vgetstate vs;
1660 	int error, ltype;
1661 	bool whiteout;
1662 
1663 	MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1664 
1665 	if ((cnp->cn_flags & MAKEENTRY) == 0) {
1666 		cache_remove_cnp(dvp, cnp);
1667 		return (0);
1668 	}
1669 
1670 	counter_u64_add(dotdothits, 1);
1671 retry:
1672 	dvlp = VP2VNODELOCK(dvp);
1673 	mtx_lock(dvlp);
1674 	ncp = dvp->v_cache_dd;
1675 	if (ncp == NULL) {
1676 		SDT_PROBE3(vfs, namecache, lookup, miss, dvp, "..", NULL);
1677 		mtx_unlock(dvlp);
1678 		return (0);
1679 	}
1680 	if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1681 		if (ncp->nc_flag & NCF_NEGATIVE)
1682 			*vpp = NULL;
1683 		else
1684 			*vpp = ncp->nc_vp;
1685 	} else
1686 		*vpp = ncp->nc_dvp;
1687 	if (*vpp == NULL)
1688 		goto negative_success;
1689 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1690 	cache_out_ts(ncp, tsp, ticksp);
1691 	if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1692 	    NCF_DTS && tsp != NULL) {
1693 		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1694 		*tsp = ncp_ts->nc_dotdottime;
1695 	}
1696 
1697 	MPASS(dvp != *vpp);
1698 	ltype = VOP_ISLOCKED(dvp);
1699 	VOP_UNLOCK(dvp);
1700 	vs = vget_prep(*vpp);
1701 	mtx_unlock(dvlp);
1702 	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1703 	vn_lock(dvp, ltype | LK_RETRY);
1704 	if (VN_IS_DOOMED(dvp)) {
1705 		if (error == 0)
1706 			vput(*vpp);
1707 		*vpp = NULL;
1708 		return (ENOENT);
1709 	}
1710 	if (error) {
1711 		*vpp = NULL;
1712 		goto retry;
1713 	}
1714 	return (-1);
1715 negative_success:
1716 	if (__predict_false(cnp->cn_nameiop == CREATE)) {
1717 		if (cnp->cn_flags & ISLASTCN) {
1718 			counter_u64_add(numnegzaps, 1);
1719 			cache_zap_negative_locked_vnode_kl(ncp, dvp);
1720 			mtx_unlock(dvlp);
1721 			cache_free(ncp);
1722 			return (0);
1723 		}
1724 	}
1725 
1726 	whiteout = (ncp->nc_flag & NCF_WHITE);
1727 	cache_out_ts(ncp, tsp, ticksp);
1728 	if (cache_neg_hit_prep(ncp))
1729 		cache_neg_promote(ncp);
1730 	else
1731 		cache_neg_hit_finish(ncp);
1732 	mtx_unlock(dvlp);
1733 	if (whiteout)
1734 		cnp->cn_flags |= ISWHITEOUT;
1735 	return (ENOENT);
1736 }
1737 
1738 /**
1739  * Lookup a name in the name cache
1740  *
1741  * # Arguments
1742  *
1743  * - dvp:	Parent directory in which to search.
1744  * - vpp:	Return argument.  Will contain desired vnode on cache hit.
1745  * - cnp:	Parameters of the name search.  The most interesting bits of
1746  *   		the cn_flags field have the following meanings:
1747  *   	- MAKEENTRY:	If clear, free an entry from the cache rather than look
1748  *   			it up.
1749  *   	- ISDOTDOT:	Must be set if and only if cn_nameptr == ".."
1750  * - tsp:	Return storage for cache timestamp.  On a successful (positive
1751  *   		or negative) lookup, tsp will be filled with any timespec that
1752  *   		was stored when this cache entry was created.  However, it will
1753  *   		be clear for "." entries.
1754  * - ticks:	Return storage for alternate cache timestamp.  On a successful
1755  *   		(positive or negative) lookup, it will contain the ticks value
1756  *   		that was current when the cache entry was created, unless cnp
1757  *   		was ".".
1758  *
1759  * Either both tsp and ticks have to be provided or neither of them.
1760  *
1761  * # Returns
1762  *
1763  * - -1:	A positive cache hit.  vpp will contain the desired vnode.
1764  * - ENOENT:	A negative cache hit, or dvp was recycled out from under us due
1765  *		to a forced unmount.  vpp will not be modified.  If the entry
1766  *		is a whiteout, then the ISWHITEOUT flag will be set in
1767  *		cnp->cn_flags.
1768  * - 0:		A cache miss.  vpp will not be modified.
1769  *
1770  * # Locking
1771  *
1772  * On a cache hit, vpp will be returned locked and ref'd.  If we're looking up
1773  * .., dvp is unlocked.  If we're looking up . an extra ref is taken, but the
1774  * lock is not recursively acquired.
1775  */
1776 static int __noinline
1777 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1778     struct timespec *tsp, int *ticksp)
1779 {
1780 	struct namecache *ncp;
1781 	struct mtx *blp;
1782 	uint32_t hash;
1783 	enum vgetstate vs;
1784 	int error;
1785 	bool whiteout;
1786 
1787 	MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1788 	MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1789 
1790 retry:
1791 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1792 	blp = HASH2BUCKETLOCK(hash);
1793 	mtx_lock(blp);
1794 
1795 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1796 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1797 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1798 			break;
1799 	}
1800 
1801 	if (__predict_false(ncp == NULL)) {
1802 		mtx_unlock(blp);
1803 		SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1804 		    NULL);
1805 		counter_u64_add(nummiss, 1);
1806 		return (0);
1807 	}
1808 
1809 	if (ncp->nc_flag & NCF_NEGATIVE)
1810 		goto negative_success;
1811 
1812 	counter_u64_add(numposhits, 1);
1813 	*vpp = ncp->nc_vp;
1814 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1815 	cache_out_ts(ncp, tsp, ticksp);
1816 	MPASS(dvp != *vpp);
1817 	vs = vget_prep(*vpp);
1818 	mtx_unlock(blp);
1819 	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1820 	if (error) {
1821 		*vpp = NULL;
1822 		goto retry;
1823 	}
1824 	return (-1);
1825 negative_success:
1826 	/*
1827 	 * We don't get here with regular lookup apart from corner cases.
1828 	 */
1829 	if (__predict_true(cnp->cn_nameiop == CREATE)) {
1830 		if (cnp->cn_flags & ISLASTCN) {
1831 			counter_u64_add(numnegzaps, 1);
1832 			error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1833 			if (__predict_false(error != 0)) {
1834 				zap_bucket_fail2++;
1835 				goto retry;
1836 			}
1837 			cache_free(ncp);
1838 			return (0);
1839 		}
1840 	}
1841 
1842 	whiteout = (ncp->nc_flag & NCF_WHITE);
1843 	cache_out_ts(ncp, tsp, ticksp);
1844 	if (cache_neg_hit_prep(ncp))
1845 		cache_neg_promote(ncp);
1846 	else
1847 		cache_neg_hit_finish(ncp);
1848 	mtx_unlock(blp);
1849 	if (whiteout)
1850 		cnp->cn_flags |= ISWHITEOUT;
1851 	return (ENOENT);
1852 }
1853 
1854 int
1855 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1856     struct timespec *tsp, int *ticksp)
1857 {
1858 	struct namecache *ncp;
1859 	uint32_t hash;
1860 	enum vgetstate vs;
1861 	int error;
1862 	bool whiteout, neg_promote;
1863 	u_short nc_flag;
1864 
1865 	MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
1866 
1867 #ifdef DEBUG_CACHE
1868 	if (__predict_false(!doingcache)) {
1869 		cnp->cn_flags &= ~MAKEENTRY;
1870 		return (0);
1871 	}
1872 #endif
1873 
1874 	if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1875 		if (cnp->cn_namelen == 1)
1876 			return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1877 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
1878 			return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
1879 	}
1880 
1881 	MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1882 
1883 	if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
1884 		cache_remove_cnp(dvp, cnp);
1885 		return (0);
1886 	}
1887 
1888 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1889 	vfs_smr_enter();
1890 
1891 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1892 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1893 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1894 			break;
1895 	}
1896 
1897 	if (__predict_false(ncp == NULL)) {
1898 		vfs_smr_exit();
1899 		SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1900 		    NULL);
1901 		counter_u64_add(nummiss, 1);
1902 		return (0);
1903 	}
1904 
1905 	nc_flag = atomic_load_char(&ncp->nc_flag);
1906 	if (nc_flag & NCF_NEGATIVE)
1907 		goto negative_success;
1908 
1909 	counter_u64_add(numposhits, 1);
1910 	*vpp = ncp->nc_vp;
1911 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1912 	cache_out_ts(ncp, tsp, ticksp);
1913 	MPASS(dvp != *vpp);
1914 	if (!cache_ncp_canuse(ncp)) {
1915 		vfs_smr_exit();
1916 		*vpp = NULL;
1917 		goto out_fallback;
1918 	}
1919 	vs = vget_prep_smr(*vpp);
1920 	vfs_smr_exit();
1921 	if (__predict_false(vs == VGET_NONE)) {
1922 		*vpp = NULL;
1923 		goto out_fallback;
1924 	}
1925 	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1926 	if (error) {
1927 		*vpp = NULL;
1928 		goto out_fallback;
1929 	}
1930 	return (-1);
1931 negative_success:
1932 	if (cnp->cn_nameiop == CREATE) {
1933 		if (cnp->cn_flags & ISLASTCN) {
1934 			vfs_smr_exit();
1935 			goto out_fallback;
1936 		}
1937 	}
1938 
1939 	cache_out_ts(ncp, tsp, ticksp);
1940 	whiteout = (ncp->nc_flag & NCF_WHITE);
1941 	neg_promote = cache_neg_hit_prep(ncp);
1942 	if (!cache_ncp_canuse(ncp)) {
1943 		cache_neg_hit_abort(ncp);
1944 		vfs_smr_exit();
1945 		goto out_fallback;
1946 	}
1947 	if (neg_promote) {
1948 		vfs_smr_exit();
1949 		if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
1950 			goto out_fallback;
1951 	} else {
1952 		cache_neg_hit_finish(ncp);
1953 		vfs_smr_exit();
1954 	}
1955 	if (whiteout)
1956 		cnp->cn_flags |= ISWHITEOUT;
1957 	return (ENOENT);
1958 out_fallback:
1959 	return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
1960 }
1961 
1962 struct celockstate {
1963 	struct mtx *vlp[3];
1964 	struct mtx *blp[2];
1965 };
1966 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1967 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1968 
1969 static inline void
1970 cache_celockstate_init(struct celockstate *cel)
1971 {
1972 
1973 	bzero(cel, sizeof(*cel));
1974 }
1975 
1976 static void
1977 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1978     struct vnode *dvp)
1979 {
1980 	struct mtx *vlp1, *vlp2;
1981 
1982 	MPASS(cel->vlp[0] == NULL);
1983 	MPASS(cel->vlp[1] == NULL);
1984 	MPASS(cel->vlp[2] == NULL);
1985 
1986 	MPASS(vp != NULL || dvp != NULL);
1987 
1988 	vlp1 = VP2VNODELOCK(vp);
1989 	vlp2 = VP2VNODELOCK(dvp);
1990 	cache_sort_vnodes(&vlp1, &vlp2);
1991 
1992 	if (vlp1 != NULL) {
1993 		mtx_lock(vlp1);
1994 		cel->vlp[0] = vlp1;
1995 	}
1996 	mtx_lock(vlp2);
1997 	cel->vlp[1] = vlp2;
1998 }
1999 
2000 static void
2001 cache_unlock_vnodes_cel(struct celockstate *cel)
2002 {
2003 
2004 	MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2005 
2006 	if (cel->vlp[0] != NULL)
2007 		mtx_unlock(cel->vlp[0]);
2008 	if (cel->vlp[1] != NULL)
2009 		mtx_unlock(cel->vlp[1]);
2010 	if (cel->vlp[2] != NULL)
2011 		mtx_unlock(cel->vlp[2]);
2012 }
2013 
2014 static bool
2015 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2016 {
2017 	struct mtx *vlp;
2018 	bool ret;
2019 
2020 	cache_assert_vlp_locked(cel->vlp[0]);
2021 	cache_assert_vlp_locked(cel->vlp[1]);
2022 	MPASS(cel->vlp[2] == NULL);
2023 
2024 	MPASS(vp != NULL);
2025 	vlp = VP2VNODELOCK(vp);
2026 
2027 	ret = true;
2028 	if (vlp >= cel->vlp[1]) {
2029 		mtx_lock(vlp);
2030 	} else {
2031 		if (mtx_trylock(vlp))
2032 			goto out;
2033 		cache_lock_vnodes_cel_3_failures++;
2034 		cache_unlock_vnodes_cel(cel);
2035 		if (vlp < cel->vlp[0]) {
2036 			mtx_lock(vlp);
2037 			mtx_lock(cel->vlp[0]);
2038 			mtx_lock(cel->vlp[1]);
2039 		} else {
2040 			if (cel->vlp[0] != NULL)
2041 				mtx_lock(cel->vlp[0]);
2042 			mtx_lock(vlp);
2043 			mtx_lock(cel->vlp[1]);
2044 		}
2045 		ret = false;
2046 	}
2047 out:
2048 	cel->vlp[2] = vlp;
2049 	return (ret);
2050 }
2051 
2052 static void
2053 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2054     struct mtx *blp2)
2055 {
2056 
2057 	MPASS(cel->blp[0] == NULL);
2058 	MPASS(cel->blp[1] == NULL);
2059 
2060 	cache_sort_vnodes(&blp1, &blp2);
2061 
2062 	if (blp1 != NULL) {
2063 		mtx_lock(blp1);
2064 		cel->blp[0] = blp1;
2065 	}
2066 	mtx_lock(blp2);
2067 	cel->blp[1] = blp2;
2068 }
2069 
2070 static void
2071 cache_unlock_buckets_cel(struct celockstate *cel)
2072 {
2073 
2074 	if (cel->blp[0] != NULL)
2075 		mtx_unlock(cel->blp[0]);
2076 	mtx_unlock(cel->blp[1]);
2077 }
2078 
2079 /*
2080  * Lock part of the cache affected by the insertion.
2081  *
2082  * This means vnodelocks for dvp, vp and the relevant bucketlock.
2083  * However, insertion can result in removal of an old entry. In this
2084  * case we have an additional vnode and bucketlock pair to lock.
2085  *
2086  * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2087  * preserving the locking order (smaller address first).
2088  */
2089 static void
2090 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2091     uint32_t hash)
2092 {
2093 	struct namecache *ncp;
2094 	struct mtx *blps[2];
2095 
2096 	blps[0] = HASH2BUCKETLOCK(hash);
2097 	for (;;) {
2098 		blps[1] = NULL;
2099 		cache_lock_vnodes_cel(cel, dvp, vp);
2100 		if (vp == NULL || vp->v_type != VDIR)
2101 			break;
2102 		ncp = vp->v_cache_dd;
2103 		if (ncp == NULL)
2104 			break;
2105 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2106 			break;
2107 		MPASS(ncp->nc_dvp == vp);
2108 		blps[1] = NCP2BUCKETLOCK(ncp);
2109 		if (ncp->nc_flag & NCF_NEGATIVE)
2110 			break;
2111 		if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2112 			break;
2113 		/*
2114 		 * All vnodes got re-locked. Re-validate the state and if
2115 		 * nothing changed we are done. Otherwise restart.
2116 		 */
2117 		if (ncp == vp->v_cache_dd &&
2118 		    (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2119 		    blps[1] == NCP2BUCKETLOCK(ncp) &&
2120 		    VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2121 			break;
2122 		cache_unlock_vnodes_cel(cel);
2123 		cel->vlp[0] = NULL;
2124 		cel->vlp[1] = NULL;
2125 		cel->vlp[2] = NULL;
2126 	}
2127 	cache_lock_buckets_cel(cel, blps[0], blps[1]);
2128 }
2129 
2130 static void
2131 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2132     uint32_t hash)
2133 {
2134 	struct namecache *ncp;
2135 	struct mtx *blps[2];
2136 
2137 	blps[0] = HASH2BUCKETLOCK(hash);
2138 	for (;;) {
2139 		blps[1] = NULL;
2140 		cache_lock_vnodes_cel(cel, dvp, vp);
2141 		ncp = dvp->v_cache_dd;
2142 		if (ncp == NULL)
2143 			break;
2144 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2145 			break;
2146 		MPASS(ncp->nc_dvp == dvp);
2147 		blps[1] = NCP2BUCKETLOCK(ncp);
2148 		if (ncp->nc_flag & NCF_NEGATIVE)
2149 			break;
2150 		if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2151 			break;
2152 		if (ncp == dvp->v_cache_dd &&
2153 		    (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2154 		    blps[1] == NCP2BUCKETLOCK(ncp) &&
2155 		    VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2156 			break;
2157 		cache_unlock_vnodes_cel(cel);
2158 		cel->vlp[0] = NULL;
2159 		cel->vlp[1] = NULL;
2160 		cel->vlp[2] = NULL;
2161 	}
2162 	cache_lock_buckets_cel(cel, blps[0], blps[1]);
2163 }
2164 
2165 static void
2166 cache_enter_unlock(struct celockstate *cel)
2167 {
2168 
2169 	cache_unlock_buckets_cel(cel);
2170 	cache_unlock_vnodes_cel(cel);
2171 }
2172 
2173 static void __noinline
2174 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2175     struct componentname *cnp)
2176 {
2177 	struct celockstate cel;
2178 	struct namecache *ncp;
2179 	uint32_t hash;
2180 	int len;
2181 
2182 	if (dvp->v_cache_dd == NULL)
2183 		return;
2184 	len = cnp->cn_namelen;
2185 	cache_celockstate_init(&cel);
2186 	hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2187 	cache_enter_lock_dd(&cel, dvp, vp, hash);
2188 	vn_seqc_write_begin(dvp);
2189 	ncp = dvp->v_cache_dd;
2190 	if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2191 		KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2192 		cache_zap_locked(ncp);
2193 	} else {
2194 		ncp = NULL;
2195 	}
2196 	dvp->v_cache_dd = NULL;
2197 	vn_seqc_write_end(dvp);
2198 	cache_enter_unlock(&cel);
2199 	if (ncp != NULL)
2200 		cache_free(ncp);
2201 }
2202 
2203 /*
2204  * Add an entry to the cache.
2205  */
2206 void
2207 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2208     struct timespec *tsp, struct timespec *dtsp)
2209 {
2210 	struct celockstate cel;
2211 	struct namecache *ncp, *n2, *ndd;
2212 	struct namecache_ts *ncp_ts;
2213 	struct nchashhead *ncpp;
2214 	uint32_t hash;
2215 	int flag;
2216 	int len;
2217 
2218 	VNPASS(dvp != vp, dvp);
2219 	VNPASS(!VN_IS_DOOMED(dvp), dvp);
2220 	VNPASS(dvp->v_type != VNON, dvp);
2221 	if (vp != NULL) {
2222 		VNPASS(!VN_IS_DOOMED(vp), vp);
2223 		VNPASS(vp->v_type != VNON, vp);
2224 	}
2225 
2226 #ifdef DEBUG_CACHE
2227 	if (__predict_false(!doingcache))
2228 		return;
2229 #endif
2230 
2231 	flag = 0;
2232 	if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2233 		if (cnp->cn_namelen == 1)
2234 			return;
2235 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2236 			cache_enter_dotdot_prep(dvp, vp, cnp);
2237 			flag = NCF_ISDOTDOT;
2238 		}
2239 	}
2240 
2241 	ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2242 	if (ncp == NULL)
2243 		return;
2244 
2245 	cache_celockstate_init(&cel);
2246 	ndd = NULL;
2247 	ncp_ts = NULL;
2248 
2249 	/*
2250 	 * Calculate the hash key and setup as much of the new
2251 	 * namecache entry as possible before acquiring the lock.
2252 	 */
2253 	ncp->nc_flag = flag | NCF_WIP;
2254 	ncp->nc_vp = vp;
2255 	if (vp == NULL)
2256 		cache_neg_init(ncp);
2257 	ncp->nc_dvp = dvp;
2258 	if (tsp != NULL) {
2259 		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2260 		ncp_ts->nc_time = *tsp;
2261 		ncp_ts->nc_ticks = ticks;
2262 		ncp_ts->nc_nc.nc_flag |= NCF_TS;
2263 		if (dtsp != NULL) {
2264 			ncp_ts->nc_dotdottime = *dtsp;
2265 			ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2266 		}
2267 	}
2268 	len = ncp->nc_nlen = cnp->cn_namelen;
2269 	hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2270 	memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2271 	ncp->nc_name[len] = '\0';
2272 	cache_enter_lock(&cel, dvp, vp, hash);
2273 
2274 	/*
2275 	 * See if this vnode or negative entry is already in the cache
2276 	 * with this name.  This can happen with concurrent lookups of
2277 	 * the same path name.
2278 	 */
2279 	ncpp = NCHHASH(hash);
2280 	CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2281 		if (n2->nc_dvp == dvp &&
2282 		    n2->nc_nlen == cnp->cn_namelen &&
2283 		    !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2284 			MPASS(cache_ncp_canuse(n2));
2285 			if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2286 				KASSERT(vp == NULL,
2287 				    ("%s: found entry pointing to a different vnode (%p != %p)",
2288 				    __func__, NULL, vp));
2289 			else
2290 				KASSERT(n2->nc_vp == vp,
2291 				    ("%s: found entry pointing to a different vnode (%p != %p)",
2292 				    __func__, n2->nc_vp, vp));
2293 			/*
2294 			 * Entries are supposed to be immutable unless in the
2295 			 * process of getting destroyed. Accommodating for
2296 			 * changing timestamps is possible but not worth it.
2297 			 * This should be harmless in terms of correctness, in
2298 			 * the worst case resulting in an earlier expiration.
2299 			 * Alternatively, the found entry can be replaced
2300 			 * altogether.
2301 			 */
2302 			MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2303 #if 0
2304 			if (tsp != NULL) {
2305 				KASSERT((n2->nc_flag & NCF_TS) != 0,
2306 				    ("no NCF_TS"));
2307 				n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2308 				n2_ts->nc_time = ncp_ts->nc_time;
2309 				n2_ts->nc_ticks = ncp_ts->nc_ticks;
2310 				if (dtsp != NULL) {
2311 					n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2312 					n2_ts->nc_nc.nc_flag |= NCF_DTS;
2313 				}
2314 			}
2315 #endif
2316 			SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2317 			    vp);
2318 			goto out_unlock_free;
2319 		}
2320 	}
2321 
2322 	if (flag == NCF_ISDOTDOT) {
2323 		/*
2324 		 * See if we are trying to add .. entry, but some other lookup
2325 		 * has populated v_cache_dd pointer already.
2326 		 */
2327 		if (dvp->v_cache_dd != NULL)
2328 			goto out_unlock_free;
2329 		KASSERT(vp == NULL || vp->v_type == VDIR,
2330 		    ("wrong vnode type %p", vp));
2331 		vn_seqc_write_begin(dvp);
2332 		dvp->v_cache_dd = ncp;
2333 		vn_seqc_write_end(dvp);
2334 	}
2335 
2336 	if (vp != NULL) {
2337 		if (flag != NCF_ISDOTDOT) {
2338 			/*
2339 			 * For this case, the cache entry maps both the
2340 			 * directory name in it and the name ".." for the
2341 			 * directory's parent.
2342 			 */
2343 			vn_seqc_write_begin(vp);
2344 			if ((ndd = vp->v_cache_dd) != NULL) {
2345 				if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2346 					cache_zap_locked(ndd);
2347 				else
2348 					ndd = NULL;
2349 			}
2350 			vp->v_cache_dd = ncp;
2351 			vn_seqc_write_end(vp);
2352 		} else if (vp->v_type != VDIR) {
2353 			if (vp->v_cache_dd != NULL) {
2354 				vn_seqc_write_begin(vp);
2355 				vp->v_cache_dd = NULL;
2356 				vn_seqc_write_end(vp);
2357 			}
2358 		}
2359 	}
2360 
2361 	if (flag != NCF_ISDOTDOT) {
2362 		if (LIST_EMPTY(&dvp->v_cache_src)) {
2363 			cache_hold_vnode(dvp);
2364 		}
2365 		LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2366 	}
2367 
2368 	/*
2369 	 * If the entry is "negative", we place it into the
2370 	 * "negative" cache queue, otherwise, we place it into the
2371 	 * destination vnode's cache entries queue.
2372 	 */
2373 	if (vp != NULL) {
2374 		TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2375 		SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2376 		    vp);
2377 	} else {
2378 		if (cnp->cn_flags & ISWHITEOUT)
2379 			ncp->nc_flag |= NCF_WHITE;
2380 		cache_neg_insert(ncp);
2381 		SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2382 		    ncp->nc_name);
2383 	}
2384 
2385 	/*
2386 	 * Insert the new namecache entry into the appropriate chain
2387 	 * within the cache entries table.
2388 	 */
2389 	CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2390 
2391 	atomic_thread_fence_rel();
2392 	/*
2393 	 * Mark the entry as fully constructed.
2394 	 * It is immutable past this point until its removal.
2395 	 */
2396 	atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2397 
2398 	cache_enter_unlock(&cel);
2399 	if (ndd != NULL)
2400 		cache_free(ndd);
2401 	return;
2402 out_unlock_free:
2403 	cache_enter_unlock(&cel);
2404 	cache_free(ncp);
2405 	return;
2406 }
2407 
2408 static u_int
2409 cache_roundup_2(u_int val)
2410 {
2411 	u_int res;
2412 
2413 	for (res = 1; res <= val; res <<= 1)
2414 		continue;
2415 
2416 	return (res);
2417 }
2418 
2419 static struct nchashhead *
2420 nchinittbl(u_long elements, u_long *hashmask)
2421 {
2422 	struct nchashhead *hashtbl;
2423 	u_long hashsize, i;
2424 
2425 	hashsize = cache_roundup_2(elements) / 2;
2426 
2427 	hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2428 	for (i = 0; i < hashsize; i++)
2429 		CK_SLIST_INIT(&hashtbl[i]);
2430 	*hashmask = hashsize - 1;
2431 	return (hashtbl);
2432 }
2433 
2434 static void
2435 ncfreetbl(struct nchashhead *hashtbl)
2436 {
2437 
2438 	free(hashtbl, M_VFSCACHE);
2439 }
2440 
2441 /*
2442  * Name cache initialization, from vfs_init() when we are booting
2443  */
2444 static void
2445 nchinit(void *dummy __unused)
2446 {
2447 	u_int i;
2448 
2449 	cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2450 	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2451 	cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2452 	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2453 	cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2454 	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2455 	cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2456 	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2457 
2458 	VFS_SMR_ZONE_SET(cache_zone_small);
2459 	VFS_SMR_ZONE_SET(cache_zone_small_ts);
2460 	VFS_SMR_ZONE_SET(cache_zone_large);
2461 	VFS_SMR_ZONE_SET(cache_zone_large_ts);
2462 
2463 	ncsize = desiredvnodes * ncsizefactor;
2464 	cache_recalc_neg_min(ncnegminpct);
2465 	nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2466 	ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2467 	if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2468 		ncbuckethash = 7;
2469 	if (ncbuckethash > nchash)
2470 		ncbuckethash = nchash;
2471 	bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2472 	    M_WAITOK | M_ZERO);
2473 	for (i = 0; i < numbucketlocks; i++)
2474 		mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2475 	ncvnodehash = ncbuckethash;
2476 	vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2477 	    M_WAITOK | M_ZERO);
2478 	for (i = 0; i < numvnodelocks; i++)
2479 		mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2480 
2481 	for (i = 0; i < numneglists; i++) {
2482 		mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2483 		mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2484 		TAILQ_INIT(&neglists[i].nl_list);
2485 		TAILQ_INIT(&neglists[i].nl_hotlist);
2486 	}
2487 }
2488 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2489 
2490 void
2491 cache_vnode_init(struct vnode *vp)
2492 {
2493 
2494 	LIST_INIT(&vp->v_cache_src);
2495 	TAILQ_INIT(&vp->v_cache_dst);
2496 	vp->v_cache_dd = NULL;
2497 	cache_prehash(vp);
2498 }
2499 
2500 void
2501 cache_changesize(u_long newmaxvnodes)
2502 {
2503 	struct nchashhead *new_nchashtbl, *old_nchashtbl;
2504 	u_long new_nchash, old_nchash;
2505 	struct namecache *ncp;
2506 	uint32_t hash;
2507 	u_long newncsize;
2508 	int i;
2509 
2510 	newncsize = newmaxvnodes * ncsizefactor;
2511 	newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2512 	if (newmaxvnodes < numbucketlocks)
2513 		newmaxvnodes = numbucketlocks;
2514 
2515 	new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2516 	/* If same hash table size, nothing to do */
2517 	if (nchash == new_nchash) {
2518 		ncfreetbl(new_nchashtbl);
2519 		return;
2520 	}
2521 	/*
2522 	 * Move everything from the old hash table to the new table.
2523 	 * None of the namecache entries in the table can be removed
2524 	 * because to do so, they have to be removed from the hash table.
2525 	 */
2526 	cache_lock_all_vnodes();
2527 	cache_lock_all_buckets();
2528 	old_nchashtbl = nchashtbl;
2529 	old_nchash = nchash;
2530 	nchashtbl = new_nchashtbl;
2531 	nchash = new_nchash;
2532 	for (i = 0; i <= old_nchash; i++) {
2533 		while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2534 			hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2535 			    ncp->nc_dvp);
2536 			CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2537 			CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2538 		}
2539 	}
2540 	ncsize = newncsize;
2541 	cache_recalc_neg_min(ncnegminpct);
2542 	cache_unlock_all_buckets();
2543 	cache_unlock_all_vnodes();
2544 	ncfreetbl(old_nchashtbl);
2545 }
2546 
2547 /*
2548  * Invalidate all entries from and to a particular vnode.
2549  */
2550 static void
2551 cache_purge_impl(struct vnode *vp)
2552 {
2553 	struct cache_freebatch batch;
2554 	struct namecache *ncp;
2555 	struct mtx *vlp, *vlp2;
2556 
2557 	TAILQ_INIT(&batch);
2558 	vlp = VP2VNODELOCK(vp);
2559 	vlp2 = NULL;
2560 	mtx_lock(vlp);
2561 retry:
2562 	while (!LIST_EMPTY(&vp->v_cache_src)) {
2563 		ncp = LIST_FIRST(&vp->v_cache_src);
2564 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2565 			goto retry;
2566 		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2567 	}
2568 	while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2569 		ncp = TAILQ_FIRST(&vp->v_cache_dst);
2570 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2571 			goto retry;
2572 		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2573 	}
2574 	ncp = vp->v_cache_dd;
2575 	if (ncp != NULL) {
2576 		KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2577 		   ("lost dotdot link"));
2578 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2579 			goto retry;
2580 		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2581 	}
2582 	KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2583 	mtx_unlock(vlp);
2584 	if (vlp2 != NULL)
2585 		mtx_unlock(vlp2);
2586 	cache_free_batch(&batch);
2587 }
2588 
2589 /*
2590  * Opportunistic check to see if there is anything to do.
2591  */
2592 static bool
2593 cache_has_entries(struct vnode *vp)
2594 {
2595 
2596 	if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2597 	    vp->v_cache_dd == NULL)
2598 		return (false);
2599 	return (true);
2600 }
2601 
2602 void
2603 cache_purge(struct vnode *vp)
2604 {
2605 
2606 	SDT_PROBE1(vfs, namecache, purge, done, vp);
2607 	if (!cache_has_entries(vp))
2608 		return;
2609 	cache_purge_impl(vp);
2610 }
2611 
2612 /*
2613  * Only to be used by vgone.
2614  */
2615 void
2616 cache_purge_vgone(struct vnode *vp)
2617 {
2618 	struct mtx *vlp;
2619 
2620 	VNPASS(VN_IS_DOOMED(vp), vp);
2621 	if (cache_has_entries(vp)) {
2622 		cache_purge_impl(vp);
2623 		return;
2624 	}
2625 
2626 	/*
2627 	 * Serialize against a potential thread doing cache_purge.
2628 	 */
2629 	vlp = VP2VNODELOCK(vp);
2630 	mtx_wait_unlocked(vlp);
2631 	if (cache_has_entries(vp)) {
2632 		cache_purge_impl(vp);
2633 		return;
2634 	}
2635 	return;
2636 }
2637 
2638 /*
2639  * Invalidate all negative entries for a particular directory vnode.
2640  */
2641 void
2642 cache_purge_negative(struct vnode *vp)
2643 {
2644 	struct cache_freebatch batch;
2645 	struct namecache *ncp, *nnp;
2646 	struct mtx *vlp;
2647 
2648 	SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2649 	if (LIST_EMPTY(&vp->v_cache_src))
2650 		return;
2651 	TAILQ_INIT(&batch);
2652 	vlp = VP2VNODELOCK(vp);
2653 	mtx_lock(vlp);
2654 	LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2655 		if (!(ncp->nc_flag & NCF_NEGATIVE))
2656 			continue;
2657 		cache_zap_negative_locked_vnode_kl(ncp, vp);
2658 		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2659 	}
2660 	mtx_unlock(vlp);
2661 	cache_free_batch(&batch);
2662 }
2663 
2664 /*
2665  * Entry points for modifying VOP operations.
2666  */
2667 void
2668 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2669     struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2670 {
2671 
2672 	ASSERT_VOP_IN_SEQC(fdvp);
2673 	ASSERT_VOP_IN_SEQC(fvp);
2674 	ASSERT_VOP_IN_SEQC(tdvp);
2675 	if (tvp != NULL)
2676 		ASSERT_VOP_IN_SEQC(tvp);
2677 
2678 	cache_purge(fvp);
2679 	if (tvp != NULL) {
2680 		cache_purge(tvp);
2681 		KASSERT(!cache_remove_cnp(tdvp, tcnp),
2682 		    ("%s: lingering negative entry", __func__));
2683 	} else {
2684 		cache_remove_cnp(tdvp, tcnp);
2685 	}
2686 }
2687 
2688 void
2689 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
2690 {
2691 
2692 	ASSERT_VOP_IN_SEQC(dvp);
2693 	ASSERT_VOP_IN_SEQC(vp);
2694 	cache_purge(vp);
2695 }
2696 
2697 #ifdef INVARIANTS
2698 /*
2699  * Validate that if an entry exists it matches.
2700  */
2701 void
2702 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2703 {
2704 	struct namecache *ncp;
2705 	struct mtx *blp;
2706 	uint32_t hash;
2707 
2708 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2709 	if (CK_SLIST_EMPTY(NCHHASH(hash)))
2710 		return;
2711 	blp = HASH2BUCKETLOCK(hash);
2712 	mtx_lock(blp);
2713 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2714 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2715 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
2716 			if (ncp->nc_vp != vp)
2717 				panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p vp %p\n",
2718 				    __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp,
2719 				    ncp->nc_vp);
2720 		}
2721 	}
2722 	mtx_unlock(blp);
2723 }
2724 #endif
2725 
2726 /*
2727  * Flush all entries referencing a particular filesystem.
2728  */
2729 void
2730 cache_purgevfs(struct mount *mp)
2731 {
2732 	struct vnode *vp, *mvp;
2733 
2734 	SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2735 	/*
2736 	 * Somewhat wasteful iteration over all vnodes. Would be better to
2737 	 * support filtering and avoid the interlock to begin with.
2738 	 */
2739 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2740 		if (!cache_has_entries(vp)) {
2741 			VI_UNLOCK(vp);
2742 			continue;
2743 		}
2744 		vholdl(vp);
2745 		VI_UNLOCK(vp);
2746 		cache_purge(vp);
2747 		vdrop(vp);
2748 	}
2749 }
2750 
2751 /*
2752  * Perform canonical checks and cache lookup and pass on to filesystem
2753  * through the vop_cachedlookup only if needed.
2754  */
2755 
2756 int
2757 vfs_cache_lookup(struct vop_lookup_args *ap)
2758 {
2759 	struct vnode *dvp;
2760 	int error;
2761 	struct vnode **vpp = ap->a_vpp;
2762 	struct componentname *cnp = ap->a_cnp;
2763 	int flags = cnp->cn_flags;
2764 
2765 	*vpp = NULL;
2766 	dvp = ap->a_dvp;
2767 
2768 	if (dvp->v_type != VDIR)
2769 		return (ENOTDIR);
2770 
2771 	if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2772 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2773 		return (EROFS);
2774 
2775 	error = vn_dir_check_exec(dvp, cnp);
2776 	if (error != 0)
2777 		return (error);
2778 
2779 	error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2780 	if (error == 0)
2781 		return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2782 	if (error == -1)
2783 		return (0);
2784 	return (error);
2785 }
2786 
2787 /* Implementation of the getcwd syscall. */
2788 int
2789 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2790 {
2791 	char *buf, *retbuf;
2792 	size_t buflen;
2793 	int error;
2794 
2795 	buflen = uap->buflen;
2796 	if (__predict_false(buflen < 2))
2797 		return (EINVAL);
2798 	if (buflen > MAXPATHLEN)
2799 		buflen = MAXPATHLEN;
2800 
2801 	buf = uma_zalloc(namei_zone, M_WAITOK);
2802 	error = vn_getcwd(buf, &retbuf, &buflen);
2803 	if (error == 0)
2804 		error = copyout(retbuf, uap->buf, buflen);
2805 	uma_zfree(namei_zone, buf);
2806 	return (error);
2807 }
2808 
2809 int
2810 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
2811 {
2812 	struct pwd *pwd;
2813 	int error;
2814 
2815 	vfs_smr_enter();
2816 	pwd = pwd_get_smr();
2817 	error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
2818 	    buflen, 0);
2819 	VFS_SMR_ASSERT_NOT_ENTERED();
2820 	if (error < 0) {
2821 		pwd = pwd_hold(curthread);
2822 		error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
2823 		    retbuf, buflen);
2824 		pwd_drop(pwd);
2825 	}
2826 
2827 #ifdef KTRACE
2828 	if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2829 		ktrnamei(*retbuf);
2830 #endif
2831 	return (error);
2832 }
2833 
2834 static int
2835 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2836     size_t size, int flags, enum uio_seg pathseg)
2837 {
2838 	struct nameidata nd;
2839 	char *retbuf, *freebuf;
2840 	int error;
2841 
2842 	if (flags != 0)
2843 		return (EINVAL);
2844 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2845 	    pathseg, path, fd, &cap_fstat_rights, td);
2846 	if ((error = namei(&nd)) != 0)
2847 		return (error);
2848 	error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
2849 	if (error == 0) {
2850 		error = copyout(retbuf, buf, size);
2851 		free(freebuf, M_TEMP);
2852 	}
2853 	NDFREE(&nd, 0);
2854 	return (error);
2855 }
2856 
2857 int
2858 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2859 {
2860 
2861 	return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2862 	    uap->flags, UIO_USERSPACE));
2863 }
2864 
2865 /*
2866  * Retrieve the full filesystem path that correspond to a vnode from the name
2867  * cache (if available)
2868  */
2869 int
2870 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
2871 {
2872 	struct pwd *pwd;
2873 	char *buf;
2874 	size_t buflen;
2875 	int error;
2876 
2877 	if (__predict_false(vp == NULL))
2878 		return (EINVAL);
2879 
2880 	buflen = MAXPATHLEN;
2881 	buf = malloc(buflen, M_TEMP, M_WAITOK);
2882 	vfs_smr_enter();
2883 	pwd = pwd_get_smr();
2884 	error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
2885 	VFS_SMR_ASSERT_NOT_ENTERED();
2886 	if (error < 0) {
2887 		pwd = pwd_hold(curthread);
2888 		error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
2889 		pwd_drop(pwd);
2890 	}
2891 	if (error == 0)
2892 		*freebuf = buf;
2893 	else
2894 		free(buf, M_TEMP);
2895 	return (error);
2896 }
2897 
2898 /*
2899  * This function is similar to vn_fullpath, but it attempts to lookup the
2900  * pathname relative to the global root mount point.  This is required for the
2901  * auditing sub-system, as audited pathnames must be absolute, relative to the
2902  * global root mount point.
2903  */
2904 int
2905 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
2906 {
2907 	char *buf;
2908 	size_t buflen;
2909 	int error;
2910 
2911 	if (__predict_false(vp == NULL))
2912 		return (EINVAL);
2913 	buflen = MAXPATHLEN;
2914 	buf = malloc(buflen, M_TEMP, M_WAITOK);
2915 	vfs_smr_enter();
2916 	error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
2917 	VFS_SMR_ASSERT_NOT_ENTERED();
2918 	if (error < 0) {
2919 		error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
2920 	}
2921 	if (error == 0)
2922 		*freebuf = buf;
2923 	else
2924 		free(buf, M_TEMP);
2925 	return (error);
2926 }
2927 
2928 static struct namecache *
2929 vn_dd_from_dst(struct vnode *vp)
2930 {
2931 	struct namecache *ncp;
2932 
2933 	cache_assert_vnode_locked(vp);
2934 	TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
2935 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2936 			return (ncp);
2937 	}
2938 	return (NULL);
2939 }
2940 
2941 int
2942 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
2943 {
2944 	struct vnode *dvp;
2945 	struct namecache *ncp;
2946 	struct mtx *vlp;
2947 	int error;
2948 
2949 	vlp = VP2VNODELOCK(*vp);
2950 	mtx_lock(vlp);
2951 	ncp = (*vp)->v_cache_dd;
2952 	if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
2953 		KASSERT(ncp == vn_dd_from_dst(*vp),
2954 		    ("%s: mismatch for dd entry (%p != %p)", __func__,
2955 		    ncp, vn_dd_from_dst(*vp)));
2956 	} else {
2957 		ncp = vn_dd_from_dst(*vp);
2958 	}
2959 	if (ncp != NULL) {
2960 		if (*buflen < ncp->nc_nlen) {
2961 			mtx_unlock(vlp);
2962 			vrele(*vp);
2963 			counter_u64_add(numfullpathfail4, 1);
2964 			error = ENOMEM;
2965 			SDT_PROBE3(vfs, namecache, fullpath, return, error,
2966 			    vp, NULL);
2967 			return (error);
2968 		}
2969 		*buflen -= ncp->nc_nlen;
2970 		memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2971 		SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2972 		    ncp->nc_name, vp);
2973 		dvp = *vp;
2974 		*vp = ncp->nc_dvp;
2975 		vref(*vp);
2976 		mtx_unlock(vlp);
2977 		vrele(dvp);
2978 		return (0);
2979 	}
2980 	SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2981 
2982 	mtx_unlock(vlp);
2983 	vn_lock(*vp, LK_SHARED | LK_RETRY);
2984 	error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
2985 	vput(*vp);
2986 	if (error) {
2987 		counter_u64_add(numfullpathfail2, 1);
2988 		SDT_PROBE3(vfs, namecache, fullpath, return,  error, vp, NULL);
2989 		return (error);
2990 	}
2991 
2992 	*vp = dvp;
2993 	if (VN_IS_DOOMED(dvp)) {
2994 		/* forced unmount */
2995 		vrele(dvp);
2996 		error = ENOENT;
2997 		SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2998 		return (error);
2999 	}
3000 	/*
3001 	 * *vp has its use count incremented still.
3002 	 */
3003 
3004 	return (0);
3005 }
3006 
3007 /*
3008  * Resolve a directory to a pathname.
3009  *
3010  * The name of the directory can always be found in the namecache or fetched
3011  * from the filesystem. There is also guaranteed to be only one parent, meaning
3012  * we can just follow vnodes up until we find the root.
3013  *
3014  * The vnode must be referenced.
3015  */
3016 static int
3017 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3018     size_t *len, size_t addend)
3019 {
3020 #ifdef KDTRACE_HOOKS
3021 	struct vnode *startvp = vp;
3022 #endif
3023 	struct vnode *vp1;
3024 	size_t buflen;
3025 	int error;
3026 	bool slash_prefixed;
3027 
3028 	VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3029 	VNPASS(vp->v_usecount > 0, vp);
3030 
3031 	buflen = *len;
3032 
3033 	slash_prefixed = true;
3034 	if (addend == 0) {
3035 		MPASS(*len >= 2);
3036 		buflen--;
3037 		buf[buflen] = '\0';
3038 		slash_prefixed = false;
3039 	}
3040 
3041 	error = 0;
3042 
3043 	SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3044 	counter_u64_add(numfullpathcalls, 1);
3045 	while (vp != rdir && vp != rootvnode) {
3046 		/*
3047 		 * The vp vnode must be already fully constructed,
3048 		 * since it is either found in namecache or obtained
3049 		 * from VOP_VPTOCNP().  We may test for VV_ROOT safely
3050 		 * without obtaining the vnode lock.
3051 		 */
3052 		if ((vp->v_vflag & VV_ROOT) != 0) {
3053 			vn_lock(vp, LK_RETRY | LK_SHARED);
3054 
3055 			/*
3056 			 * With the vnode locked, check for races with
3057 			 * unmount, forced or not.  Note that we
3058 			 * already verified that vp is not equal to
3059 			 * the root vnode, which means that
3060 			 * mnt_vnodecovered can be NULL only for the
3061 			 * case of unmount.
3062 			 */
3063 			if (VN_IS_DOOMED(vp) ||
3064 			    (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3065 			    vp1->v_mountedhere != vp->v_mount) {
3066 				vput(vp);
3067 				error = ENOENT;
3068 				SDT_PROBE3(vfs, namecache, fullpath, return,
3069 				    error, vp, NULL);
3070 				break;
3071 			}
3072 
3073 			vref(vp1);
3074 			vput(vp);
3075 			vp = vp1;
3076 			continue;
3077 		}
3078 		if (vp->v_type != VDIR) {
3079 			vrele(vp);
3080 			counter_u64_add(numfullpathfail1, 1);
3081 			error = ENOTDIR;
3082 			SDT_PROBE3(vfs, namecache, fullpath, return,
3083 			    error, vp, NULL);
3084 			break;
3085 		}
3086 		error = vn_vptocnp(&vp, buf, &buflen);
3087 		if (error)
3088 			break;
3089 		if (buflen == 0) {
3090 			vrele(vp);
3091 			error = ENOMEM;
3092 			SDT_PROBE3(vfs, namecache, fullpath, return, error,
3093 			    startvp, NULL);
3094 			break;
3095 		}
3096 		buf[--buflen] = '/';
3097 		slash_prefixed = true;
3098 	}
3099 	if (error)
3100 		return (error);
3101 	if (!slash_prefixed) {
3102 		if (buflen == 0) {
3103 			vrele(vp);
3104 			counter_u64_add(numfullpathfail4, 1);
3105 			SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3106 			    startvp, NULL);
3107 			return (ENOMEM);
3108 		}
3109 		buf[--buflen] = '/';
3110 	}
3111 	counter_u64_add(numfullpathfound, 1);
3112 	vrele(vp);
3113 
3114 	*retbuf = buf + buflen;
3115 	SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3116 	*len -= buflen;
3117 	*len += addend;
3118 	return (0);
3119 }
3120 
3121 /*
3122  * Resolve an arbitrary vnode to a pathname.
3123  *
3124  * Note 2 caveats:
3125  * - hardlinks are not tracked, thus if the vnode is not a directory this can
3126  *   resolve to a different path than the one used to find it
3127  * - namecache is not mandatory, meaning names are not guaranteed to be added
3128  *   (in which case resolving fails)
3129  */
3130 static void __inline
3131 cache_rev_failed_impl(int *reason, int line)
3132 {
3133 
3134 	*reason = line;
3135 }
3136 #define cache_rev_failed(var)	cache_rev_failed_impl((var), __LINE__)
3137 
3138 static int
3139 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3140     char **retbuf, size_t *buflen, size_t addend)
3141 {
3142 #ifdef KDTRACE_HOOKS
3143 	struct vnode *startvp = vp;
3144 #endif
3145 	struct vnode *tvp;
3146 	struct mount *mp;
3147 	struct namecache *ncp;
3148 	size_t orig_buflen;
3149 	int reason;
3150 	int error;
3151 #ifdef KDTRACE_HOOKS
3152 	int i;
3153 #endif
3154 	seqc_t vp_seqc, tvp_seqc;
3155 	u_char nc_flag;
3156 
3157 	VFS_SMR_ASSERT_ENTERED();
3158 
3159 	if (!cache_fast_revlookup) {
3160 		vfs_smr_exit();
3161 		return (-1);
3162 	}
3163 
3164 	orig_buflen = *buflen;
3165 
3166 	if (addend == 0) {
3167 		MPASS(*buflen >= 2);
3168 		*buflen -= 1;
3169 		buf[*buflen] = '\0';
3170 	}
3171 
3172 	if (vp == rdir || vp == rootvnode) {
3173 		if (addend == 0) {
3174 			*buflen -= 1;
3175 			buf[*buflen] = '/';
3176 		}
3177 		goto out_ok;
3178 	}
3179 
3180 #ifdef KDTRACE_HOOKS
3181 	i = 0;
3182 #endif
3183 	error = -1;
3184 	ncp = NULL; /* for sdt probe down below */
3185 	vp_seqc = vn_seqc_read_any(vp);
3186 	if (seqc_in_modify(vp_seqc)) {
3187 		cache_rev_failed(&reason);
3188 		goto out_abort;
3189 	}
3190 
3191 	for (;;) {
3192 #ifdef KDTRACE_HOOKS
3193 		i++;
3194 #endif
3195 		if ((vp->v_vflag & VV_ROOT) != 0) {
3196 			mp = atomic_load_ptr(&vp->v_mount);
3197 			if (mp == NULL) {
3198 				cache_rev_failed(&reason);
3199 				goto out_abort;
3200 			}
3201 			tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3202 			tvp_seqc = vn_seqc_read_any(tvp);
3203 			if (seqc_in_modify(tvp_seqc)) {
3204 				cache_rev_failed(&reason);
3205 				goto out_abort;
3206 			}
3207 			if (!vn_seqc_consistent(vp, vp_seqc)) {
3208 				cache_rev_failed(&reason);
3209 				goto out_abort;
3210 			}
3211 			vp = tvp;
3212 			vp_seqc = tvp_seqc;
3213 			continue;
3214 		}
3215 		ncp = atomic_load_ptr(&vp->v_cache_dd);
3216 		if (ncp == NULL) {
3217 			cache_rev_failed(&reason);
3218 			goto out_abort;
3219 		}
3220 		nc_flag = atomic_load_char(&ncp->nc_flag);
3221 		if ((nc_flag & NCF_ISDOTDOT) != 0) {
3222 			cache_rev_failed(&reason);
3223 			goto out_abort;
3224 		}
3225 		if (!cache_ncp_canuse(ncp)) {
3226 			cache_rev_failed(&reason);
3227 			goto out_abort;
3228 		}
3229 		if (ncp->nc_nlen >= *buflen) {
3230 			cache_rev_failed(&reason);
3231 			error = ENOMEM;
3232 			goto out_abort;
3233 		}
3234 		*buflen -= ncp->nc_nlen;
3235 		memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3236 		*buflen -= 1;
3237 		buf[*buflen] = '/';
3238 		tvp = ncp->nc_dvp;
3239 		tvp_seqc = vn_seqc_read_any(tvp);
3240 		if (seqc_in_modify(tvp_seqc)) {
3241 			cache_rev_failed(&reason);
3242 			goto out_abort;
3243 		}
3244 		if (!vn_seqc_consistent(vp, vp_seqc)) {
3245 			cache_rev_failed(&reason);
3246 			goto out_abort;
3247 		}
3248 		vp = tvp;
3249 		vp_seqc = tvp_seqc;
3250 		if (vp == rdir || vp == rootvnode)
3251 			break;
3252 	}
3253 out_ok:
3254 	vfs_smr_exit();
3255 	*retbuf = buf + *buflen;
3256 	*buflen = orig_buflen - *buflen + addend;
3257 	SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3258 	return (0);
3259 
3260 out_abort:
3261 	*buflen = orig_buflen;
3262 	SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3263 	vfs_smr_exit();
3264 	return (error);
3265 }
3266 
3267 static int
3268 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3269     size_t *buflen)
3270 {
3271 	size_t orig_buflen, addend;
3272 	int error;
3273 
3274 	if (*buflen < 2)
3275 		return (EINVAL);
3276 
3277 	orig_buflen = *buflen;
3278 
3279 	vref(vp);
3280 	addend = 0;
3281 	if (vp->v_type != VDIR) {
3282 		*buflen -= 1;
3283 		buf[*buflen] = '\0';
3284 		error = vn_vptocnp(&vp, buf, buflen);
3285 		if (error)
3286 			return (error);
3287 		if (*buflen == 0) {
3288 			vrele(vp);
3289 			return (ENOMEM);
3290 		}
3291 		*buflen -= 1;
3292 		buf[*buflen] = '/';
3293 		addend = orig_buflen - *buflen;
3294 	}
3295 
3296 	return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3297 }
3298 
3299 /*
3300  * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3301  *
3302  * Since the namecache does not track hardlinks, the caller is expected to first
3303  * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
3304  *
3305  * Then we have 2 cases:
3306  * - if the found vnode is a directory, the path can be constructed just by
3307  *   following names up the chain
3308  * - otherwise we populate the buffer with the saved name and start resolving
3309  *   from the parent
3310  */
3311 static int
3312 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
3313     size_t *buflen)
3314 {
3315 	char *buf, *tmpbuf;
3316 	struct pwd *pwd;
3317 	struct componentname *cnp;
3318 	struct vnode *vp;
3319 	size_t addend;
3320 	int error;
3321 	enum vtype type;
3322 
3323 	if (*buflen < 2)
3324 		return (EINVAL);
3325 	if (*buflen > MAXPATHLEN)
3326 		*buflen = MAXPATHLEN;
3327 
3328 	buf = malloc(*buflen, M_TEMP, M_WAITOK);
3329 
3330 	addend = 0;
3331 	vp = ndp->ni_vp;
3332 	/*
3333 	 * Check for VBAD to work around the vp_crossmp bug in lookup().
3334 	 *
3335 	 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3336 	 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3337 	 * If the type is VDIR (like in this very case) we can skip looking
3338 	 * at ni_dvp in the first place. However, since vnodes get passed here
3339 	 * unlocked the target may transition to doomed state (type == VBAD)
3340 	 * before we get to evaluate the condition. If this happens, we will
3341 	 * populate part of the buffer and descend to vn_fullpath_dir with
3342 	 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3343 	 *
3344 	 * This should be atomic_load(&vp->v_type) but it is illegal to take
3345 	 * an address of a bit field, even if said field is sized to char.
3346 	 * Work around the problem by reading the value into a full-sized enum
3347 	 * and then re-reading it with atomic_load which will still prevent
3348 	 * the compiler from re-reading down the road.
3349 	 */
3350 	type = vp->v_type;
3351 	type = atomic_load_int(&type);
3352 	if (type == VBAD) {
3353 		error = ENOENT;
3354 		goto out_bad;
3355 	}
3356 	if (type != VDIR) {
3357 		cnp = &ndp->ni_cnd;
3358 		addend = cnp->cn_namelen + 2;
3359 		if (*buflen < addend) {
3360 			error = ENOMEM;
3361 			goto out_bad;
3362 		}
3363 		*buflen -= addend;
3364 		tmpbuf = buf + *buflen;
3365 		tmpbuf[0] = '/';
3366 		memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3367 		tmpbuf[addend - 1] = '\0';
3368 		vp = ndp->ni_dvp;
3369 	}
3370 
3371 	vfs_smr_enter();
3372 	pwd = pwd_get_smr();
3373 	error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3374 	    addend);
3375 	VFS_SMR_ASSERT_NOT_ENTERED();
3376 	if (error < 0) {
3377 		pwd = pwd_hold(curthread);
3378 		vref(vp);
3379 		error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3380 		    addend);
3381 		pwd_drop(pwd);
3382 		if (error != 0)
3383 			goto out_bad;
3384 	}
3385 
3386 	*freebuf = buf;
3387 
3388 	return (0);
3389 out_bad:
3390 	free(buf, M_TEMP);
3391 	return (error);
3392 }
3393 
3394 struct vnode *
3395 vn_dir_dd_ino(struct vnode *vp)
3396 {
3397 	struct namecache *ncp;
3398 	struct vnode *ddvp;
3399 	struct mtx *vlp;
3400 	enum vgetstate vs;
3401 
3402 	ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3403 	vlp = VP2VNODELOCK(vp);
3404 	mtx_lock(vlp);
3405 	TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3406 		if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3407 			continue;
3408 		ddvp = ncp->nc_dvp;
3409 		vs = vget_prep(ddvp);
3410 		mtx_unlock(vlp);
3411 		if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3412 			return (NULL);
3413 		return (ddvp);
3414 	}
3415 	mtx_unlock(vlp);
3416 	return (NULL);
3417 }
3418 
3419 int
3420 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3421 {
3422 	struct namecache *ncp;
3423 	struct mtx *vlp;
3424 	int l;
3425 
3426 	vlp = VP2VNODELOCK(vp);
3427 	mtx_lock(vlp);
3428 	TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3429 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3430 			break;
3431 	if (ncp == NULL) {
3432 		mtx_unlock(vlp);
3433 		return (ENOENT);
3434 	}
3435 	l = min(ncp->nc_nlen, buflen - 1);
3436 	memcpy(buf, ncp->nc_name, l);
3437 	mtx_unlock(vlp);
3438 	buf[l] = '\0';
3439 	return (0);
3440 }
3441 
3442 /*
3443  * This function updates path string to vnode's full global path
3444  * and checks the size of the new path string against the pathlen argument.
3445  *
3446  * Requires a locked, referenced vnode.
3447  * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3448  *
3449  * If vp is a directory, the call to vn_fullpath_global() always succeeds
3450  * because it falls back to the ".." lookup if the namecache lookup fails.
3451  */
3452 int
3453 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3454     u_int pathlen)
3455 {
3456 	struct nameidata nd;
3457 	struct vnode *vp1;
3458 	char *rpath, *fbuf;
3459 	int error;
3460 
3461 	ASSERT_VOP_ELOCKED(vp, __func__);
3462 
3463 	/* Construct global filesystem path from vp. */
3464 	VOP_UNLOCK(vp);
3465 	error = vn_fullpath_global(vp, &rpath, &fbuf);
3466 
3467 	if (error != 0) {
3468 		vrele(vp);
3469 		return (error);
3470 	}
3471 
3472 	if (strlen(rpath) >= pathlen) {
3473 		vrele(vp);
3474 		error = ENAMETOOLONG;
3475 		goto out;
3476 	}
3477 
3478 	/*
3479 	 * Re-lookup the vnode by path to detect a possible rename.
3480 	 * As a side effect, the vnode is relocked.
3481 	 * If vnode was renamed, return ENOENT.
3482 	 */
3483 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3484 	    UIO_SYSSPACE, path, td);
3485 	error = namei(&nd);
3486 	if (error != 0) {
3487 		vrele(vp);
3488 		goto out;
3489 	}
3490 	NDFREE(&nd, NDF_ONLY_PNBUF);
3491 	vp1 = nd.ni_vp;
3492 	vrele(vp);
3493 	if (vp1 == vp)
3494 		strcpy(path, rpath);
3495 	else {
3496 		vput(vp1);
3497 		error = ENOENT;
3498 	}
3499 
3500 out:
3501 	free(fbuf, M_TEMP);
3502 	return (error);
3503 }
3504 
3505 #ifdef DDB
3506 static void
3507 db_print_vpath(struct vnode *vp)
3508 {
3509 
3510 	while (vp != NULL) {
3511 		db_printf("%p: ", vp);
3512 		if (vp == rootvnode) {
3513 			db_printf("/");
3514 			vp = NULL;
3515 		} else {
3516 			if (vp->v_vflag & VV_ROOT) {
3517 				db_printf("<mount point>");
3518 				vp = vp->v_mount->mnt_vnodecovered;
3519 			} else {
3520 				struct namecache *ncp;
3521 				char *ncn;
3522 				int i;
3523 
3524 				ncp = TAILQ_FIRST(&vp->v_cache_dst);
3525 				if (ncp != NULL) {
3526 					ncn = ncp->nc_name;
3527 					for (i = 0; i < ncp->nc_nlen; i++)
3528 						db_printf("%c", *ncn++);
3529 					vp = ncp->nc_dvp;
3530 				} else {
3531 					vp = NULL;
3532 				}
3533 			}
3534 		}
3535 		db_printf("\n");
3536 	}
3537 
3538 	return;
3539 }
3540 
3541 DB_SHOW_COMMAND(vpath, db_show_vpath)
3542 {
3543 	struct vnode *vp;
3544 
3545 	if (!have_addr) {
3546 		db_printf("usage: show vpath <struct vnode *>\n");
3547 		return;
3548 	}
3549 
3550 	vp = (struct vnode *)addr;
3551 	db_print_vpath(vp);
3552 }
3553 
3554 #endif
3555 
3556 static bool __read_frequently cache_fast_lookup = true;
3557 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_lookup, CTLFLAG_RW,
3558     &cache_fast_lookup, 0, "");
3559 
3560 #define CACHE_FPL_FAILED	-2020
3561 
3562 static void
3563 cache_fpl_cleanup_cnp(struct componentname *cnp)
3564 {
3565 
3566 	uma_zfree(namei_zone, cnp->cn_pnbuf);
3567 #ifdef DIAGNOSTIC
3568 	cnp->cn_pnbuf = NULL;
3569 	cnp->cn_nameptr = NULL;
3570 #endif
3571 }
3572 
3573 static void
3574 cache_fpl_handle_root(struct nameidata *ndp, struct vnode **dpp)
3575 {
3576 	struct componentname *cnp;
3577 
3578 	cnp = &ndp->ni_cnd;
3579 	while (*(cnp->cn_nameptr) == '/') {
3580 		cnp->cn_nameptr++;
3581 		ndp->ni_pathlen--;
3582 	}
3583 
3584 	*dpp = ndp->ni_rootdir;
3585 }
3586 
3587 /*
3588  * Components of nameidata (or objects it can point to) which may
3589  * need restoring in case fast path lookup fails.
3590  */
3591 struct nameidata_saved {
3592 	long cn_namelen;
3593 	char *cn_nameptr;
3594 	size_t ni_pathlen;
3595 	int cn_flags;
3596 };
3597 
3598 struct cache_fpl {
3599 	struct nameidata *ndp;
3600 	struct componentname *cnp;
3601 	struct pwd *pwd;
3602 	struct vnode *dvp;
3603 	struct vnode *tvp;
3604 	seqc_t dvp_seqc;
3605 	seqc_t tvp_seqc;
3606 	struct nameidata_saved snd;
3607 	int line;
3608 	enum cache_fpl_status status:8;
3609 	bool in_smr;
3610 	bool fsearch;
3611 };
3612 
3613 static void
3614 cache_fpl_checkpoint(struct cache_fpl *fpl, struct nameidata_saved *snd)
3615 {
3616 
3617 	snd->cn_flags = fpl->ndp->ni_cnd.cn_flags;
3618 	snd->cn_namelen = fpl->ndp->ni_cnd.cn_namelen;
3619 	snd->cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3620 	snd->ni_pathlen = fpl->ndp->ni_pathlen;
3621 }
3622 
3623 static void
3624 cache_fpl_restore_partial(struct cache_fpl *fpl, struct nameidata_saved *snd)
3625 {
3626 
3627 	fpl->ndp->ni_cnd.cn_flags = snd->cn_flags;
3628 	fpl->ndp->ni_cnd.cn_namelen = snd->cn_namelen;
3629 	fpl->ndp->ni_cnd.cn_nameptr = snd->cn_nameptr;
3630 	fpl->ndp->ni_pathlen = snd->ni_pathlen;
3631 }
3632 
3633 static void
3634 cache_fpl_restore_abort(struct cache_fpl *fpl, struct nameidata_saved *snd)
3635 {
3636 
3637 	cache_fpl_restore_partial(fpl, snd);
3638 	/*
3639 	 * It is 0 on entry by API contract.
3640 	 */
3641 	fpl->ndp->ni_resflags = 0;
3642 }
3643 
3644 #ifdef INVARIANTS
3645 #define cache_fpl_smr_assert_entered(fpl) ({			\
3646 	struct cache_fpl *_fpl = (fpl);				\
3647 	MPASS(_fpl->in_smr == true);				\
3648 	VFS_SMR_ASSERT_ENTERED();				\
3649 })
3650 #define cache_fpl_smr_assert_not_entered(fpl) ({		\
3651 	struct cache_fpl *_fpl = (fpl);				\
3652 	MPASS(_fpl->in_smr == false);				\
3653 	VFS_SMR_ASSERT_NOT_ENTERED();				\
3654 })
3655 #else
3656 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3657 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3658 #endif
3659 
3660 #define cache_fpl_smr_enter_initial(fpl) ({			\
3661 	struct cache_fpl *_fpl = (fpl);				\
3662 	vfs_smr_enter();					\
3663 	_fpl->in_smr = true;					\
3664 })
3665 
3666 #define cache_fpl_smr_enter(fpl) ({				\
3667 	struct cache_fpl *_fpl = (fpl);				\
3668 	MPASS(_fpl->in_smr == false);				\
3669 	vfs_smr_enter();					\
3670 	_fpl->in_smr = true;					\
3671 })
3672 
3673 #define cache_fpl_smr_exit(fpl) ({				\
3674 	struct cache_fpl *_fpl = (fpl);				\
3675 	MPASS(_fpl->in_smr == true);				\
3676 	vfs_smr_exit();						\
3677 	_fpl->in_smr = false;					\
3678 })
3679 
3680 static int
3681 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3682 {
3683 
3684 	if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3685 		KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3686 		    ("%s: converting to abort from %d at %d, set at %d\n",
3687 		    __func__, fpl->status, line, fpl->line));
3688 	}
3689 	fpl->status = CACHE_FPL_STATUS_ABORTED;
3690 	fpl->line = line;
3691 	return (CACHE_FPL_FAILED);
3692 }
3693 
3694 #define cache_fpl_aborted(x)	cache_fpl_aborted_impl((x), __LINE__)
3695 
3696 static int
3697 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3698 {
3699 
3700 	KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3701 	    ("%s: setting to partial at %d, but already set to %d at %d\n",
3702 	    __func__, line, fpl->status, fpl->line));
3703 	cache_fpl_smr_assert_entered(fpl);
3704 	fpl->status = CACHE_FPL_STATUS_PARTIAL;
3705 	fpl->line = line;
3706 	return (CACHE_FPL_FAILED);
3707 }
3708 
3709 #define cache_fpl_partial(x)	cache_fpl_partial_impl((x), __LINE__)
3710 
3711 static int
3712 cache_fpl_handled_impl(struct cache_fpl *fpl, int error, int line)
3713 {
3714 
3715 	KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3716 	    ("%s: setting to handled at %d, but already set to %d at %d\n",
3717 	    __func__, line, fpl->status, fpl->line));
3718 	cache_fpl_smr_assert_not_entered(fpl);
3719 	MPASS(error != CACHE_FPL_FAILED);
3720 	fpl->status = CACHE_FPL_STATUS_HANDLED;
3721 	fpl->line = line;
3722 	return (error);
3723 }
3724 
3725 #define cache_fpl_handled(x, e)	cache_fpl_handled_impl((x), (e), __LINE__)
3726 
3727 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3728 	(NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
3729 	 FOLLOW | LOCKSHARED | SAVENAME | SAVESTART | WILLBEDIR | ISOPEN | \
3730 	 NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
3731 
3732 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3733 	(ISDOTDOT | MAKEENTRY | ISLASTCN)
3734 
3735 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3736     "supported and internal flags overlap");
3737 
3738 static bool
3739 cache_fpl_islastcn(struct nameidata *ndp)
3740 {
3741 
3742 	return (*ndp->ni_next == 0);
3743 }
3744 
3745 static bool
3746 cache_fpl_isdotdot(struct componentname *cnp)
3747 {
3748 
3749 	if (cnp->cn_namelen == 2 &&
3750 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3751 		return (true);
3752 	return (false);
3753 }
3754 
3755 static bool
3756 cache_can_fplookup(struct cache_fpl *fpl)
3757 {
3758 	struct nameidata *ndp;
3759 	struct componentname *cnp;
3760 	struct thread *td;
3761 
3762 	ndp = fpl->ndp;
3763 	cnp = fpl->cnp;
3764 	td = cnp->cn_thread;
3765 
3766 	if (!cache_fast_lookup) {
3767 		cache_fpl_aborted(fpl);
3768 		return (false);
3769 	}
3770 #ifdef MAC
3771 	if (mac_vnode_check_lookup_enabled()) {
3772 		cache_fpl_aborted(fpl);
3773 		return (false);
3774 	}
3775 #endif
3776 	if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3777 		cache_fpl_aborted(fpl);
3778 		return (false);
3779 	}
3780 	if (IN_CAPABILITY_MODE(td)) {
3781 		cache_fpl_aborted(fpl);
3782 		return (false);
3783 	}
3784 	if (AUDITING_TD(td)) {
3785 		cache_fpl_aborted(fpl);
3786 		return (false);
3787 	}
3788 	if (ndp->ni_startdir != NULL) {
3789 		cache_fpl_aborted(fpl);
3790 		return (false);
3791 	}
3792 	return (true);
3793 }
3794 
3795 static int
3796 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
3797 {
3798 	struct nameidata *ndp;
3799 	int error;
3800 	bool fsearch;
3801 
3802 	ndp = fpl->ndp;
3803 	error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
3804 	if (__predict_false(error != 0)) {
3805 		cache_fpl_smr_exit(fpl);
3806 		return (cache_fpl_aborted(fpl));
3807 	}
3808 	fpl->fsearch = fsearch;
3809 	return (0);
3810 }
3811 
3812 static bool
3813 cache_fplookup_vnode_supported(struct vnode *vp)
3814 {
3815 
3816 	return (vp->v_type != VLNK);
3817 }
3818 
3819 static int __noinline
3820 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
3821     uint32_t hash)
3822 {
3823 	struct componentname *cnp;
3824 	struct vnode *dvp;
3825 
3826 	cnp = fpl->cnp;
3827 	dvp = fpl->dvp;
3828 
3829 	cache_fpl_smr_exit(fpl);
3830 	if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
3831 		return (cache_fpl_handled(fpl, ENOENT));
3832 	else
3833 		return (cache_fpl_aborted(fpl));
3834 }
3835 
3836 /*
3837  * The target vnode is not supported, prepare for the slow path to take over.
3838  */
3839 static int __noinline
3840 cache_fplookup_partial_setup(struct cache_fpl *fpl)
3841 {
3842 	struct nameidata *ndp;
3843 	struct componentname *cnp;
3844 	enum vgetstate dvs;
3845 	struct vnode *dvp;
3846 	struct pwd *pwd;
3847 	seqc_t dvp_seqc;
3848 
3849 	ndp = fpl->ndp;
3850 	cnp = fpl->cnp;
3851 	pwd = fpl->pwd;
3852 	dvp = fpl->dvp;
3853 	dvp_seqc = fpl->dvp_seqc;
3854 
3855 	if (!pwd_hold_smr(pwd)) {
3856 		cache_fpl_smr_exit(fpl);
3857 		return (cache_fpl_aborted(fpl));
3858 	}
3859 
3860 	dvs = vget_prep_smr(dvp);
3861 	cache_fpl_smr_exit(fpl);
3862 	if (__predict_false(dvs == VGET_NONE)) {
3863 		pwd_drop(pwd);
3864 		return (cache_fpl_aborted(fpl));
3865 	}
3866 
3867 	vget_finish_ref(dvp, dvs);
3868 	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3869 		vrele(dvp);
3870 		pwd_drop(pwd);
3871 		return (cache_fpl_aborted(fpl));
3872 	}
3873 
3874 	cache_fpl_restore_partial(fpl, &fpl->snd);
3875 
3876 	ndp->ni_startdir = dvp;
3877 	cnp->cn_flags |= MAKEENTRY;
3878 	if (cache_fpl_islastcn(ndp))
3879 		cnp->cn_flags |= ISLASTCN;
3880 	if (cache_fpl_isdotdot(cnp))
3881 		cnp->cn_flags |= ISDOTDOT;
3882 
3883 	return (0);
3884 }
3885 
3886 static int
3887 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
3888 {
3889 	struct componentname *cnp;
3890 	struct vnode *tvp;
3891 	seqc_t tvp_seqc;
3892 	int error, lkflags;
3893 
3894 	cnp = fpl->cnp;
3895 	tvp = fpl->tvp;
3896 	tvp_seqc = fpl->tvp_seqc;
3897 
3898 	if ((cnp->cn_flags & LOCKLEAF) != 0) {
3899 		lkflags = LK_SHARED;
3900 		if ((cnp->cn_flags & LOCKSHARED) == 0)
3901 			lkflags = LK_EXCLUSIVE;
3902 		error = vget_finish(tvp, lkflags, tvs);
3903 		if (__predict_false(error != 0)) {
3904 			return (cache_fpl_aborted(fpl));
3905 		}
3906 	} else {
3907 		vget_finish_ref(tvp, tvs);
3908 	}
3909 
3910 	if (!vn_seqc_consistent(tvp, tvp_seqc)) {
3911 		if ((cnp->cn_flags & LOCKLEAF) != 0)
3912 			vput(tvp);
3913 		else
3914 			vrele(tvp);
3915 		return (cache_fpl_aborted(fpl));
3916 	}
3917 
3918 	return (cache_fpl_handled(fpl, 0));
3919 }
3920 
3921 /*
3922  * They want to possibly modify the state of the namecache.
3923  *
3924  * Don't try to match the API contract, just leave.
3925  * TODO: this leaves scalability on the table
3926  */
3927 static int
3928 cache_fplookup_final_modifying(struct cache_fpl *fpl)
3929 {
3930 	struct componentname *cnp;
3931 
3932 	cnp = fpl->cnp;
3933 	MPASS(cnp->cn_nameiop != LOOKUP);
3934 	return (cache_fpl_partial(fpl));
3935 }
3936 
3937 static int __noinline
3938 cache_fplookup_final_withparent(struct cache_fpl *fpl)
3939 {
3940 	struct componentname *cnp;
3941 	enum vgetstate dvs, tvs;
3942 	struct vnode *dvp, *tvp;
3943 	seqc_t dvp_seqc;
3944 	int error;
3945 
3946 	cnp = fpl->cnp;
3947 	dvp = fpl->dvp;
3948 	dvp_seqc = fpl->dvp_seqc;
3949 	tvp = fpl->tvp;
3950 
3951 	MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
3952 
3953 	/*
3954 	 * This is less efficient than it can be for simplicity.
3955 	 */
3956 	dvs = vget_prep_smr(dvp);
3957 	if (__predict_false(dvs == VGET_NONE)) {
3958 		return (cache_fpl_aborted(fpl));
3959 	}
3960 	tvs = vget_prep_smr(tvp);
3961 	if (__predict_false(tvs == VGET_NONE)) {
3962 		cache_fpl_smr_exit(fpl);
3963 		vget_abort(dvp, dvs);
3964 		return (cache_fpl_aborted(fpl));
3965 	}
3966 
3967 	cache_fpl_smr_exit(fpl);
3968 
3969 	if ((cnp->cn_flags & LOCKPARENT) != 0) {
3970 		error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
3971 		if (__predict_false(error != 0)) {
3972 			vget_abort(tvp, tvs);
3973 			return (cache_fpl_aborted(fpl));
3974 		}
3975 	} else {
3976 		vget_finish_ref(dvp, dvs);
3977 	}
3978 
3979 	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3980 		vget_abort(tvp, tvs);
3981 		if ((cnp->cn_flags & LOCKPARENT) != 0)
3982 			vput(dvp);
3983 		else
3984 			vrele(dvp);
3985 		return (cache_fpl_aborted(fpl));
3986 	}
3987 
3988 	error = cache_fplookup_final_child(fpl, tvs);
3989 	if (__predict_false(error != 0)) {
3990 		MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
3991 		if ((cnp->cn_flags & LOCKPARENT) != 0)
3992 			vput(dvp);
3993 		else
3994 			vrele(dvp);
3995 		return (error);
3996 	}
3997 
3998 	MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
3999 	return (0);
4000 }
4001 
4002 static int
4003 cache_fplookup_final(struct cache_fpl *fpl)
4004 {
4005 	struct componentname *cnp;
4006 	enum vgetstate tvs;
4007 	struct vnode *dvp, *tvp;
4008 	seqc_t dvp_seqc;
4009 
4010 	cnp = fpl->cnp;
4011 	dvp = fpl->dvp;
4012 	dvp_seqc = fpl->dvp_seqc;
4013 	tvp = fpl->tvp;
4014 
4015 	VNPASS(cache_fplookup_vnode_supported(dvp), dvp);
4016 
4017 	if (cnp->cn_nameiop != LOOKUP) {
4018 		return (cache_fplookup_final_modifying(fpl));
4019 	}
4020 
4021 	if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4022 		return (cache_fplookup_final_withparent(fpl));
4023 
4024 	tvs = vget_prep_smr(tvp);
4025 	if (__predict_false(tvs == VGET_NONE)) {
4026 		return (cache_fpl_partial(fpl));
4027 	}
4028 
4029 	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4030 		cache_fpl_smr_exit(fpl);
4031 		vget_abort(tvp, tvs);
4032 		return (cache_fpl_aborted(fpl));
4033 	}
4034 
4035 	cache_fpl_smr_exit(fpl);
4036 	return (cache_fplookup_final_child(fpl, tvs));
4037 }
4038 
4039 static int __noinline
4040 cache_fplookup_dot(struct cache_fpl *fpl)
4041 {
4042 	struct vnode *dvp;
4043 
4044 	dvp = fpl->dvp;
4045 
4046 	fpl->tvp = dvp;
4047 	fpl->tvp_seqc = vn_seqc_read_any(dvp);
4048 	if (seqc_in_modify(fpl->tvp_seqc)) {
4049 		return (cache_fpl_aborted(fpl));
4050 	}
4051 
4052 	counter_u64_add(dothits, 1);
4053 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", dvp);
4054 
4055 	return (0);
4056 }
4057 
4058 static int __noinline
4059 cache_fplookup_dotdot(struct cache_fpl *fpl)
4060 {
4061 	struct nameidata *ndp;
4062 	struct componentname *cnp;
4063 	struct namecache *ncp;
4064 	struct vnode *dvp;
4065 	struct prison *pr;
4066 	u_char nc_flag;
4067 
4068 	ndp = fpl->ndp;
4069 	cnp = fpl->cnp;
4070 	dvp = fpl->dvp;
4071 
4072 	/*
4073 	 * XXX this is racy the same way regular lookup is
4074 	 */
4075 	for (pr = cnp->cn_cred->cr_prison; pr != NULL;
4076 	    pr = pr->pr_parent)
4077 		if (dvp == pr->pr_root)
4078 			break;
4079 
4080 	if (dvp == ndp->ni_rootdir ||
4081 	    dvp == ndp->ni_topdir ||
4082 	    dvp == rootvnode ||
4083 	    pr != NULL) {
4084 		fpl->tvp = dvp;
4085 		fpl->tvp_seqc = vn_seqc_read_any(dvp);
4086 		if (seqc_in_modify(fpl->tvp_seqc)) {
4087 			return (cache_fpl_aborted(fpl));
4088 		}
4089 		return (0);
4090 	}
4091 
4092 	if ((dvp->v_vflag & VV_ROOT) != 0) {
4093 		/*
4094 		 * TODO
4095 		 * The opposite of climb mount is needed here.
4096 		 */
4097 		return (cache_fpl_aborted(fpl));
4098 	}
4099 
4100 	ncp = atomic_load_ptr(&dvp->v_cache_dd);
4101 	if (ncp == NULL) {
4102 		return (cache_fpl_aborted(fpl));
4103 	}
4104 
4105 	nc_flag = atomic_load_char(&ncp->nc_flag);
4106 	if ((nc_flag & NCF_ISDOTDOT) != 0) {
4107 		if ((nc_flag & NCF_NEGATIVE) != 0)
4108 			return (cache_fpl_aborted(fpl));
4109 		fpl->tvp = ncp->nc_vp;
4110 	} else {
4111 		fpl->tvp = ncp->nc_dvp;
4112 	}
4113 
4114 	if (!cache_ncp_canuse(ncp)) {
4115 		return (cache_fpl_aborted(fpl));
4116 	}
4117 
4118 	fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
4119 	if (seqc_in_modify(fpl->tvp_seqc)) {
4120 		return (cache_fpl_partial(fpl));
4121 	}
4122 
4123 	counter_u64_add(dotdothits, 1);
4124 	return (0);
4125 }
4126 
4127 static int __noinline
4128 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
4129 {
4130 	u_char nc_flag;
4131 	bool neg_promote;
4132 
4133 	nc_flag = atomic_load_char(&ncp->nc_flag);
4134 	MPASS((nc_flag & NCF_NEGATIVE) != 0);
4135 	/*
4136 	 * If they want to create an entry we need to replace this one.
4137 	 */
4138 	if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
4139 		/*
4140 		 * TODO
4141 		 * This should call something similar to
4142 		 * cache_fplookup_final_modifying.
4143 		 */
4144 		return (cache_fpl_partial(fpl));
4145 	}
4146 	neg_promote = cache_neg_hit_prep(ncp);
4147 	if (!cache_ncp_canuse(ncp)) {
4148 		cache_neg_hit_abort(ncp);
4149 		return (cache_fpl_partial(fpl));
4150 	}
4151 	if (__predict_false((nc_flag & NCF_WHITE) != 0)) {
4152 		cache_neg_hit_abort(ncp);
4153 		return (cache_fpl_partial(fpl));
4154 	}
4155 	if (neg_promote) {
4156 		return (cache_fplookup_negative_promote(fpl, ncp, hash));
4157 	}
4158 	cache_neg_hit_finish(ncp);
4159 	cache_fpl_smr_exit(fpl);
4160 	return (cache_fpl_handled(fpl, ENOENT));
4161 }
4162 
4163 static int
4164 cache_fplookup_next(struct cache_fpl *fpl)
4165 {
4166 	struct componentname *cnp;
4167 	struct namecache *ncp;
4168 	struct vnode *dvp, *tvp;
4169 	u_char nc_flag;
4170 	uint32_t hash;
4171 
4172 	cnp = fpl->cnp;
4173 	dvp = fpl->dvp;
4174 
4175 	if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.')) {
4176 		return (cache_fplookup_dot(fpl));
4177 	}
4178 
4179 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
4180 
4181 	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
4182 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
4183 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
4184 			break;
4185 	}
4186 
4187 	/*
4188 	 * If there is no entry we have to punt to the slow path to perform
4189 	 * actual lookup. Should there be nothing with this name a negative
4190 	 * entry will be created.
4191 	 */
4192 	if (__predict_false(ncp == NULL)) {
4193 		return (cache_fpl_partial(fpl));
4194 	}
4195 
4196 	tvp = atomic_load_ptr(&ncp->nc_vp);
4197 	nc_flag = atomic_load_char(&ncp->nc_flag);
4198 	if ((nc_flag & NCF_NEGATIVE) != 0) {
4199 		return (cache_fplookup_neg(fpl, ncp, hash));
4200 	}
4201 
4202 	if (!cache_ncp_canuse(ncp)) {
4203 		return (cache_fpl_partial(fpl));
4204 	}
4205 
4206 	fpl->tvp = tvp;
4207 	fpl->tvp_seqc = vn_seqc_read_any(tvp);
4208 	if (seqc_in_modify(fpl->tvp_seqc)) {
4209 		return (cache_fpl_partial(fpl));
4210 	}
4211 
4212 	if (!cache_fplookup_vnode_supported(tvp)) {
4213 		return (cache_fpl_partial(fpl));
4214 	}
4215 
4216 	counter_u64_add(numposhits, 1);
4217 	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
4218 	return (0);
4219 }
4220 
4221 static bool
4222 cache_fplookup_mp_supported(struct mount *mp)
4223 {
4224 
4225 	if (mp == NULL)
4226 		return (false);
4227 	if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
4228 		return (false);
4229 	return (true);
4230 }
4231 
4232 /*
4233  * Walk up the mount stack (if any).
4234  *
4235  * Correctness is provided in the following ways:
4236  * - all vnodes are protected from freeing with SMR
4237  * - struct mount objects are type stable making them always safe to access
4238  * - stability of the particular mount is provided by busying it
4239  * - relationship between the vnode which is mounted on and the mount is
4240  *   verified with the vnode sequence counter after busying
4241  * - association between root vnode of the mount and the mount is protected
4242  *   by busy
4243  *
4244  * From that point on we can read the sequence counter of the root vnode
4245  * and get the next mount on the stack (if any) using the same protection.
4246  *
4247  * By the end of successful walk we are guaranteed the reached state was
4248  * indeed present at least at some point which matches the regular lookup.
4249  */
4250 static int __noinline
4251 cache_fplookup_climb_mount(struct cache_fpl *fpl)
4252 {
4253 	struct mount *mp, *prev_mp;
4254 	struct mount_pcpu *mpcpu, *prev_mpcpu;
4255 	struct vnode *vp;
4256 	seqc_t vp_seqc;
4257 
4258 	vp = fpl->tvp;
4259 	vp_seqc = fpl->tvp_seqc;
4260 
4261 	VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
4262 	mp = atomic_load_ptr(&vp->v_mountedhere);
4263 	if (mp == NULL)
4264 		return (0);
4265 
4266 	prev_mp = NULL;
4267 	for (;;) {
4268 		if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
4269 			if (prev_mp != NULL)
4270 				vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
4271 			return (cache_fpl_partial(fpl));
4272 		}
4273 		if (prev_mp != NULL)
4274 			vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
4275 		if (!vn_seqc_consistent(vp, vp_seqc)) {
4276 			vfs_op_thread_exit_crit(mp, mpcpu);
4277 			return (cache_fpl_partial(fpl));
4278 		}
4279 		if (!cache_fplookup_mp_supported(mp)) {
4280 			vfs_op_thread_exit_crit(mp, mpcpu);
4281 			return (cache_fpl_partial(fpl));
4282 		}
4283 		vp = atomic_load_ptr(&mp->mnt_rootvnode);
4284 		if (vp == NULL || VN_IS_DOOMED(vp)) {
4285 			vfs_op_thread_exit_crit(mp, mpcpu);
4286 			return (cache_fpl_partial(fpl));
4287 		}
4288 		vp_seqc = vn_seqc_read_any(vp);
4289 		if (seqc_in_modify(vp_seqc)) {
4290 			vfs_op_thread_exit_crit(mp, mpcpu);
4291 			return (cache_fpl_partial(fpl));
4292 		}
4293 		prev_mp = mp;
4294 		prev_mpcpu = mpcpu;
4295 		mp = atomic_load_ptr(&vp->v_mountedhere);
4296 		if (mp == NULL)
4297 			break;
4298 	}
4299 
4300 	vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
4301 	fpl->tvp = vp;
4302 	fpl->tvp_seqc = vp_seqc;
4303 	return (0);
4304 }
4305 
4306 static bool
4307 cache_fplookup_need_climb_mount(struct cache_fpl *fpl)
4308 {
4309 	struct mount *mp;
4310 	struct vnode *vp;
4311 
4312 	vp = fpl->tvp;
4313 
4314 	/*
4315 	 * Hack: while this is a union, the pointer tends to be NULL so save on
4316 	 * a branch.
4317 	 */
4318 	mp = atomic_load_ptr(&vp->v_mountedhere);
4319 	if (mp == NULL)
4320 		return (false);
4321 	if (vp->v_type == VDIR)
4322 		return (true);
4323 	return (false);
4324 }
4325 
4326 /*
4327  * Parse the path.
4328  *
4329  * The code was originally copy-pasted from regular lookup and despite
4330  * clean ups leaves performance on the table. Any modifications here
4331  * must take into account that in case off fallback the resulting
4332  * nameidata state has to be compatible with the original.
4333  */
4334 static int
4335 cache_fplookup_parse(struct cache_fpl *fpl)
4336 {
4337 	struct nameidata *ndp;
4338 	struct componentname *cnp;
4339 	char *cp;
4340 
4341 	ndp = fpl->ndp;
4342 	cnp = fpl->cnp;
4343 
4344 	/*
4345 	 * Search a new directory.
4346 	 *
4347 	 * The last component of the filename is left accessible via
4348 	 * cnp->cn_nameptr for callers that need the name. Callers needing
4349 	 * the name set the SAVENAME flag. When done, they assume
4350 	 * responsibility for freeing the pathname buffer.
4351 	 */
4352 	for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
4353 		continue;
4354 	cnp->cn_namelen = cp - cnp->cn_nameptr;
4355 	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4356 		cache_fpl_smr_exit(fpl);
4357 		return (cache_fpl_handled(fpl, ENAMETOOLONG));
4358 	}
4359 	ndp->ni_pathlen -= cnp->cn_namelen;
4360 	KASSERT(ndp->ni_pathlen <= PATH_MAX,
4361 	    ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
4362 	ndp->ni_next = cp;
4363 
4364 	/*
4365 	 * Replace multiple slashes by a single slash and trailing slashes
4366 	 * by a null.  This must be done before VOP_LOOKUP() because some
4367 	 * fs's don't know about trailing slashes.  Remember if there were
4368 	 * trailing slashes to handle symlinks, existing non-directories
4369 	 * and non-existing files that won't be directories specially later.
4370 	 */
4371 	while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
4372 		cp++;
4373 		ndp->ni_pathlen--;
4374 		if (*cp == '\0') {
4375 			/*
4376 			 * TODO
4377 			 * Regular lookup performs the following:
4378 			 * *ndp->ni_next = '\0';
4379 			 * cnp->cn_flags |= TRAILINGSLASH;
4380 			 *
4381 			 * Which is problematic since it modifies data read
4382 			 * from userspace. Then if fast path lookup was to
4383 			 * abort we would have to either restore it or convey
4384 			 * the flag. Since this is a corner case just ignore
4385 			 * it for simplicity.
4386 			 */
4387 			return (cache_fpl_partial(fpl));
4388 		}
4389 	}
4390 	ndp->ni_next = cp;
4391 
4392 	/*
4393 	 * Check for degenerate name (e.g. / or "")
4394 	 * which is a way of talking about a directory,
4395 	 * e.g. like "/." or ".".
4396 	 *
4397 	 * TODO
4398 	 * Another corner case handled by the regular lookup
4399 	 */
4400 	if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
4401 		return (cache_fpl_partial(fpl));
4402 	}
4403 	return (0);
4404 }
4405 
4406 static void
4407 cache_fplookup_parse_advance(struct cache_fpl *fpl)
4408 {
4409 	struct nameidata *ndp;
4410 	struct componentname *cnp;
4411 
4412 	ndp = fpl->ndp;
4413 	cnp = fpl->cnp;
4414 
4415 	cnp->cn_nameptr = ndp->ni_next;
4416 	while (*cnp->cn_nameptr == '/') {
4417 		cnp->cn_nameptr++;
4418 		ndp->ni_pathlen--;
4419 	}
4420 }
4421 
4422 /*
4423  * See the API contract for VOP_FPLOOKUP_VEXEC.
4424  */
4425 static int __noinline
4426 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
4427 {
4428 	struct vnode *dvp;
4429 	seqc_t dvp_seqc;
4430 
4431 	dvp = fpl->dvp;
4432 	dvp_seqc = fpl->dvp_seqc;
4433 
4434 	/*
4435 	 * Hack: they may be looking up foo/bar, where foo is a
4436 	 * regular file. In such a case we need to turn ENOTDIR,
4437 	 * but we may happen to get here with a different error.
4438 	 */
4439 	if (dvp->v_type != VDIR) {
4440 		/*
4441 		 * The check here is predominantly to catch
4442 		 * EOPNOTSUPP from dead_vnodeops. If the vnode
4443 		 * gets doomed past this point it is going to
4444 		 * fail seqc verification.
4445 		 */
4446 		if (VN_IS_DOOMED(dvp)) {
4447 			return (cache_fpl_aborted(fpl));
4448 		}
4449 		error = ENOTDIR;
4450 	}
4451 
4452 	/*
4453 	 * Hack: handle O_SEARCH.
4454 	 *
4455 	 * Open Group Base Specifications Issue 7, 2018 edition states:
4456 	 * If the access mode of the open file description associated with the
4457 	 * file descriptor is not O_SEARCH, the function shall check whether
4458 	 * directory searches are permitted using the current permissions of
4459 	 * the directory underlying the file descriptor. If the access mode is
4460 	 * O_SEARCH, the function shall not perform the check.
4461 	 *
4462 	 * Regular lookup tests for the NOEXECCHECK flag for every path
4463 	 * component to decide whether to do the permission check. However,
4464 	 * since most lookups never have the flag (and when they do it is only
4465 	 * present for the first path component), lockless lookup only acts on
4466 	 * it if there is a permission problem. Here the flag is represented
4467 	 * with a boolean so that we don't have to clear it on the way out.
4468 	 *
4469 	 * For simplicity this always aborts.
4470 	 * TODO: check if this is the first lookup and ignore the permission
4471 	 * problem. Note the flag has to survive fallback (if it happens to be
4472 	 * performed).
4473 	 */
4474 	if (fpl->fsearch) {
4475 		return (cache_fpl_aborted(fpl));
4476 	}
4477 
4478 	switch (error) {
4479 	case EAGAIN:
4480 		if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4481 			error = cache_fpl_aborted(fpl);
4482 		} else {
4483 			cache_fpl_partial(fpl);
4484 		}
4485 		break;
4486 	default:
4487 		if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4488 			error = cache_fpl_aborted(fpl);
4489 		} else {
4490 			cache_fpl_smr_exit(fpl);
4491 			cache_fpl_handled(fpl, error);
4492 		}
4493 		break;
4494 	}
4495 	return (error);
4496 }
4497 
4498 static int
4499 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
4500 {
4501 	struct nameidata *ndp;
4502 	struct componentname *cnp;
4503 	struct mount *mp;
4504 	int error;
4505 
4506 	error = CACHE_FPL_FAILED;
4507 	ndp = fpl->ndp;
4508 	cnp = fpl->cnp;
4509 
4510 	cache_fpl_checkpoint(fpl, &fpl->snd);
4511 
4512 	fpl->dvp = dvp;
4513 	fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
4514 	if (seqc_in_modify(fpl->dvp_seqc)) {
4515 		cache_fpl_aborted(fpl);
4516 		goto out;
4517 	}
4518 	mp = atomic_load_ptr(&fpl->dvp->v_mount);
4519 	if (!cache_fplookup_mp_supported(mp)) {
4520 		cache_fpl_aborted(fpl);
4521 		goto out;
4522 	}
4523 
4524 	VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4525 
4526 	for (;;) {
4527 		error = cache_fplookup_parse(fpl);
4528 		if (__predict_false(error != 0)) {
4529 			break;
4530 		}
4531 
4532 		VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4533 
4534 		error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
4535 		if (__predict_false(error != 0)) {
4536 			error = cache_fplookup_failed_vexec(fpl, error);
4537 			break;
4538 		}
4539 
4540 		if (__predict_false(cache_fpl_isdotdot(cnp))) {
4541 			error = cache_fplookup_dotdot(fpl);
4542 			if (__predict_false(error != 0)) {
4543 				break;
4544 			}
4545 		} else {
4546 			error = cache_fplookup_next(fpl);
4547 			if (__predict_false(error != 0)) {
4548 				break;
4549 			}
4550 
4551 			VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4552 
4553 			if (cache_fplookup_need_climb_mount(fpl)) {
4554 				error = cache_fplookup_climb_mount(fpl);
4555 				if (__predict_false(error != 0)) {
4556 					break;
4557 				}
4558 			}
4559 		}
4560 
4561 		VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4562 
4563 		if (cache_fpl_islastcn(ndp)) {
4564 			error = cache_fplookup_final(fpl);
4565 			break;
4566 		}
4567 
4568 		if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
4569 			error = cache_fpl_aborted(fpl);
4570 			break;
4571 		}
4572 
4573 		fpl->dvp = fpl->tvp;
4574 		fpl->dvp_seqc = fpl->tvp_seqc;
4575 
4576 		cache_fplookup_parse_advance(fpl);
4577 		cache_fpl_checkpoint(fpl, &fpl->snd);
4578 	}
4579 out:
4580 	switch (fpl->status) {
4581 	case CACHE_FPL_STATUS_UNSET:
4582 		__assert_unreachable();
4583 		break;
4584 	case CACHE_FPL_STATUS_PARTIAL:
4585 		cache_fpl_smr_assert_entered(fpl);
4586 		return (cache_fplookup_partial_setup(fpl));
4587 	case CACHE_FPL_STATUS_ABORTED:
4588 		if (fpl->in_smr)
4589 			cache_fpl_smr_exit(fpl);
4590 		return (CACHE_FPL_FAILED);
4591 	case CACHE_FPL_STATUS_HANDLED:
4592 		MPASS(error != CACHE_FPL_FAILED);
4593 		cache_fpl_smr_assert_not_entered(fpl);
4594 		/*
4595 		 * A common error is ENOENT.
4596 		 */
4597 		if (error != 0) {
4598 			ndp->ni_dvp = NULL;
4599 			ndp->ni_vp = NULL;
4600 			cache_fpl_cleanup_cnp(cnp);
4601 			return (error);
4602 		}
4603 		ndp->ni_dvp = fpl->dvp;
4604 		ndp->ni_vp = fpl->tvp;
4605 		if (cnp->cn_flags & SAVENAME)
4606 			cnp->cn_flags |= HASBUF;
4607 		else
4608 			cache_fpl_cleanup_cnp(cnp);
4609 		return (error);
4610 	}
4611 	__assert_unreachable();
4612 }
4613 
4614 /*
4615  * Fast path lookup protected with SMR and sequence counters.
4616  *
4617  * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
4618  *
4619  * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
4620  * outlined below.
4621  *
4622  * Traditional vnode lookup conceptually looks like this:
4623  *
4624  * vn_lock(current);
4625  * for (;;) {
4626  *	next = find();
4627  *	vn_lock(next);
4628  *	vn_unlock(current);
4629  *	current = next;
4630  *	if (last)
4631  *	    break;
4632  * }
4633  * return (current);
4634  *
4635  * Each jump to the next vnode is safe memory-wise and atomic with respect to
4636  * any modifications thanks to holding respective locks.
4637  *
4638  * The same guarantee can be provided with a combination of safe memory
4639  * reclamation and sequence counters instead. If all operations which affect
4640  * the relationship between the current vnode and the one we are looking for
4641  * also modify the counter, we can verify whether all the conditions held as
4642  * we made the jump. This includes things like permissions, mount points etc.
4643  * Counter modification is provided by enclosing relevant places in
4644  * vn_seqc_write_begin()/end() calls.
4645  *
4646  * Thus this translates to:
4647  *
4648  * vfs_smr_enter();
4649  * dvp_seqc = seqc_read_any(dvp);
4650  * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
4651  *     abort();
4652  * for (;;) {
4653  * 	tvp = find();
4654  * 	tvp_seqc = seqc_read_any(tvp);
4655  * 	if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
4656  * 	    abort();
4657  * 	if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
4658  * 	    abort();
4659  * 	dvp = tvp; // we know nothing of importance has changed
4660  * 	dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
4661  * 	if (last)
4662  * 	    break;
4663  * }
4664  * vget(); // secure the vnode
4665  * if (!seqc_consistent(tvp, tvp_seqc) // final check
4666  * 	    abort();
4667  * // at this point we know nothing has changed for any parent<->child pair
4668  * // as they were crossed during the lookup, meaning we matched the guarantee
4669  * // of the locked variant
4670  * return (tvp);
4671  *
4672  * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
4673  * - they are called while within vfs_smr protection which they must never exit
4674  * - EAGAIN can be returned to denote checking could not be performed, it is
4675  *   always valid to return it
4676  * - if the sequence counter has not changed the result must be valid
4677  * - if the sequence counter has changed both false positives and false negatives
4678  *   are permitted (since the result will be rejected later)
4679  * - for simple cases of unix permission checks vaccess_vexec_smr can be used
4680  *
4681  * Caveats to watch out for:
4682  * - vnodes are passed unlocked and unreferenced with nothing stopping
4683  *   VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
4684  *   to use atomic_load_ptr to fetch it.
4685  * - the aforementioned object can also get freed, meaning absent other means it
4686  *   should be protected with vfs_smr
4687  * - either safely checking permissions as they are modified or guaranteeing
4688  *   their stability is left to the routine
4689  */
4690 int
4691 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
4692     struct pwd **pwdp)
4693 {
4694 	struct cache_fpl fpl;
4695 	struct pwd *pwd;
4696 	struct vnode *dvp;
4697 	struct componentname *cnp;
4698 	struct nameidata_saved orig;
4699 	int error;
4700 
4701 	MPASS(ndp->ni_lcf == 0);
4702 
4703 	fpl.status = CACHE_FPL_STATUS_UNSET;
4704 	fpl.ndp = ndp;
4705 	fpl.cnp = &ndp->ni_cnd;
4706 	MPASS(curthread == fpl.cnp->cn_thread);
4707 
4708 	if ((fpl.cnp->cn_flags & SAVESTART) != 0)
4709 		MPASS(fpl.cnp->cn_nameiop != LOOKUP);
4710 
4711 	if (!cache_can_fplookup(&fpl)) {
4712 		SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4713 		*status = fpl.status;
4714 		return (EOPNOTSUPP);
4715 	}
4716 
4717 	cache_fpl_checkpoint(&fpl, &orig);
4718 
4719 	cache_fpl_smr_enter_initial(&fpl);
4720 	fpl.fsearch = false;
4721 	pwd = pwd_get_smr();
4722 	fpl.pwd = pwd;
4723 	ndp->ni_rootdir = pwd->pwd_rdir;
4724 	ndp->ni_topdir = pwd->pwd_jdir;
4725 
4726 	cnp = fpl.cnp;
4727 	cnp->cn_nameptr = cnp->cn_pnbuf;
4728 	if (cnp->cn_pnbuf[0] == '/') {
4729 		cache_fpl_handle_root(ndp, &dvp);
4730 		ndp->ni_resflags |= NIRES_ABS;
4731 	} else {
4732 		if (ndp->ni_dirfd == AT_FDCWD) {
4733 			dvp = pwd->pwd_cdir;
4734 		} else {
4735 			error = cache_fplookup_dirfd(&fpl, &dvp);
4736 			if (__predict_false(error != 0)) {
4737 				goto out;
4738 			}
4739 		}
4740 	}
4741 
4742 	SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
4743 
4744 	error = cache_fplookup_impl(dvp, &fpl);
4745 out:
4746 	cache_fpl_smr_assert_not_entered(&fpl);
4747 	SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4748 
4749 	*status = fpl.status;
4750 	switch (fpl.status) {
4751 	case CACHE_FPL_STATUS_UNSET:
4752 		__assert_unreachable();
4753 		break;
4754 	case CACHE_FPL_STATUS_HANDLED:
4755 		SDT_PROBE3(vfs, namei, lookup, return, error,
4756 		    (error == 0 ? ndp->ni_vp : NULL), true);
4757 		break;
4758 	case CACHE_FPL_STATUS_PARTIAL:
4759 		*pwdp = fpl.pwd;
4760 		/*
4761 		 * Status restored by cache_fplookup_partial_setup.
4762 		 */
4763 		break;
4764 	case CACHE_FPL_STATUS_ABORTED:
4765 		cache_fpl_restore_abort(&fpl, &orig);
4766 		break;
4767 	}
4768 	return (error);
4769 }
4770