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