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