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