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