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