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