]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_cache.c
cache: reimplement purgevfs to iterate vnodes instead of the entire hash
[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
71 #include <sys/capsicum.h>
72
73 #include <security/audit/audit.h>
74 #include <security/mac/mac_framework.h>
75
76 #ifdef DDB
77 #include <ddb/ddb.h>
78 #endif
79
80 #include <vm/uma.h>
81
82 SDT_PROVIDER_DECLARE(vfs);
83 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
84     "struct vnode *");
85 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
86     "char *");
87 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
88     "const char *");
89 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
90     "struct namecache *", "int", "int");
91 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
92 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
93     "char *", "struct vnode *");
94 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
95 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
96     "struct vnode *", "char *");
97 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
98     "struct vnode *");
99 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
100     "struct vnode *", "char *");
101 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
102     "char *");
103 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
104     "struct componentname *");
105 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
106     "struct componentname *");
107 SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
108 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
109 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
110 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
111     "struct vnode *");
112 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
113     "char *");
114 SDT_PROBE_DEFINE2(vfs, namecache, shrink_negative, done, "struct vnode *",
115     "char *");
116
117 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
118 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
119 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
120
121 /*
122  * This structure describes the elements in the cache of recent
123  * names looked up by namei.
124  */
125 struct negstate {
126         u_char neg_flag;
127 };
128 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
129     "the state must fit in a union with a pointer without growing it");
130
131 struct  namecache {
132         LIST_ENTRY(namecache) nc_src;   /* source vnode list */
133         TAILQ_ENTRY(namecache) nc_dst;  /* destination vnode list */
134         CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
135         struct  vnode *nc_dvp;          /* vnode of parent of name */
136         union {
137                 struct  vnode *nu_vp;   /* vnode the name refers to */
138                 struct  negstate nu_neg;/* negative entry state */
139         } n_un;
140         u_char  nc_flag;                /* flag bits */
141         u_char  nc_nlen;                /* length of name */
142         char    nc_name[0];             /* segment name + nul */
143 };
144
145 /*
146  * struct namecache_ts repeats struct namecache layout up to the
147  * nc_nlen member.
148  * struct namecache_ts is used in place of struct namecache when time(s) need
149  * to be stored.  The nc_dotdottime field is used when a cache entry is mapping
150  * both a non-dotdot directory name plus dotdot for the directory's
151  * parent.
152  *
153  * See below for alignment requirement.
154  */
155 struct  namecache_ts {
156         struct  timespec nc_time;       /* timespec provided by fs */
157         struct  timespec nc_dotdottime; /* dotdot timespec provided by fs */
158         int     nc_ticks;               /* ticks value when entry was added */
159         struct namecache nc_nc;
160 };
161
162 /*
163  * At least mips n32 performs 64-bit accesses to timespec as found
164  * in namecache_ts and requires them to be aligned. Since others
165  * may be in the same spot suffer a little bit and enforce the
166  * alignment for everyone. Note this is a nop for 64-bit platforms.
167  */
168 #define CACHE_ZONE_ALIGNMENT    UMA_ALIGNOF(time_t)
169 #define CACHE_PATH_CUTOFF       39
170
171 #define CACHE_ZONE_SMALL_SIZE           (sizeof(struct namecache) + CACHE_PATH_CUTOFF + 1)
172 #define CACHE_ZONE_SMALL_TS_SIZE        (sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1)
173 #define CACHE_ZONE_LARGE_SIZE           (sizeof(struct namecache) + NAME_MAX + 1)
174 #define CACHE_ZONE_LARGE_TS_SIZE        (sizeof(struct namecache_ts) + NAME_MAX + 1)
175
176 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
177 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
178 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
179 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
180
181 #define nc_vp           n_un.nu_vp
182 #define nc_neg          n_un.nu_neg
183
184 /*
185  * Flags in namecache.nc_flag
186  */
187 #define NCF_WHITE       0x01
188 #define NCF_ISDOTDOT    0x02
189 #define NCF_TS          0x04
190 #define NCF_DTS         0x08
191 #define NCF_DVDROP      0x10
192 #define NCF_NEGATIVE    0x20
193 #define NCF_INVALID     0x40
194 #define NCF_WIP         0x80
195
196 /*
197  * Flags in negstate.neg_flag
198  */
199 #define NEG_HOT         0x01
200
201 /*
202  * Mark an entry as invalid.
203  *
204  * This is called before it starts getting deconstructed.
205  */
206 static void
207 cache_ncp_invalidate(struct namecache *ncp)
208 {
209
210         KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
211             ("%s: entry %p already invalid", __func__, ncp));
212         atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
213         atomic_thread_fence_rel();
214 }
215
216 /*
217  * Check whether the entry can be safely used.
218  *
219  * All places which elide locks are supposed to call this after they are
220  * done with reading from an entry.
221  */
222 static bool
223 cache_ncp_canuse(struct namecache *ncp)
224 {
225
226         atomic_thread_fence_acq();
227         return ((atomic_load_char(&ncp->nc_flag) & (NCF_INVALID | NCF_WIP)) == 0);
228 }
229
230 /*
231  * Name caching works as follows:
232  *
233  * Names found by directory scans are retained in a cache
234  * for future reference.  It is managed LRU, so frequently
235  * used names will hang around.  Cache is indexed by hash value
236  * obtained from (dvp, name) where dvp refers to the directory
237  * containing name.
238  *
239  * If it is a "negative" entry, (i.e. for a name that is known NOT to
240  * exist) the vnode pointer will be NULL.
241  *
242  * Upon reaching the last segment of a path, if the reference
243  * is for DELETE, or NOCACHE is set (rewrite), and the
244  * name is located in the cache, it will be dropped.
245  *
246  * These locks are used (in the order in which they can be taken):
247  * NAME         TYPE    ROLE
248  * vnodelock    mtx     vnode lists and v_cache_dd field protection
249  * bucketlock   mtx     for access to given set of hash buckets
250  * neglist      mtx     negative entry LRU management
251  *
252  * Additionally, ncneg_shrink_lock mtx is used to have at most one thread
253  * shrinking the LRU list.
254  *
255  * It is legal to take multiple vnodelock and bucketlock locks. The locking
256  * order is lower address first. Both are recursive.
257  *
258  * "." lookups are lockless.
259  *
260  * ".." and vnode -> name lookups require vnodelock.
261  *
262  * name -> vnode lookup requires the relevant bucketlock to be held for reading.
263  *
264  * Insertions and removals of entries require involved vnodes and bucketlocks
265  * to be locked to provide safe operation against other threads modifying the
266  * cache.
267  *
268  * Some lookups result in removal of the found entry (e.g. getting rid of a
269  * negative entry with the intent to create a positive one), which poses a
270  * problem when multiple threads reach the state. Similarly, two different
271  * threads can purge two different vnodes and try to remove the same name.
272  *
273  * If the already held vnode lock is lower than the second required lock, we
274  * can just take the other lock. However, in the opposite case, this could
275  * deadlock. As such, this is resolved by trylocking and if that fails unlocking
276  * the first node, locking everything in order and revalidating the state.
277  */
278
279 VFS_SMR_DECLARE;
280
281 /*
282  * Structures associated with name caching.
283  */
284 #define NCHHASH(hash) \
285         (&nchashtbl[(hash) & nchash])
286 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
287 static u_long __read_mostly     nchash;                 /* size of hash table */
288 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
289     "Size of namecache hash table");
290 static u_long __read_mostly     ncnegfactor = 5; /* ratio of negative entries */
291 SYSCTL_ULONG(_vfs, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
292     "Ratio of negative namecache entries");
293 static u_long __exclusive_cache_line    numneg; /* number of negative entries allocated */
294 static u_long __exclusive_cache_line    numcache;/* number of cache entries allocated */
295 u_int ncsizefactor = 2;
296 SYSCTL_UINT(_vfs, OID_AUTO, ncsizefactor, CTLFLAG_RW, &ncsizefactor, 0,
297     "Size factor for namecache");
298 static u_int __read_mostly      ncpurgeminvnodes;
299 SYSCTL_UINT(_vfs, OID_AUTO, ncpurgeminvnodes, CTLFLAG_RW, &ncpurgeminvnodes, 0,
300     "Number of vnodes below which purgevfs ignores the request");
301 static u_int __read_mostly      ncsize; /* the size as computed on creation or resizing */
302
303 struct nchstats nchstats;               /* cache effectiveness statistics */
304
305 static bool __read_frequently cache_fast_revlookup = true;
306 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
307     &cache_fast_revlookup, 0, "");
308
309 static struct mtx __exclusive_cache_line        ncneg_shrink_lock;
310
311 struct neglist {
312         struct mtx              nl_lock;
313         TAILQ_HEAD(, namecache) nl_list;
314 } __aligned(CACHE_LINE_SIZE);
315
316 static struct neglist __read_mostly     *neglists;
317 static struct neglist ncneg_hot;
318 static u_long numhotneg;
319
320 #define ncneghash       3
321 #define numneglists     (ncneghash + 1)
322 static inline struct neglist *
323 NCP2NEGLIST(struct namecache *ncp)
324 {
325
326         return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
327 }
328
329 static inline struct negstate *
330 NCP2NEGSTATE(struct namecache *ncp)
331 {
332
333         MPASS(ncp->nc_flag & NCF_NEGATIVE);
334         return (&ncp->nc_neg);
335 }
336
337 #define numbucketlocks (ncbuckethash + 1)
338 static u_int __read_mostly  ncbuckethash;
339 static struct mtx_padalign __read_mostly  *bucketlocks;
340 #define HASH2BUCKETLOCK(hash) \
341         ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
342
343 #define numvnodelocks (ncvnodehash + 1)
344 static u_int __read_mostly  ncvnodehash;
345 static struct mtx __read_mostly *vnodelocks;
346 static inline struct mtx *
347 VP2VNODELOCK(struct vnode *vp)
348 {
349
350         return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
351 }
352
353 /*
354  * UMA zones for the VFS cache.
355  *
356  * The small cache is used for entries with short names, which are the
357  * most common.  The large cache is used for entries which are too big to
358  * fit in the small cache.
359  */
360 static uma_zone_t __read_mostly cache_zone_small;
361 static uma_zone_t __read_mostly cache_zone_small_ts;
362 static uma_zone_t __read_mostly cache_zone_large;
363 static uma_zone_t __read_mostly cache_zone_large_ts;
364
365 static struct namecache *
366 cache_alloc(int len, int ts)
367 {
368         struct namecache_ts *ncp_ts;
369         struct namecache *ncp;
370
371         if (__predict_false(ts)) {
372                 if (len <= CACHE_PATH_CUTOFF)
373                         ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
374                 else
375                         ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
376                 ncp = &ncp_ts->nc_nc;
377         } else {
378                 if (len <= CACHE_PATH_CUTOFF)
379                         ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
380                 else
381                         ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
382         }
383         return (ncp);
384 }
385
386 static void
387 cache_free(struct namecache *ncp)
388 {
389         struct namecache_ts *ncp_ts;
390
391         MPASS(ncp != NULL);
392         if ((ncp->nc_flag & NCF_DVDROP) != 0)
393                 vdrop(ncp->nc_dvp);
394         if (__predict_false(ncp->nc_flag & NCF_TS)) {
395                 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
396                 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
397                         uma_zfree_smr(cache_zone_small_ts, ncp_ts);
398                 else
399                         uma_zfree_smr(cache_zone_large_ts, ncp_ts);
400         } else {
401                 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
402                         uma_zfree_smr(cache_zone_small, ncp);
403                 else
404                         uma_zfree_smr(cache_zone_large, ncp);
405         }
406 }
407
408 static void
409 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
410 {
411         struct namecache_ts *ncp_ts;
412
413         KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
414             (tsp == NULL && ticksp == NULL),
415             ("No NCF_TS"));
416
417         if (tsp == NULL)
418                 return;
419
420         ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
421         *tsp = ncp_ts->nc_time;
422         *ticksp = ncp_ts->nc_ticks;
423 }
424
425 #ifdef DEBUG_CACHE
426 static int __read_mostly        doingcache = 1; /* 1 => enable the cache */
427 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
428     "VFS namecache enabled");
429 #endif
430
431 /* Export size information to userland */
432 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
433     sizeof(struct namecache), "sizeof(struct namecache)");
434
435 /*
436  * The new name cache statistics
437  */
438 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
439     "Name cache statistics");
440 #define STATNODE_ULONG(name, descr)                                     \
441         SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, descr);
442 #define STATNODE_COUNTER(name, descr)                                   \
443         static COUNTER_U64_DEFINE_EARLY(name);                          \
444         SYSCTL_COUNTER_U64(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, \
445             descr);
446 STATNODE_ULONG(numneg, "Number of negative cache entries");
447 STATNODE_ULONG(numcache, "Number of cache entries");
448 STATNODE_COUNTER(numcachehv, "Number of namecache entries with vnodes held");
449 STATNODE_COUNTER(numdrops, "Number of dropped entries due to reaching the limit");
450 STATNODE_COUNTER(dothits, "Number of '.' hits");
451 STATNODE_COUNTER(dotdothits, "Number of '..' hits");
452 STATNODE_COUNTER(nummiss, "Number of cache misses");
453 STATNODE_COUNTER(nummisszap, "Number of cache misses we do not want to cache");
454 STATNODE_COUNTER(numposzaps,
455     "Number of cache hits (positive) we do not want to cache");
456 STATNODE_COUNTER(numposhits, "Number of cache hits (positive)");
457 STATNODE_COUNTER(numnegzaps,
458     "Number of cache hits (negative) we do not want to cache");
459 STATNODE_COUNTER(numneghits, "Number of cache hits (negative)");
460 /* These count for vn_getcwd(), too. */
461 STATNODE_COUNTER(numfullpathcalls, "Number of fullpath search calls");
462 STATNODE_COUNTER(numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
463 STATNODE_COUNTER(numfullpathfail2,
464     "Number of fullpath search errors (VOP_VPTOCNP failures)");
465 STATNODE_COUNTER(numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
466 STATNODE_COUNTER(numfullpathfound, "Number of successful fullpath calls");
467 STATNODE_COUNTER(zap_and_exit_bucket_relock_success,
468     "Number of successful removals after relocking");
469 static long zap_and_exit_bucket_fail; STATNODE_ULONG(zap_and_exit_bucket_fail,
470     "Number of times zap_and_exit failed to lock");
471 static long zap_and_exit_bucket_fail2; STATNODE_ULONG(zap_and_exit_bucket_fail2,
472     "Number of times zap_and_exit failed to lock");
473 static long cache_lock_vnodes_cel_3_failures;
474 STATNODE_ULONG(cache_lock_vnodes_cel_3_failures,
475     "Number of times 3-way vnode locking failed");
476 STATNODE_ULONG(numhotneg, "Number of hot negative entries");
477 STATNODE_COUNTER(numneg_evicted,
478     "Number of negative entries evicted when adding a new entry");
479 STATNODE_COUNTER(shrinking_skipped,
480     "Number of times shrinking was already in progress");
481
482 static void cache_zap_locked(struct namecache *ncp);
483 static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
484     char **freebuf, size_t *buflen);
485 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
486     char **retbuf, size_t *buflen, bool slash_prefixed, size_t addend);
487 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
488     char **retbuf, size_t *buflen);
489 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
490     char **retbuf, size_t *len, bool slash_prefixed, size_t addend);
491
492 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
493
494 static inline void
495 cache_assert_vlp_locked(struct mtx *vlp)
496 {
497
498         if (vlp != NULL)
499                 mtx_assert(vlp, MA_OWNED);
500 }
501
502 static inline void
503 cache_assert_vnode_locked(struct vnode *vp)
504 {
505         struct mtx *vlp;
506
507         vlp = VP2VNODELOCK(vp);
508         cache_assert_vlp_locked(vlp);
509 }
510
511 /*
512  * TODO: With the value stored we can do better than computing the hash based
513  * on the address. The choice of FNV should also be revisited.
514  */
515 static void
516 cache_prehash(struct vnode *vp)
517 {
518
519         vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
520 }
521
522 static uint32_t
523 cache_get_hash(char *name, u_char len, struct vnode *dvp)
524 {
525
526         return (fnv_32_buf(name, len, dvp->v_nchash));
527 }
528
529 static inline struct nchashhead *
530 NCP2BUCKET(struct namecache *ncp)
531 {
532         uint32_t hash;
533
534         hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
535         return (NCHHASH(hash));
536 }
537
538 static inline struct mtx *
539 NCP2BUCKETLOCK(struct namecache *ncp)
540 {
541         uint32_t hash;
542
543         hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
544         return (HASH2BUCKETLOCK(hash));
545 }
546
547 #ifdef INVARIANTS
548 static void
549 cache_assert_bucket_locked(struct namecache *ncp)
550 {
551         struct mtx *blp;
552
553         blp = NCP2BUCKETLOCK(ncp);
554         mtx_assert(blp, MA_OWNED);
555 }
556
557 static void
558 cache_assert_bucket_unlocked(struct namecache *ncp)
559 {
560         struct mtx *blp;
561
562         blp = NCP2BUCKETLOCK(ncp);
563         mtx_assert(blp, MA_NOTOWNED);
564 }
565 #else
566 #define cache_assert_bucket_locked(x) do { } while (0)
567 #define cache_assert_bucket_unlocked(x) do { } while (0)
568 #endif
569
570 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
571 static void
572 _cache_sort_vnodes(void **p1, void **p2)
573 {
574         void *tmp;
575
576         MPASS(*p1 != NULL || *p2 != NULL);
577
578         if (*p1 > *p2) {
579                 tmp = *p2;
580                 *p2 = *p1;
581                 *p1 = tmp;
582         }
583 }
584
585 static void
586 cache_lock_all_buckets(void)
587 {
588         u_int i;
589
590         for (i = 0; i < numbucketlocks; i++)
591                 mtx_lock(&bucketlocks[i]);
592 }
593
594 static void
595 cache_unlock_all_buckets(void)
596 {
597         u_int i;
598
599         for (i = 0; i < numbucketlocks; i++)
600                 mtx_unlock(&bucketlocks[i]);
601 }
602
603 static void
604 cache_lock_all_vnodes(void)
605 {
606         u_int i;
607
608         for (i = 0; i < numvnodelocks; i++)
609                 mtx_lock(&vnodelocks[i]);
610 }
611
612 static void
613 cache_unlock_all_vnodes(void)
614 {
615         u_int i;
616
617         for (i = 0; i < numvnodelocks; i++)
618                 mtx_unlock(&vnodelocks[i]);
619 }
620
621 static int
622 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
623 {
624
625         cache_sort_vnodes(&vlp1, &vlp2);
626
627         if (vlp1 != NULL) {
628                 if (!mtx_trylock(vlp1))
629                         return (EAGAIN);
630         }
631         if (!mtx_trylock(vlp2)) {
632                 if (vlp1 != NULL)
633                         mtx_unlock(vlp1);
634                 return (EAGAIN);
635         }
636
637         return (0);
638 }
639
640 static void
641 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
642 {
643
644         MPASS(vlp1 != NULL || vlp2 != NULL);
645         MPASS(vlp1 <= vlp2);
646
647         if (vlp1 != NULL)
648                 mtx_lock(vlp1);
649         if (vlp2 != NULL)
650                 mtx_lock(vlp2);
651 }
652
653 static void
654 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
655 {
656
657         MPASS(vlp1 != NULL || vlp2 != NULL);
658
659         if (vlp1 != NULL)
660                 mtx_unlock(vlp1);
661         if (vlp2 != NULL)
662                 mtx_unlock(vlp2);
663 }
664
665 static int
666 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
667 {
668         struct nchstats snap;
669
670         if (req->oldptr == NULL)
671                 return (SYSCTL_OUT(req, 0, sizeof(snap)));
672
673         snap = nchstats;
674         snap.ncs_goodhits = counter_u64_fetch(numposhits);
675         snap.ncs_neghits = counter_u64_fetch(numneghits);
676         snap.ncs_badhits = counter_u64_fetch(numposzaps) +
677             counter_u64_fetch(numnegzaps);
678         snap.ncs_miss = counter_u64_fetch(nummisszap) +
679             counter_u64_fetch(nummiss);
680
681         return (SYSCTL_OUT(req, &snap, sizeof(snap)));
682 }
683 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
684     CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
685     "VFS cache effectiveness statistics");
686
687 #ifdef DIAGNOSTIC
688 /*
689  * Grab an atomic snapshot of the name cache hash chain lengths
690  */
691 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
692     CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
693     "hash table stats");
694
695 static int
696 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
697 {
698         struct nchashhead *ncpp;
699         struct namecache *ncp;
700         int i, error, n_nchash, *cntbuf;
701
702 retry:
703         n_nchash = nchash + 1;  /* nchash is max index, not count */
704         if (req->oldptr == NULL)
705                 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
706         cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
707         cache_lock_all_buckets();
708         if (n_nchash != nchash + 1) {
709                 cache_unlock_all_buckets();
710                 free(cntbuf, M_TEMP);
711                 goto retry;
712         }
713         /* Scan hash tables counting entries */
714         for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
715                 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
716                         cntbuf[i]++;
717         cache_unlock_all_buckets();
718         for (error = 0, i = 0; i < n_nchash; i++)
719                 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
720                         break;
721         free(cntbuf, M_TEMP);
722         return (error);
723 }
724 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
725     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
726     "nchash chain lengths");
727
728 static int
729 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
730 {
731         int error;
732         struct nchashhead *ncpp;
733         struct namecache *ncp;
734         int n_nchash;
735         int count, maxlength, used, pct;
736
737         if (!req->oldptr)
738                 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
739
740         cache_lock_all_buckets();
741         n_nchash = nchash + 1;  /* nchash is max index, not count */
742         used = 0;
743         maxlength = 0;
744
745         /* Scan hash tables for applicable entries */
746         for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
747                 count = 0;
748                 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
749                         count++;
750                 }
751                 if (count)
752                         used++;
753                 if (maxlength < count)
754                         maxlength = count;
755         }
756         n_nchash = nchash + 1;
757         cache_unlock_all_buckets();
758         pct = (used * 100) / (n_nchash / 100);
759         error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
760         if (error)
761                 return (error);
762         error = SYSCTL_OUT(req, &used, sizeof(used));
763         if (error)
764                 return (error);
765         error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
766         if (error)
767                 return (error);
768         error = SYSCTL_OUT(req, &pct, sizeof(pct));
769         if (error)
770                 return (error);
771         return (0);
772 }
773 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
774     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
775     "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
776 #endif
777
778 /*
779  * Negative entries management
780  *
781  * A variation of LRU scheme is used. New entries are hashed into one of
782  * numneglists cold lists. Entries get promoted to the hot list on first hit.
783  *
784  * The shrinker will demote hot list head and evict from the cold list in a
785  * round-robin manner.
786  */
787 static void
788 cache_negative_init(struct namecache *ncp)
789 {
790         struct negstate *negstate;
791
792         ncp->nc_flag |= NCF_NEGATIVE;
793         negstate = NCP2NEGSTATE(ncp);
794         negstate->neg_flag = 0;
795 }
796
797 static void
798 cache_negative_hit(struct namecache *ncp)
799 {
800         struct neglist *neglist;
801         struct negstate *negstate;
802
803         negstate = NCP2NEGSTATE(ncp);
804         if ((negstate->neg_flag & NEG_HOT) != 0)
805                 return;
806         neglist = NCP2NEGLIST(ncp);
807         mtx_lock(&ncneg_hot.nl_lock);
808         mtx_lock(&neglist->nl_lock);
809         if ((negstate->neg_flag & NEG_HOT) == 0) {
810                 numhotneg++;
811                 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
812                 TAILQ_INSERT_TAIL(&ncneg_hot.nl_list, ncp, nc_dst);
813                 negstate->neg_flag |= NEG_HOT;
814         }
815         mtx_unlock(&neglist->nl_lock);
816         mtx_unlock(&ncneg_hot.nl_lock);
817 }
818
819 static void
820 cache_negative_insert(struct namecache *ncp)
821 {
822         struct neglist *neglist;
823
824         MPASS(ncp->nc_flag & NCF_NEGATIVE);
825         cache_assert_bucket_locked(ncp);
826         neglist = NCP2NEGLIST(ncp);
827         mtx_lock(&neglist->nl_lock);
828         TAILQ_INSERT_TAIL(&neglist->nl_list, ncp, nc_dst);
829         mtx_unlock(&neglist->nl_lock);
830         atomic_add_long(&numneg, 1);
831 }
832
833 static void
834 cache_negative_remove(struct namecache *ncp)
835 {
836         struct neglist *neglist;
837         struct negstate *negstate;
838         bool hot_locked = false;
839         bool list_locked = false;
840
841         cache_assert_bucket_locked(ncp);
842         neglist = NCP2NEGLIST(ncp);
843         negstate = NCP2NEGSTATE(ncp);
844         if ((negstate->neg_flag & NEG_HOT) != 0) {
845                 hot_locked = true;
846                 mtx_lock(&ncneg_hot.nl_lock);
847                 if ((negstate->neg_flag & NEG_HOT) == 0) {
848                         list_locked = true;
849                         mtx_lock(&neglist->nl_lock);
850                 }
851         } else {
852                 list_locked = true;
853                 mtx_lock(&neglist->nl_lock);
854                 /*
855                  * We may be racing against promotion in lockless lookup.
856                  */
857                 if ((negstate->neg_flag & NEG_HOT) != 0) {
858                         mtx_unlock(&neglist->nl_lock);
859                         hot_locked = true;
860                         mtx_lock(&ncneg_hot.nl_lock);
861                         mtx_lock(&neglist->nl_lock);
862                 }
863         }
864         if ((negstate->neg_flag & NEG_HOT) != 0) {
865                 mtx_assert(&ncneg_hot.nl_lock, MA_OWNED);
866                 TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
867                 numhotneg--;
868         } else {
869                 mtx_assert(&neglist->nl_lock, MA_OWNED);
870                 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
871         }
872         if (list_locked)
873                 mtx_unlock(&neglist->nl_lock);
874         if (hot_locked)
875                 mtx_unlock(&ncneg_hot.nl_lock);
876         atomic_subtract_long(&numneg, 1);
877 }
878
879 static void
880 cache_negative_shrink_select(struct namecache **ncpp,
881     struct neglist **neglistpp)
882 {
883         struct neglist *neglist;
884         struct namecache *ncp;
885         static u_int cycle;
886         u_int i;
887
888         *ncpp = ncp = NULL;
889
890         for (i = 0; i < numneglists; i++) {
891                 neglist = &neglists[(cycle + i) % numneglists];
892                 if (TAILQ_FIRST(&neglist->nl_list) == NULL)
893                         continue;
894                 mtx_lock(&neglist->nl_lock);
895                 ncp = TAILQ_FIRST(&neglist->nl_list);
896                 if (ncp != NULL)
897                         break;
898                 mtx_unlock(&neglist->nl_lock);
899         }
900
901         *neglistpp = neglist;
902         *ncpp = ncp;
903         cycle++;
904 }
905
906 static void
907 cache_negative_zap_one(void)
908 {
909         struct namecache *ncp, *ncp2;
910         struct neglist *neglist;
911         struct negstate *negstate;
912         struct mtx *dvlp;
913         struct mtx *blp;
914
915         if (mtx_owner(&ncneg_shrink_lock) != NULL ||
916             !mtx_trylock(&ncneg_shrink_lock)) {
917                 counter_u64_add(shrinking_skipped, 1);
918                 return;
919         }
920
921         mtx_lock(&ncneg_hot.nl_lock);
922         ncp = TAILQ_FIRST(&ncneg_hot.nl_list);
923         if (ncp != NULL) {
924                 neglist = NCP2NEGLIST(ncp);
925                 negstate = NCP2NEGSTATE(ncp);
926                 mtx_lock(&neglist->nl_lock);
927                 MPASS((negstate->neg_flag & NEG_HOT) != 0);
928                 TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
929                 TAILQ_INSERT_TAIL(&neglist->nl_list, ncp, nc_dst);
930                 negstate->neg_flag &= ~NEG_HOT;
931                 numhotneg--;
932                 mtx_unlock(&neglist->nl_lock);
933         }
934         mtx_unlock(&ncneg_hot.nl_lock);
935
936         cache_negative_shrink_select(&ncp, &neglist);
937
938         mtx_unlock(&ncneg_shrink_lock);
939         if (ncp == NULL)
940                 return;
941
942         MPASS(ncp->nc_flag & NCF_NEGATIVE);
943         dvlp = VP2VNODELOCK(ncp->nc_dvp);
944         blp = NCP2BUCKETLOCK(ncp);
945         mtx_unlock(&neglist->nl_lock);
946         mtx_lock(dvlp);
947         mtx_lock(blp);
948         /*
949          * Enter SMR to safely check the negative list.
950          * Even if the found pointer matches, the entry may now be reallocated
951          * and used by a different vnode.
952          */
953         vfs_smr_enter();
954         ncp2 = TAILQ_FIRST(&neglist->nl_list);
955         if (ncp != ncp2 || dvlp != VP2VNODELOCK(ncp2->nc_dvp) ||
956             blp != NCP2BUCKETLOCK(ncp2)) {
957                 vfs_smr_exit();
958                 ncp = NULL;
959         } else {
960                 vfs_smr_exit();
961                 SDT_PROBE2(vfs, namecache, shrink_negative, done, ncp->nc_dvp,
962                     ncp->nc_name);
963                 cache_zap_locked(ncp);
964                 counter_u64_add(numneg_evicted, 1);
965         }
966         mtx_unlock(blp);
967         mtx_unlock(dvlp);
968         if (ncp != NULL)
969                 cache_free(ncp);
970 }
971
972 /*
973  * cache_zap_locked():
974  *
975  *   Removes a namecache entry from cache, whether it contains an actual
976  *   pointer to a vnode or if it is just a negative cache entry.
977  */
978 static void
979 cache_zap_locked(struct namecache *ncp)
980 {
981         struct nchashhead *ncpp;
982
983         if (!(ncp->nc_flag & NCF_NEGATIVE))
984                 cache_assert_vnode_locked(ncp->nc_vp);
985         cache_assert_vnode_locked(ncp->nc_dvp);
986         cache_assert_bucket_locked(ncp);
987
988         cache_ncp_invalidate(ncp);
989
990         ncpp = NCP2BUCKET(ncp);
991         CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
992         if (!(ncp->nc_flag & NCF_NEGATIVE)) {
993                 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
994                     ncp->nc_name, ncp->nc_vp);
995                 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
996                 if (ncp == ncp->nc_vp->v_cache_dd) {
997                         vn_seqc_write_begin_unheld(ncp->nc_vp);
998                         ncp->nc_vp->v_cache_dd = NULL;
999                         vn_seqc_write_end(ncp->nc_vp);
1000                 }
1001         } else {
1002                 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
1003                     ncp->nc_name);
1004                 cache_negative_remove(ncp);
1005         }
1006         if (ncp->nc_flag & NCF_ISDOTDOT) {
1007                 if (ncp == ncp->nc_dvp->v_cache_dd) {
1008                         vn_seqc_write_begin_unheld(ncp->nc_dvp);
1009                         ncp->nc_dvp->v_cache_dd = NULL;
1010                         vn_seqc_write_end(ncp->nc_dvp);
1011                 }
1012         } else {
1013                 LIST_REMOVE(ncp, nc_src);
1014                 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
1015                         ncp->nc_flag |= NCF_DVDROP;
1016                         counter_u64_add(numcachehv, -1);
1017                 }
1018         }
1019         atomic_subtract_long(&numcache, 1);
1020 }
1021
1022 static void
1023 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1024 {
1025         struct mtx *blp;
1026
1027         MPASS(ncp->nc_dvp == vp);
1028         MPASS(ncp->nc_flag & NCF_NEGATIVE);
1029         cache_assert_vnode_locked(vp);
1030
1031         blp = NCP2BUCKETLOCK(ncp);
1032         mtx_lock(blp);
1033         cache_zap_locked(ncp);
1034         mtx_unlock(blp);
1035 }
1036
1037 static bool
1038 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1039     struct mtx **vlpp)
1040 {
1041         struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1042         struct mtx *blp;
1043
1044         MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1045         cache_assert_vnode_locked(vp);
1046
1047         if (ncp->nc_flag & NCF_NEGATIVE) {
1048                 if (*vlpp != NULL) {
1049                         mtx_unlock(*vlpp);
1050                         *vlpp = NULL;
1051                 }
1052                 cache_zap_negative_locked_vnode_kl(ncp, vp);
1053                 return (true);
1054         }
1055
1056         pvlp = VP2VNODELOCK(vp);
1057         blp = NCP2BUCKETLOCK(ncp);
1058         vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1059         vlp2 = VP2VNODELOCK(ncp->nc_vp);
1060
1061         if (*vlpp == vlp1 || *vlpp == vlp2) {
1062                 to_unlock = *vlpp;
1063                 *vlpp = NULL;
1064         } else {
1065                 if (*vlpp != NULL) {
1066                         mtx_unlock(*vlpp);
1067                         *vlpp = NULL;
1068                 }
1069                 cache_sort_vnodes(&vlp1, &vlp2);
1070                 if (vlp1 == pvlp) {
1071                         mtx_lock(vlp2);
1072                         to_unlock = vlp2;
1073                 } else {
1074                         if (!mtx_trylock(vlp1))
1075                                 goto out_relock;
1076                         to_unlock = vlp1;
1077                 }
1078         }
1079         mtx_lock(blp);
1080         cache_zap_locked(ncp);
1081         mtx_unlock(blp);
1082         if (to_unlock != NULL)
1083                 mtx_unlock(to_unlock);
1084         return (true);
1085
1086 out_relock:
1087         mtx_unlock(vlp2);
1088         mtx_lock(vlp1);
1089         mtx_lock(vlp2);
1090         MPASS(*vlpp == NULL);
1091         *vlpp = vlp1;
1092         return (false);
1093 }
1094
1095 static int __noinline
1096 cache_zap_locked_vnode(struct namecache *ncp, struct vnode *vp)
1097 {
1098         struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1099         struct mtx *blp;
1100         int error = 0;
1101
1102         MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1103         cache_assert_vnode_locked(vp);
1104
1105         pvlp = VP2VNODELOCK(vp);
1106         if (ncp->nc_flag & NCF_NEGATIVE) {
1107                 cache_zap_negative_locked_vnode_kl(ncp, vp);
1108                 goto out;
1109         }
1110
1111         blp = NCP2BUCKETLOCK(ncp);
1112         vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1113         vlp2 = VP2VNODELOCK(ncp->nc_vp);
1114         cache_sort_vnodes(&vlp1, &vlp2);
1115         if (vlp1 == pvlp) {
1116                 mtx_lock(vlp2);
1117                 to_unlock = vlp2;
1118         } else {
1119                 if (!mtx_trylock(vlp1)) {
1120                         /*
1121                          * TODO: Very wasteful but rare.
1122                          */
1123                         mtx_unlock(pvlp);
1124                         mtx_lock(vlp1);
1125                         mtx_lock(vlp2);
1126                         mtx_unlock(vlp2);
1127                         mtx_unlock(vlp1);
1128                         return (EAGAIN);
1129                 }
1130                 to_unlock = vlp1;
1131         }
1132         mtx_lock(blp);
1133         cache_zap_locked(ncp);
1134         mtx_unlock(blp);
1135         mtx_unlock(to_unlock);
1136 out:
1137         mtx_unlock(pvlp);
1138         return (error);
1139 }
1140
1141 /*
1142  * If trylocking failed we can get here. We know enough to take all needed locks
1143  * in the right order and re-lookup the entry.
1144  */
1145 static int
1146 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1147     struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1148     struct mtx *blp)
1149 {
1150         struct namecache *rncp;
1151
1152         cache_assert_bucket_unlocked(ncp);
1153
1154         cache_sort_vnodes(&dvlp, &vlp);
1155         cache_lock_vnodes(dvlp, vlp);
1156         mtx_lock(blp);
1157         CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1158                 if (rncp == ncp && rncp->nc_dvp == dvp &&
1159                     rncp->nc_nlen == cnp->cn_namelen &&
1160                     !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1161                         break;
1162         }
1163         if (rncp != NULL) {
1164                 cache_zap_locked(rncp);
1165                 mtx_unlock(blp);
1166                 cache_unlock_vnodes(dvlp, vlp);
1167                 counter_u64_add(zap_and_exit_bucket_relock_success, 1);
1168                 return (0);
1169         }
1170
1171         mtx_unlock(blp);
1172         cache_unlock_vnodes(dvlp, vlp);
1173         return (EAGAIN);
1174 }
1175
1176 static int __noinline
1177 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1178     uint32_t hash, struct mtx *blp)
1179 {
1180         struct mtx *dvlp, *vlp;
1181         struct vnode *dvp;
1182
1183         cache_assert_bucket_locked(ncp);
1184
1185         dvlp = VP2VNODELOCK(ncp->nc_dvp);
1186         vlp = NULL;
1187         if (!(ncp->nc_flag & NCF_NEGATIVE))
1188                 vlp = VP2VNODELOCK(ncp->nc_vp);
1189         if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1190                 cache_zap_locked(ncp);
1191                 mtx_unlock(blp);
1192                 cache_unlock_vnodes(dvlp, vlp);
1193                 return (0);
1194         }
1195
1196         dvp = ncp->nc_dvp;
1197         mtx_unlock(blp);
1198         return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1199 }
1200
1201 static __noinline int
1202 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1203 {
1204         struct namecache *ncp;
1205         struct mtx *blp;
1206         struct mtx *dvlp, *dvlp2;
1207         uint32_t hash;
1208         int error;
1209
1210         if (cnp->cn_namelen == 2 &&
1211             cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1212                 dvlp = VP2VNODELOCK(dvp);
1213                 dvlp2 = NULL;
1214                 mtx_lock(dvlp);
1215 retry_dotdot:
1216                 ncp = dvp->v_cache_dd;
1217                 if (ncp == NULL) {
1218                         mtx_unlock(dvlp);
1219                         if (dvlp2 != NULL)
1220                                 mtx_unlock(dvlp2);
1221                         SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1222                         return (0);
1223                 }
1224                 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1225                         if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1226                                 goto retry_dotdot;
1227                         MPASS(dvp->v_cache_dd == NULL);
1228                         mtx_unlock(dvlp);
1229                         if (dvlp2 != NULL)
1230                                 mtx_unlock(dvlp2);
1231                         cache_free(ncp);
1232                 } else {
1233                         vn_seqc_write_begin(dvp);
1234                         dvp->v_cache_dd = NULL;
1235                         vn_seqc_write_end(dvp);
1236                         mtx_unlock(dvlp);
1237                         if (dvlp2 != NULL)
1238                                 mtx_unlock(dvlp2);
1239                 }
1240                 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1241                 return (1);
1242         }
1243
1244         hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1245         blp = HASH2BUCKETLOCK(hash);
1246 retry:
1247         if (CK_SLIST_EMPTY(NCHHASH(hash)))
1248                 goto out_no_entry;
1249
1250         mtx_lock(blp);
1251
1252         CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1253                 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1254                     !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1255                         break;
1256         }
1257
1258         if (ncp == NULL) {
1259                 mtx_unlock(blp);
1260                 goto out_no_entry;
1261         }
1262
1263         error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1264         if (__predict_false(error != 0)) {
1265                 zap_and_exit_bucket_fail++;
1266                 goto retry;
1267         }
1268         counter_u64_add(numposzaps, 1);
1269         SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1270         cache_free(ncp);
1271         return (1);
1272 out_no_entry:
1273         counter_u64_add(nummisszap, 1);
1274         SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1275         return (0);
1276 }
1277
1278 static int __noinline
1279 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1280     struct timespec *tsp, int *ticksp)
1281 {
1282         int ltype;
1283
1284         *vpp = dvp;
1285         counter_u64_add(dothits, 1);
1286         SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1287         if (tsp != NULL)
1288                 timespecclear(tsp);
1289         if (ticksp != NULL)
1290                 *ticksp = ticks;
1291         vrefact(*vpp);
1292         /*
1293          * When we lookup "." we still can be asked to lock it
1294          * differently...
1295          */
1296         ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1297         if (ltype != VOP_ISLOCKED(*vpp)) {
1298                 if (ltype == LK_EXCLUSIVE) {
1299                         vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1300                         if (VN_IS_DOOMED((*vpp))) {
1301                                 /* forced unmount */
1302                                 vrele(*vpp);
1303                                 *vpp = NULL;
1304                                 return (ENOENT);
1305                         }
1306                 } else
1307                         vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1308         }
1309         return (-1);
1310 }
1311
1312 static int __noinline
1313 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1314     struct timespec *tsp, int *ticksp)
1315 {
1316         struct namecache_ts *ncp_ts;
1317         struct namecache *ncp;
1318         struct mtx *dvlp;
1319         enum vgetstate vs;
1320         int error, ltype;
1321         bool whiteout;
1322
1323         MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1324
1325         if ((cnp->cn_flags & MAKEENTRY) == 0) {
1326                 cache_remove_cnp(dvp, cnp);
1327                 return (0);
1328         }
1329
1330         counter_u64_add(dotdothits, 1);
1331 retry:
1332         dvlp = VP2VNODELOCK(dvp);
1333         mtx_lock(dvlp);
1334         ncp = dvp->v_cache_dd;
1335         if (ncp == NULL) {
1336                 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, "..", NULL);
1337                 mtx_unlock(dvlp);
1338                 return (0);
1339         }
1340         if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1341                 if (ncp->nc_flag & NCF_NEGATIVE)
1342                         *vpp = NULL;
1343                 else
1344                         *vpp = ncp->nc_vp;
1345         } else
1346                 *vpp = ncp->nc_dvp;
1347         if (*vpp == NULL)
1348                 goto negative_success;
1349         SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1350         cache_out_ts(ncp, tsp, ticksp);
1351         if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1352             NCF_DTS && tsp != NULL) {
1353                 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1354                 *tsp = ncp_ts->nc_dotdottime;
1355         }
1356
1357         MPASS(dvp != *vpp);
1358         ltype = VOP_ISLOCKED(dvp);
1359         VOP_UNLOCK(dvp);
1360         vs = vget_prep(*vpp);
1361         mtx_unlock(dvlp);
1362         error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1363         vn_lock(dvp, ltype | LK_RETRY);
1364         if (VN_IS_DOOMED(dvp)) {
1365                 if (error == 0)
1366                         vput(*vpp);
1367                 *vpp = NULL;
1368                 return (ENOENT);
1369         }
1370         if (error) {
1371                 *vpp = NULL;
1372                 goto retry;
1373         }
1374         return (-1);
1375 negative_success:
1376         if (__predict_false(cnp->cn_nameiop == CREATE)) {
1377                 if (cnp->cn_flags & ISLASTCN) {
1378                         counter_u64_add(numnegzaps, 1);
1379                         error = cache_zap_locked_vnode(ncp, dvp);
1380                         if (__predict_false(error != 0)) {
1381                                 zap_and_exit_bucket_fail2++;
1382                                 goto retry;
1383                         }
1384                         cache_free(ncp);
1385                         return (0);
1386                 }
1387         }
1388
1389         SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1390         cache_out_ts(ncp, tsp, ticksp);
1391         counter_u64_add(numneghits, 1);
1392         whiteout = (ncp->nc_flag & NCF_WHITE);
1393         cache_negative_hit(ncp);
1394         mtx_unlock(dvlp);
1395         if (whiteout)
1396                 cnp->cn_flags |= ISWHITEOUT;
1397         return (ENOENT);
1398 }
1399
1400 /**
1401  * Lookup a name in the name cache
1402  *
1403  * # Arguments
1404  *
1405  * - dvp:       Parent directory in which to search.
1406  * - vpp:       Return argument.  Will contain desired vnode on cache hit.
1407  * - cnp:       Parameters of the name search.  The most interesting bits of
1408  *              the cn_flags field have the following meanings:
1409  *      - MAKEENTRY:    If clear, free an entry from the cache rather than look
1410  *                      it up.
1411  *      - ISDOTDOT:     Must be set if and only if cn_nameptr == ".."
1412  * - tsp:       Return storage for cache timestamp.  On a successful (positive
1413  *              or negative) lookup, tsp will be filled with any timespec that
1414  *              was stored when this cache entry was created.  However, it will
1415  *              be clear for "." entries.
1416  * - ticks:     Return storage for alternate cache timestamp.  On a successful
1417  *              (positive or negative) lookup, it will contain the ticks value
1418  *              that was current when the cache entry was created, unless cnp
1419  *              was ".".
1420  *
1421  * Either both tsp and ticks have to be provided or neither of them.
1422  *
1423  * # Returns
1424  *
1425  * - -1:        A positive cache hit.  vpp will contain the desired vnode.
1426  * - ENOENT:    A negative cache hit, or dvp was recycled out from under us due
1427  *              to a forced unmount.  vpp will not be modified.  If the entry
1428  *              is a whiteout, then the ISWHITEOUT flag will be set in
1429  *              cnp->cn_flags.
1430  * - 0:         A cache miss.  vpp will not be modified.
1431  *
1432  * # Locking
1433  *
1434  * On a cache hit, vpp will be returned locked and ref'd.  If we're looking up
1435  * .., dvp is unlocked.  If we're looking up . an extra ref is taken, but the
1436  * lock is not recursively acquired.
1437  */
1438 static int __noinline
1439 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1440     struct timespec *tsp, int *ticksp)
1441 {
1442         struct namecache *ncp;
1443         struct mtx *blp;
1444         uint32_t hash;
1445         enum vgetstate vs;
1446         int error;
1447         bool whiteout;
1448
1449         MPASS((cnp->cn_flags & (MAKEENTRY | ISDOTDOT)) == MAKEENTRY);
1450
1451 retry:
1452         hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1453         blp = HASH2BUCKETLOCK(hash);
1454         mtx_lock(blp);
1455
1456         CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1457                 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1458                     !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1459                         break;
1460         }
1461
1462         if (__predict_false(ncp == NULL)) {
1463                 mtx_unlock(blp);
1464                 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1465                     NULL);
1466                 counter_u64_add(nummiss, 1);
1467                 return (0);
1468         }
1469
1470         if (ncp->nc_flag & NCF_NEGATIVE)
1471                 goto negative_success;
1472
1473         counter_u64_add(numposhits, 1);
1474         *vpp = ncp->nc_vp;
1475         SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1476         cache_out_ts(ncp, tsp, ticksp);
1477         MPASS(dvp != *vpp);
1478         vs = vget_prep(*vpp);
1479         mtx_unlock(blp);
1480         error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1481         if (error) {
1482                 *vpp = NULL;
1483                 goto retry;
1484         }
1485         return (-1);
1486 negative_success:
1487         if (__predict_false(cnp->cn_nameiop == CREATE)) {
1488                 if (cnp->cn_flags & ISLASTCN) {
1489                         counter_u64_add(numnegzaps, 1);
1490                         error = cache_zap_locked_vnode(ncp, dvp);
1491                         if (__predict_false(error != 0)) {
1492                                 zap_and_exit_bucket_fail2++;
1493                                 goto retry;
1494                         }
1495                         cache_free(ncp);
1496                         return (0);
1497                 }
1498         }
1499
1500         SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1501         cache_out_ts(ncp, tsp, ticksp);
1502         counter_u64_add(numneghits, 1);
1503         whiteout = (ncp->nc_flag & NCF_WHITE);
1504         cache_negative_hit(ncp);
1505         mtx_unlock(blp);
1506         if (whiteout)
1507                 cnp->cn_flags |= ISWHITEOUT;
1508         return (ENOENT);
1509 }
1510
1511 int
1512 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1513     struct timespec *tsp, int *ticksp)
1514 {
1515         struct namecache *ncp;
1516         struct negstate *negstate;
1517         uint32_t hash;
1518         enum vgetstate vs;
1519         int error;
1520         bool whiteout;
1521         u_short nc_flag;
1522
1523         MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
1524
1525 #ifdef DEBUG_CACHE
1526         if (__predict_false(!doingcache)) {
1527                 cnp->cn_flags &= ~MAKEENTRY;
1528                 return (0);
1529         }
1530 #endif
1531
1532         if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1533                 if (cnp->cn_namelen == 1)
1534                         return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
1535                 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
1536                         return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
1537         }
1538
1539         MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1540
1541         if ((cnp->cn_flags & MAKEENTRY) == 0) {
1542                 cache_remove_cnp(dvp, cnp);
1543                 return (0);
1544         }
1545
1546         hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1547         vfs_smr_enter();
1548
1549         CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1550                 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1551                     !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1552                         break;
1553         }
1554
1555         if (__predict_false(ncp == NULL)) {
1556                 vfs_smr_exit();
1557                 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1558                     NULL);
1559                 counter_u64_add(nummiss, 1);
1560                 return (0);
1561         }
1562
1563         nc_flag = atomic_load_char(&ncp->nc_flag);
1564         if (nc_flag & NCF_NEGATIVE)
1565                 goto negative_success;
1566
1567         counter_u64_add(numposhits, 1);
1568         *vpp = ncp->nc_vp;
1569         SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
1570         cache_out_ts(ncp, tsp, ticksp);
1571         MPASS(dvp != *vpp);
1572         if (!cache_ncp_canuse(ncp)) {
1573                 vfs_smr_exit();
1574                 *vpp = NULL;
1575                 goto out_fallback;
1576         }
1577         vs = vget_prep_smr(*vpp);
1578         vfs_smr_exit();
1579         if (__predict_false(vs == VGET_NONE)) {
1580                 *vpp = NULL;
1581                 goto out_fallback;
1582         }
1583         error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1584         if (error) {
1585                 *vpp = NULL;
1586                 goto out_fallback;
1587         }
1588         return (-1);
1589 negative_success:
1590         if (__predict_false(cnp->cn_nameiop == CREATE)) {
1591                 if (cnp->cn_flags & ISLASTCN) {
1592                         vfs_smr_exit();
1593                         goto out_fallback;
1594                 }
1595         }
1596
1597         SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
1598         cache_out_ts(ncp, tsp, ticksp);
1599         counter_u64_add(numneghits, 1);
1600         whiteout = (ncp->nc_flag & NCF_WHITE);
1601         /*
1602          * TODO: We need to take locks to promote an entry. Code doing it
1603          * in SMR lookup can be modified to be shared.
1604          */
1605         negstate = NCP2NEGSTATE(ncp);
1606         if ((negstate->neg_flag & NEG_HOT) == 0 ||
1607             !cache_ncp_canuse(ncp)) {
1608                 vfs_smr_exit();
1609                 goto out_fallback;
1610         }
1611         vfs_smr_exit();
1612         if (whiteout)
1613                 cnp->cn_flags |= ISWHITEOUT;
1614         return (ENOENT);
1615 out_fallback:
1616         return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
1617 }
1618
1619 struct celockstate {
1620         struct mtx *vlp[3];
1621         struct mtx *blp[2];
1622 };
1623 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1624 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1625
1626 static inline void
1627 cache_celockstate_init(struct celockstate *cel)
1628 {
1629
1630         bzero(cel, sizeof(*cel));
1631 }
1632
1633 static void
1634 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1635     struct vnode *dvp)
1636 {
1637         struct mtx *vlp1, *vlp2;
1638
1639         MPASS(cel->vlp[0] == NULL);
1640         MPASS(cel->vlp[1] == NULL);
1641         MPASS(cel->vlp[2] == NULL);
1642
1643         MPASS(vp != NULL || dvp != NULL);
1644
1645         vlp1 = VP2VNODELOCK(vp);
1646         vlp2 = VP2VNODELOCK(dvp);
1647         cache_sort_vnodes(&vlp1, &vlp2);
1648
1649         if (vlp1 != NULL) {
1650                 mtx_lock(vlp1);
1651                 cel->vlp[0] = vlp1;
1652         }
1653         mtx_lock(vlp2);
1654         cel->vlp[1] = vlp2;
1655 }
1656
1657 static void
1658 cache_unlock_vnodes_cel(struct celockstate *cel)
1659 {
1660
1661         MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
1662
1663         if (cel->vlp[0] != NULL)
1664                 mtx_unlock(cel->vlp[0]);
1665         if (cel->vlp[1] != NULL)
1666                 mtx_unlock(cel->vlp[1]);
1667         if (cel->vlp[2] != NULL)
1668                 mtx_unlock(cel->vlp[2]);
1669 }
1670
1671 static bool
1672 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
1673 {
1674         struct mtx *vlp;
1675         bool ret;
1676
1677         cache_assert_vlp_locked(cel->vlp[0]);
1678         cache_assert_vlp_locked(cel->vlp[1]);
1679         MPASS(cel->vlp[2] == NULL);
1680
1681         MPASS(vp != NULL);
1682         vlp = VP2VNODELOCK(vp);
1683
1684         ret = true;
1685         if (vlp >= cel->vlp[1]) {
1686                 mtx_lock(vlp);
1687         } else {
1688                 if (mtx_trylock(vlp))
1689                         goto out;
1690                 cache_lock_vnodes_cel_3_failures++;
1691                 cache_unlock_vnodes_cel(cel);
1692                 if (vlp < cel->vlp[0]) {
1693                         mtx_lock(vlp);
1694                         mtx_lock(cel->vlp[0]);
1695                         mtx_lock(cel->vlp[1]);
1696                 } else {
1697                         if (cel->vlp[0] != NULL)
1698                                 mtx_lock(cel->vlp[0]);
1699                         mtx_lock(vlp);
1700                         mtx_lock(cel->vlp[1]);
1701                 }
1702                 ret = false;
1703         }
1704 out:
1705         cel->vlp[2] = vlp;
1706         return (ret);
1707 }
1708
1709 static void
1710 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
1711     struct mtx *blp2)
1712 {
1713
1714         MPASS(cel->blp[0] == NULL);
1715         MPASS(cel->blp[1] == NULL);
1716
1717         cache_sort_vnodes(&blp1, &blp2);
1718
1719         if (blp1 != NULL) {
1720                 mtx_lock(blp1);
1721                 cel->blp[0] = blp1;
1722         }
1723         mtx_lock(blp2);
1724         cel->blp[1] = blp2;
1725 }
1726
1727 static void
1728 cache_unlock_buckets_cel(struct celockstate *cel)
1729 {
1730
1731         if (cel->blp[0] != NULL)
1732                 mtx_unlock(cel->blp[0]);
1733         mtx_unlock(cel->blp[1]);
1734 }
1735
1736 /*
1737  * Lock part of the cache affected by the insertion.
1738  *
1739  * This means vnodelocks for dvp, vp and the relevant bucketlock.
1740  * However, insertion can result in removal of an old entry. In this
1741  * case we have an additional vnode and bucketlock pair to lock.
1742  *
1743  * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
1744  * preserving the locking order (smaller address first).
1745  */
1746 static void
1747 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1748     uint32_t hash)
1749 {
1750         struct namecache *ncp;
1751         struct mtx *blps[2];
1752
1753         blps[0] = HASH2BUCKETLOCK(hash);
1754         for (;;) {
1755                 blps[1] = NULL;
1756                 cache_lock_vnodes_cel(cel, dvp, vp);
1757                 if (vp == NULL || vp->v_type != VDIR)
1758                         break;
1759                 ncp = vp->v_cache_dd;
1760                 if (ncp == NULL)
1761                         break;
1762                 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1763                         break;
1764                 MPASS(ncp->nc_dvp == vp);
1765                 blps[1] = NCP2BUCKETLOCK(ncp);
1766                 if (ncp->nc_flag & NCF_NEGATIVE)
1767                         break;
1768                 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1769                         break;
1770                 /*
1771                  * All vnodes got re-locked. Re-validate the state and if
1772                  * nothing changed we are done. Otherwise restart.
1773                  */
1774                 if (ncp == vp->v_cache_dd &&
1775                     (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1776                     blps[1] == NCP2BUCKETLOCK(ncp) &&
1777                     VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1778                         break;
1779                 cache_unlock_vnodes_cel(cel);
1780                 cel->vlp[0] = NULL;
1781                 cel->vlp[1] = NULL;
1782                 cel->vlp[2] = NULL;
1783         }
1784         cache_lock_buckets_cel(cel, blps[0], blps[1]);
1785 }
1786
1787 static void
1788 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1789     uint32_t hash)
1790 {
1791         struct namecache *ncp;
1792         struct mtx *blps[2];
1793
1794         blps[0] = HASH2BUCKETLOCK(hash);
1795         for (;;) {
1796                 blps[1] = NULL;
1797                 cache_lock_vnodes_cel(cel, dvp, vp);
1798                 ncp = dvp->v_cache_dd;
1799                 if (ncp == NULL)
1800                         break;
1801                 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1802                         break;
1803                 MPASS(ncp->nc_dvp == dvp);
1804                 blps[1] = NCP2BUCKETLOCK(ncp);
1805                 if (ncp->nc_flag & NCF_NEGATIVE)
1806                         break;
1807                 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1808                         break;
1809                 if (ncp == dvp->v_cache_dd &&
1810                     (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1811                     blps[1] == NCP2BUCKETLOCK(ncp) &&
1812                     VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1813                         break;
1814                 cache_unlock_vnodes_cel(cel);
1815                 cel->vlp[0] = NULL;
1816                 cel->vlp[1] = NULL;
1817                 cel->vlp[2] = NULL;
1818         }
1819         cache_lock_buckets_cel(cel, blps[0], blps[1]);
1820 }
1821
1822 static void
1823 cache_enter_unlock(struct celockstate *cel)
1824 {
1825
1826         cache_unlock_buckets_cel(cel);
1827         cache_unlock_vnodes_cel(cel);
1828 }
1829
1830 static void __noinline
1831 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
1832     struct componentname *cnp)
1833 {
1834         struct celockstate cel;
1835         struct namecache *ncp;
1836         uint32_t hash;
1837         int len;
1838
1839         if (dvp->v_cache_dd == NULL)
1840                 return;
1841         len = cnp->cn_namelen;
1842         cache_celockstate_init(&cel);
1843         hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
1844         cache_enter_lock_dd(&cel, dvp, vp, hash);
1845         vn_seqc_write_begin(dvp);
1846         ncp = dvp->v_cache_dd;
1847         if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
1848                 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
1849                 cache_zap_locked(ncp);
1850         } else {
1851                 ncp = NULL;
1852         }
1853         dvp->v_cache_dd = NULL;
1854         vn_seqc_write_end(dvp);
1855         cache_enter_unlock(&cel);
1856         if (ncp != NULL)
1857                 cache_free(ncp);
1858 }
1859
1860 /*
1861  * Add an entry to the cache.
1862  */
1863 void
1864 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
1865     struct timespec *tsp, struct timespec *dtsp)
1866 {
1867         struct celockstate cel;
1868         struct namecache *ncp, *n2, *ndd;
1869         struct namecache_ts *ncp_ts;
1870         struct nchashhead *ncpp;
1871         uint32_t hash;
1872         int flag;
1873         int len;
1874         u_long lnumcache;
1875
1876         VNPASS(!VN_IS_DOOMED(dvp), dvp);
1877         VNPASS(dvp->v_type != VNON, dvp);
1878         if (vp != NULL) {
1879                 VNPASS(!VN_IS_DOOMED(vp), vp);
1880                 VNPASS(vp->v_type != VNON, vp);
1881         }
1882
1883 #ifdef DEBUG_CACHE
1884         if (__predict_false(!doingcache))
1885                 return;
1886 #endif
1887
1888         flag = 0;
1889         if (__predict_false(cnp->cn_nameptr[0] == '.')) {
1890                 if (cnp->cn_namelen == 1)
1891                         return;
1892                 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
1893                         cache_enter_dotdot_prep(dvp, vp, cnp);
1894                         flag = NCF_ISDOTDOT;
1895                 }
1896         }
1897
1898         /*
1899          * Avoid blowout in namecache entries.
1900          */
1901         lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
1902         if (__predict_false(lnumcache >= ncsize)) {
1903                 atomic_subtract_long(&numcache, 1);
1904                 counter_u64_add(numdrops, 1);
1905                 return;
1906         }
1907
1908         cache_celockstate_init(&cel);
1909         ndd = NULL;
1910         ncp_ts = NULL;
1911
1912         /*
1913          * Calculate the hash key and setup as much of the new
1914          * namecache entry as possible before acquiring the lock.
1915          */
1916         ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
1917         ncp->nc_flag = flag | NCF_WIP;
1918         ncp->nc_vp = vp;
1919         if (vp == NULL)
1920                 cache_negative_init(ncp);
1921         ncp->nc_dvp = dvp;
1922         if (tsp != NULL) {
1923                 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1924                 ncp_ts->nc_time = *tsp;
1925                 ncp_ts->nc_ticks = ticks;
1926                 ncp_ts->nc_nc.nc_flag |= NCF_TS;
1927                 if (dtsp != NULL) {
1928                         ncp_ts->nc_dotdottime = *dtsp;
1929                         ncp_ts->nc_nc.nc_flag |= NCF_DTS;
1930                 }
1931         }
1932         len = ncp->nc_nlen = cnp->cn_namelen;
1933         hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
1934         memcpy(ncp->nc_name, cnp->cn_nameptr, len);
1935         ncp->nc_name[len] = '\0';
1936         cache_enter_lock(&cel, dvp, vp, hash);
1937
1938         /*
1939          * See if this vnode or negative entry is already in the cache
1940          * with this name.  This can happen with concurrent lookups of
1941          * the same path name.
1942          */
1943         ncpp = NCHHASH(hash);
1944         CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
1945                 if (n2->nc_dvp == dvp &&
1946                     n2->nc_nlen == cnp->cn_namelen &&
1947                     !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
1948                         MPASS(cache_ncp_canuse(n2));
1949                         if ((n2->nc_flag & NCF_NEGATIVE) != 0)
1950                                 KASSERT(vp == NULL,
1951                                     ("%s: found entry pointing to a different vnode (%p != %p)",
1952                                     __func__, NULL, vp));
1953                         else
1954                                 KASSERT(n2->nc_vp == vp,
1955                                     ("%s: found entry pointing to a different vnode (%p != %p)",
1956                                     __func__, n2->nc_vp, vp));
1957                         /*
1958                          * Entries are supposed to be immutable unless in the
1959                          * process of getting destroyed. Accommodating for
1960                          * changing timestamps is possible but not worth it.
1961                          * This should be harmless in terms of correctness, in
1962                          * the worst case resulting in an earlier expiration.
1963                          * Alternatively, the found entry can be replaced
1964                          * altogether.
1965                          */
1966                         MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
1967 #if 0
1968                         if (tsp != NULL) {
1969                                 KASSERT((n2->nc_flag & NCF_TS) != 0,
1970                                     ("no NCF_TS"));
1971                                 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
1972                                 n2_ts->nc_time = ncp_ts->nc_time;
1973                                 n2_ts->nc_ticks = ncp_ts->nc_ticks;
1974                                 if (dtsp != NULL) {
1975                                         n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
1976                                         n2_ts->nc_nc.nc_flag |= NCF_DTS;
1977                                 }
1978                         }
1979 #endif
1980                         goto out_unlock_free;
1981                 }
1982         }
1983
1984         if (flag == NCF_ISDOTDOT) {
1985                 /*
1986                  * See if we are trying to add .. entry, but some other lookup
1987                  * has populated v_cache_dd pointer already.
1988                  */
1989                 if (dvp->v_cache_dd != NULL)
1990                         goto out_unlock_free;
1991                 KASSERT(vp == NULL || vp->v_type == VDIR,
1992                     ("wrong vnode type %p", vp));
1993                 vn_seqc_write_begin(dvp);
1994                 dvp->v_cache_dd = ncp;
1995                 vn_seqc_write_end(dvp);
1996         }
1997
1998         if (vp != NULL) {
1999                 if (flag != NCF_ISDOTDOT) {
2000                         /*
2001                          * For this case, the cache entry maps both the
2002                          * directory name in it and the name ".." for the
2003                          * directory's parent.
2004                          */
2005                         vn_seqc_write_begin(vp);
2006                         if ((ndd = vp->v_cache_dd) != NULL) {
2007                                 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2008                                         cache_zap_locked(ndd);
2009                                 else
2010                                         ndd = NULL;
2011                         }
2012                         vp->v_cache_dd = ncp;
2013                         vn_seqc_write_end(vp);
2014                 } else if (vp->v_type != VDIR) {
2015                         if (vp->v_cache_dd != NULL) {
2016                                 vn_seqc_write_begin(vp);
2017                                 vp->v_cache_dd = NULL;
2018                                 vn_seqc_write_end(vp);
2019                         }
2020                 }
2021         }
2022
2023         if (flag != NCF_ISDOTDOT) {
2024                 if (LIST_EMPTY(&dvp->v_cache_src)) {
2025                         vhold(dvp);
2026                         counter_u64_add(numcachehv, 1);
2027                 }
2028                 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2029         }
2030
2031         /*
2032          * If the entry is "negative", we place it into the
2033          * "negative" cache queue, otherwise, we place it into the
2034          * destination vnode's cache entries queue.
2035          */
2036         if (vp != NULL) {
2037                 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2038                 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2039                     vp);
2040         } else {
2041                 if (cnp->cn_flags & ISWHITEOUT)
2042                         ncp->nc_flag |= NCF_WHITE;
2043                 cache_negative_insert(ncp);
2044                 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2045                     ncp->nc_name);
2046         }
2047
2048         /*
2049          * Insert the new namecache entry into the appropriate chain
2050          * within the cache entries table.
2051          */
2052         CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2053
2054         atomic_thread_fence_rel();
2055         /*
2056          * Mark the entry as fully constructed.
2057          * It is immutable past this point until its removal.
2058          */
2059         atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2060
2061         cache_enter_unlock(&cel);
2062         if (numneg * ncnegfactor > lnumcache)
2063                 cache_negative_zap_one();
2064         if (ndd != NULL)
2065                 cache_free(ndd);
2066         return;
2067 out_unlock_free:
2068         cache_enter_unlock(&cel);
2069         atomic_subtract_long(&numcache, 1);
2070         cache_free(ncp);
2071         return;
2072 }
2073
2074 static u_int
2075 cache_roundup_2(u_int val)
2076 {
2077         u_int res;
2078
2079         for (res = 1; res <= val; res <<= 1)
2080                 continue;
2081
2082         return (res);
2083 }
2084
2085 static struct nchashhead *
2086 nchinittbl(u_long elements, u_long *hashmask)
2087 {
2088         struct nchashhead *hashtbl;
2089         u_long hashsize, i;
2090
2091         hashsize = cache_roundup_2(elements) / 2;
2092
2093         hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2094         for (i = 0; i < hashsize; i++)
2095                 CK_SLIST_INIT(&hashtbl[i]);
2096         *hashmask = hashsize - 1;
2097         return (hashtbl);
2098 }
2099
2100 static void
2101 ncfreetbl(struct nchashhead *hashtbl)
2102 {
2103
2104         free(hashtbl, M_VFSCACHE);
2105 }
2106
2107 /*
2108  * Name cache initialization, from vfs_init() when we are booting
2109  */
2110 static void
2111 nchinit(void *dummy __unused)
2112 {
2113         u_int i;
2114
2115         cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2116             NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2117         cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2118             NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2119         cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2120             NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2121         cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2122             NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2123
2124         VFS_SMR_ZONE_SET(cache_zone_small);
2125         VFS_SMR_ZONE_SET(cache_zone_small_ts);
2126         VFS_SMR_ZONE_SET(cache_zone_large);
2127         VFS_SMR_ZONE_SET(cache_zone_large_ts);
2128
2129         ncsize = desiredvnodes * ncsizefactor;
2130         nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2131         ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2132         if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2133                 ncbuckethash = 7;
2134         if (ncbuckethash > nchash)
2135                 ncbuckethash = nchash;
2136         bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2137             M_WAITOK | M_ZERO);
2138         for (i = 0; i < numbucketlocks; i++)
2139                 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2140         ncvnodehash = ncbuckethash;
2141         vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2142             M_WAITOK | M_ZERO);
2143         for (i = 0; i < numvnodelocks; i++)
2144                 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2145         ncpurgeminvnodes = numbucketlocks * 2;
2146
2147         neglists = malloc(sizeof(*neglists) * numneglists, M_VFSCACHE,
2148             M_WAITOK | M_ZERO);
2149         for (i = 0; i < numneglists; i++) {
2150                 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2151                 TAILQ_INIT(&neglists[i].nl_list);
2152         }
2153         mtx_init(&ncneg_hot.nl_lock, "ncneglh", NULL, MTX_DEF);
2154         TAILQ_INIT(&ncneg_hot.nl_list);
2155
2156         mtx_init(&ncneg_shrink_lock, "ncnegs", NULL, MTX_DEF);
2157 }
2158 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2159
2160 void
2161 cache_vnode_init(struct vnode *vp)
2162 {
2163
2164         LIST_INIT(&vp->v_cache_src);
2165         TAILQ_INIT(&vp->v_cache_dst);
2166         vp->v_cache_dd = NULL;
2167         cache_prehash(vp);
2168 }
2169
2170 void
2171 cache_changesize(u_long newmaxvnodes)
2172 {
2173         struct nchashhead *new_nchashtbl, *old_nchashtbl;
2174         u_long new_nchash, old_nchash;
2175         struct namecache *ncp;
2176         uint32_t hash;
2177         u_long newncsize;
2178         int i;
2179
2180         newncsize = newmaxvnodes * ncsizefactor;
2181         newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2182         if (newmaxvnodes < numbucketlocks)
2183                 newmaxvnodes = numbucketlocks;
2184
2185         new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2186         /* If same hash table size, nothing to do */
2187         if (nchash == new_nchash) {
2188                 ncfreetbl(new_nchashtbl);
2189                 return;
2190         }
2191         /*
2192          * Move everything from the old hash table to the new table.
2193          * None of the namecache entries in the table can be removed
2194          * because to do so, they have to be removed from the hash table.
2195          */
2196         cache_lock_all_vnodes();
2197         cache_lock_all_buckets();
2198         old_nchashtbl = nchashtbl;
2199         old_nchash = nchash;
2200         nchashtbl = new_nchashtbl;
2201         nchash = new_nchash;
2202         for (i = 0; i <= old_nchash; i++) {
2203                 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2204                         hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2205                             ncp->nc_dvp);
2206                         CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2207                         CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
2208                 }
2209         }
2210         ncsize = newncsize;
2211         cache_unlock_all_buckets();
2212         cache_unlock_all_vnodes();
2213         ncfreetbl(old_nchashtbl);
2214 }
2215
2216 /*
2217  * Invalidate all entries from and to a particular vnode.
2218  */
2219 static void
2220 cache_purge_impl(struct vnode *vp)
2221 {
2222         TAILQ_HEAD(, namecache) ncps;
2223         struct namecache *ncp, *nnp;
2224         struct mtx *vlp, *vlp2;
2225
2226         TAILQ_INIT(&ncps);
2227         vlp = VP2VNODELOCK(vp);
2228         vlp2 = NULL;
2229         mtx_assert(vlp, MA_OWNED);
2230 retry:
2231         while (!LIST_EMPTY(&vp->v_cache_src)) {
2232                 ncp = LIST_FIRST(&vp->v_cache_src);
2233                 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2234                         goto retry;
2235                 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2236         }
2237         while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2238                 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2239                 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2240                         goto retry;
2241                 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2242         }
2243         ncp = vp->v_cache_dd;
2244         if (ncp != NULL) {
2245                 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2246                    ("lost dotdot link"));
2247                 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2248                         goto retry;
2249                 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2250         }
2251         KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2252         mtx_unlock(vlp);
2253         if (vlp2 != NULL)
2254                 mtx_unlock(vlp2);
2255         TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2256                 cache_free(ncp);
2257         }
2258 }
2259
2260 /*
2261  * Opportunistic check to see if there is anything to do.
2262  */
2263 static bool
2264 cache_has_entries(struct vnode *vp)
2265 {
2266
2267         if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2268             vp->v_cache_dd == NULL)
2269                 return (false);
2270         return (true);
2271 }
2272
2273 void
2274 cache_purge(struct vnode *vp)
2275 {
2276         struct mtx *vlp;
2277
2278         SDT_PROBE1(vfs, namecache, purge, done, vp);
2279         if (!cache_has_entries(vp))
2280                 return;
2281         vlp = VP2VNODELOCK(vp);
2282         mtx_lock(vlp);
2283         cache_purge_impl(vp);
2284 }
2285
2286 /*
2287  * Only to be used by vgone.
2288  */
2289 void
2290 cache_purge_vgone(struct vnode *vp)
2291 {
2292         struct mtx *vlp;
2293
2294         VNPASS(VN_IS_DOOMED(vp), vp);
2295         vlp = VP2VNODELOCK(vp);
2296         if (!(LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2297             vp->v_cache_dd == NULL)) {
2298                 mtx_lock(vlp);
2299                 cache_purge_impl(vp);
2300                 mtx_assert(vlp, MA_NOTOWNED);
2301                 return;
2302         }
2303
2304         /*
2305          * All the NULL pointer state we found above may be transient.
2306          * Serialize against a possible thread doing cache_purge.
2307          */
2308         mtx_wait_unlocked(vlp);
2309         if (!(LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2310             vp->v_cache_dd == NULL)) {
2311                 mtx_lock(vlp);
2312                 cache_purge_impl(vp);
2313                 mtx_assert(vlp, MA_NOTOWNED);
2314                 return;
2315         }
2316         return;
2317 }
2318
2319 /*
2320  * Invalidate all negative entries for a particular directory vnode.
2321  */
2322 void
2323 cache_purge_negative(struct vnode *vp)
2324 {
2325         TAILQ_HEAD(, namecache) ncps;
2326         struct namecache *ncp, *nnp;
2327         struct mtx *vlp;
2328
2329         SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2330         if (LIST_EMPTY(&vp->v_cache_src))
2331                 return;
2332         TAILQ_INIT(&ncps);
2333         vlp = VP2VNODELOCK(vp);
2334         mtx_lock(vlp);
2335         LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2336                 if (!(ncp->nc_flag & NCF_NEGATIVE))
2337                         continue;
2338                 cache_zap_negative_locked_vnode_kl(ncp, vp);
2339                 TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
2340         }
2341         mtx_unlock(vlp);
2342         TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
2343                 cache_free(ncp);
2344         }
2345 }
2346
2347 void
2348 cache_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2349     struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2350 {
2351
2352         ASSERT_VOP_IN_SEQC(fdvp);
2353         ASSERT_VOP_IN_SEQC(fvp);
2354         ASSERT_VOP_IN_SEQC(tdvp);
2355         if (tvp != NULL)
2356                 ASSERT_VOP_IN_SEQC(tvp);
2357
2358         cache_purge(fvp);
2359         if (tvp != NULL) {
2360                 cache_purge(tvp);
2361                 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2362                     ("%s: lingering negative entry", __func__));
2363         } else {
2364                 cache_remove_cnp(tdvp, tcnp);
2365         }
2366 }
2367
2368 /*
2369  * Flush all entries referencing a particular filesystem.
2370  */
2371 void
2372 cache_purgevfs(struct mount *mp, bool force)
2373 {
2374         struct vnode *vp, *mvp;
2375
2376         SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
2377         if (!force && mp->mnt_nvnodelistsize <= ncpurgeminvnodes)
2378                 return;
2379
2380         /*
2381          * Somewhat wasteful iteration over all vnodes. Would be better to
2382          * support filtering and avoid the interlock to begin with.
2383          */
2384         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2385                 if (!cache_has_entries(vp)) {
2386                         VI_UNLOCK(vp);
2387                         continue;
2388                 }
2389                 vholdl(vp);
2390                 VI_UNLOCK(vp);
2391                 cache_purge(vp);
2392                 vdrop(vp);
2393         }
2394 }
2395
2396 /*
2397  * Perform canonical checks and cache lookup and pass on to filesystem
2398  * through the vop_cachedlookup only if needed.
2399  */
2400
2401 int
2402 vfs_cache_lookup(struct vop_lookup_args *ap)
2403 {
2404         struct vnode *dvp;
2405         int error;
2406         struct vnode **vpp = ap->a_vpp;
2407         struct componentname *cnp = ap->a_cnp;
2408         int flags = cnp->cn_flags;
2409
2410         *vpp = NULL;
2411         dvp = ap->a_dvp;
2412
2413         if (dvp->v_type != VDIR)
2414                 return (ENOTDIR);
2415
2416         if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2417             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2418                 return (EROFS);
2419
2420         error = vn_dir_check_exec(dvp, cnp);
2421         if (error != 0)
2422                 return (error);
2423
2424         error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2425         if (error == 0)
2426                 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2427         if (error == -1)
2428                 return (0);
2429         return (error);
2430 }
2431
2432 /* Implementation of the getcwd syscall. */
2433 int
2434 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2435 {
2436         char *buf, *retbuf;
2437         size_t buflen;
2438         int error;
2439
2440         buflen = uap->buflen;
2441         if (__predict_false(buflen < 2))
2442                 return (EINVAL);
2443         if (buflen > MAXPATHLEN)
2444                 buflen = MAXPATHLEN;
2445
2446         buf = uma_zalloc(namei_zone, M_WAITOK);
2447         error = vn_getcwd(buf, &retbuf, &buflen);
2448         if (error == 0)
2449                 error = copyout(retbuf, uap->buf, buflen);
2450         uma_zfree(namei_zone, buf);
2451         return (error);
2452 }
2453
2454 int
2455 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
2456 {
2457         struct pwd *pwd;
2458         int error;
2459
2460         vfs_smr_enter();
2461         pwd = pwd_get_smr();
2462         error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
2463             buflen, false, 0);
2464         VFS_SMR_ASSERT_NOT_ENTERED();
2465         if (error < 0) {
2466                 pwd = pwd_hold(curthread);
2467                 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
2468                     retbuf, buflen);
2469                 pwd_drop(pwd);
2470         }
2471
2472 #ifdef KTRACE
2473         if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
2474                 ktrnamei(*retbuf);
2475 #endif
2476         return (error);
2477 }
2478
2479 static int
2480 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
2481     size_t size, int flags, enum uio_seg pathseg)
2482 {
2483         struct nameidata nd;
2484         char *retbuf, *freebuf;
2485         int error;
2486
2487         if (flags != 0)
2488                 return (EINVAL);
2489         NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
2490             pathseg, path, fd, &cap_fstat_rights, td);
2491         if ((error = namei(&nd)) != 0)
2492                 return (error);
2493         error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
2494         if (error == 0) {
2495                 error = copyout(retbuf, buf, size);
2496                 free(freebuf, M_TEMP);
2497         }
2498         NDFREE(&nd, 0);
2499         return (error);
2500 }
2501
2502 int
2503 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
2504 {
2505
2506         return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
2507             uap->flags, UIO_USERSPACE));
2508 }
2509
2510 /*
2511  * Retrieve the full filesystem path that correspond to a vnode from the name
2512  * cache (if available)
2513  */
2514 int
2515 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
2516 {
2517         struct pwd *pwd;
2518         char *buf;
2519         size_t buflen;
2520         int error;
2521
2522         if (__predict_false(vp == NULL))
2523                 return (EINVAL);
2524
2525         buflen = MAXPATHLEN;
2526         buf = malloc(buflen, M_TEMP, M_WAITOK);
2527         vfs_smr_enter();
2528         pwd = pwd_get_smr();
2529         error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, false, 0);
2530         VFS_SMR_ASSERT_NOT_ENTERED();
2531         if (error < 0) {
2532                 pwd = pwd_hold(curthread);
2533                 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
2534                 pwd_drop(pwd);
2535         }
2536         if (error == 0)
2537                 *freebuf = buf;
2538         else
2539                 free(buf, M_TEMP);
2540         return (error);
2541 }
2542
2543 /*
2544  * This function is similar to vn_fullpath, but it attempts to lookup the
2545  * pathname relative to the global root mount point.  This is required for the
2546  * auditing sub-system, as audited pathnames must be absolute, relative to the
2547  * global root mount point.
2548  */
2549 int
2550 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
2551 {
2552         char *buf;
2553         size_t buflen;
2554         int error;
2555
2556         if (__predict_false(vp == NULL))
2557                 return (EINVAL);
2558         buflen = MAXPATHLEN;
2559         buf = malloc(buflen, M_TEMP, M_WAITOK);
2560         vfs_smr_enter();
2561         error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, false, 0);
2562         VFS_SMR_ASSERT_NOT_ENTERED();
2563         if (error < 0) {
2564                 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
2565         }
2566         if (error == 0)
2567                 *freebuf = buf;
2568         else
2569                 free(buf, M_TEMP);
2570         return (error);
2571 }
2572
2573 static struct namecache *
2574 vn_dd_from_dst(struct vnode *vp)
2575 {
2576         struct namecache *ncp;
2577
2578         cache_assert_vnode_locked(vp);
2579         TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
2580                 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2581                         return (ncp);
2582         }
2583         return (NULL);
2584 }
2585
2586 int
2587 vn_vptocnp(struct vnode **vp, struct ucred *cred, char *buf, size_t *buflen)
2588 {
2589         struct vnode *dvp;
2590         struct namecache *ncp;
2591         struct mtx *vlp;
2592         int error;
2593
2594         vlp = VP2VNODELOCK(*vp);
2595         mtx_lock(vlp);
2596         ncp = (*vp)->v_cache_dd;
2597         if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
2598                 KASSERT(ncp == vn_dd_from_dst(*vp),
2599                     ("%s: mismatch for dd entry (%p != %p)", __func__,
2600                     ncp, vn_dd_from_dst(*vp)));
2601         } else {
2602                 ncp = vn_dd_from_dst(*vp);
2603         }
2604         if (ncp != NULL) {
2605                 if (*buflen < ncp->nc_nlen) {
2606                         mtx_unlock(vlp);
2607                         vrele(*vp);
2608                         counter_u64_add(numfullpathfail4, 1);
2609                         error = ENOMEM;
2610                         SDT_PROBE3(vfs, namecache, fullpath, return, error,
2611                             vp, NULL);
2612                         return (error);
2613                 }
2614                 *buflen -= ncp->nc_nlen;
2615                 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2616                 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2617                     ncp->nc_name, vp);
2618                 dvp = *vp;
2619                 *vp = ncp->nc_dvp;
2620                 vref(*vp);
2621                 mtx_unlock(vlp);
2622                 vrele(dvp);
2623                 return (0);
2624         }
2625         SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2626
2627         mtx_unlock(vlp);
2628         vn_lock(*vp, LK_SHARED | LK_RETRY);
2629         error = VOP_VPTOCNP(*vp, &dvp, cred, buf, buflen);
2630         vput(*vp);
2631         if (error) {
2632                 counter_u64_add(numfullpathfail2, 1);
2633                 SDT_PROBE3(vfs, namecache, fullpath, return,  error, vp, NULL);
2634                 return (error);
2635         }
2636
2637         *vp = dvp;
2638         if (VN_IS_DOOMED(dvp)) {
2639                 /* forced unmount */
2640                 vrele(dvp);
2641                 error = ENOENT;
2642                 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2643                 return (error);
2644         }
2645         /*
2646          * *vp has its use count incremented still.
2647          */
2648
2649         return (0);
2650 }
2651
2652 /*
2653  * Resolve a directory to a pathname.
2654  *
2655  * The name of the directory can always be found in the namecache or fetched
2656  * from the filesystem. There is also guaranteed to be only one parent, meaning
2657  * we can just follow vnodes up until we find the root.
2658  *
2659  * The vnode must be referenced.
2660  */
2661 static int
2662 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
2663     size_t *len, bool slash_prefixed, size_t addend)
2664 {
2665 #ifdef KDTRACE_HOOKS
2666         struct vnode *startvp = vp;
2667 #endif
2668         struct vnode *vp1;
2669         size_t buflen;
2670         int error;
2671
2672         VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
2673         VNPASS(vp->v_usecount > 0, vp);
2674
2675         buflen = *len;
2676
2677         if (!slash_prefixed) {
2678                 MPASS(*len >= 2);
2679                 buflen--;
2680                 buf[buflen] = '\0';
2681         }
2682
2683         error = 0;
2684
2685         SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
2686         counter_u64_add(numfullpathcalls, 1);
2687         while (vp != rdir && vp != rootvnode) {
2688                 /*
2689                  * The vp vnode must be already fully constructed,
2690                  * since it is either found in namecache or obtained
2691                  * from VOP_VPTOCNP().  We may test for VV_ROOT safely
2692                  * without obtaining the vnode lock.
2693                  */
2694                 if ((vp->v_vflag & VV_ROOT) != 0) {
2695                         vn_lock(vp, LK_RETRY | LK_SHARED);
2696
2697                         /*
2698                          * With the vnode locked, check for races with
2699                          * unmount, forced or not.  Note that we
2700                          * already verified that vp is not equal to
2701                          * the root vnode, which means that
2702                          * mnt_vnodecovered can be NULL only for the
2703                          * case of unmount.
2704                          */
2705                         if (VN_IS_DOOMED(vp) ||
2706                             (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
2707                             vp1->v_mountedhere != vp->v_mount) {
2708                                 vput(vp);
2709                                 error = ENOENT;
2710                                 SDT_PROBE3(vfs, namecache, fullpath, return,
2711                                     error, vp, NULL);
2712                                 break;
2713                         }
2714
2715                         vref(vp1);
2716                         vput(vp);
2717                         vp = vp1;
2718                         continue;
2719                 }
2720                 if (vp->v_type != VDIR) {
2721                         vrele(vp);
2722                         counter_u64_add(numfullpathfail1, 1);
2723                         error = ENOTDIR;
2724                         SDT_PROBE3(vfs, namecache, fullpath, return,
2725                             error, vp, NULL);
2726                         break;
2727                 }
2728                 error = vn_vptocnp(&vp, curthread->td_ucred, buf, &buflen);
2729                 if (error)
2730                         break;
2731                 if (buflen == 0) {
2732                         vrele(vp);
2733                         error = ENOMEM;
2734                         SDT_PROBE3(vfs, namecache, fullpath, return, error,
2735                             startvp, NULL);
2736                         break;
2737                 }
2738                 buf[--buflen] = '/';
2739                 slash_prefixed = true;
2740         }
2741         if (error)
2742                 return (error);
2743         if (!slash_prefixed) {
2744                 if (buflen == 0) {
2745                         vrele(vp);
2746                         counter_u64_add(numfullpathfail4, 1);
2747                         SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
2748                             startvp, NULL);
2749                         return (ENOMEM);
2750                 }
2751                 buf[--buflen] = '/';
2752         }
2753         counter_u64_add(numfullpathfound, 1);
2754         vrele(vp);
2755
2756         *retbuf = buf + buflen;
2757         SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
2758         *len -= buflen;
2759         *len += addend;
2760         return (0);
2761 }
2762
2763 /*
2764  * Resolve an arbitrary vnode to a pathname.
2765  *
2766  * Note 2 caveats:
2767  * - hardlinks are not tracked, thus if the vnode is not a directory this can
2768  *   resolve to a different path than the one used to find it
2769  * - namecache is not mandatory, meaning names are not guaranteed to be added
2770  *   (in which case resolving fails)
2771  */
2772 static void __inline
2773 cache_rev_failed_impl(int *reason, int line)
2774 {
2775
2776         *reason = line;
2777 }
2778 #define cache_rev_failed(var)   cache_rev_failed_impl((var), __LINE__)
2779
2780 static int
2781 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
2782     char **retbuf, size_t *buflen, bool slash_prefixed, size_t addend)
2783 {
2784 #ifdef KDTRACE_HOOKS
2785         struct vnode *startvp = vp;
2786 #endif
2787         struct vnode *tvp;
2788         struct mount *mp;
2789         struct namecache *ncp;
2790         size_t orig_buflen;
2791         int reason;
2792         int error;
2793 #ifdef KDTRACE_HOOKS
2794         int i;
2795 #endif
2796         seqc_t vp_seqc, tvp_seqc;
2797         u_char nc_flag;
2798
2799         VFS_SMR_ASSERT_ENTERED();
2800
2801         if (!cache_fast_revlookup) {
2802                 vfs_smr_exit();
2803                 return (-1);
2804         }
2805
2806         orig_buflen = *buflen;
2807
2808         if (!slash_prefixed) {
2809                 MPASS(*buflen >= 2);
2810                 *buflen -= 1;
2811                 buf[*buflen] = '\0';
2812         }
2813
2814         if (vp == rdir || vp == rootvnode) {
2815                 if (!slash_prefixed) {
2816                         *buflen -= 1;
2817                         buf[*buflen] = '/';
2818                 }
2819                 goto out_ok;
2820         }
2821
2822 #ifdef KDTRACE_HOOKS
2823         i = 0;
2824 #endif
2825         error = -1;
2826         ncp = NULL; /* for sdt probe down below */
2827         vp_seqc = vn_seqc_read_any(vp);
2828         if (seqc_in_modify(vp_seqc)) {
2829                 cache_rev_failed(&reason);
2830                 goto out_abort;
2831         }
2832
2833         for (;;) {
2834 #ifdef KDTRACE_HOOKS
2835                 i++;
2836 #endif
2837                 if ((vp->v_vflag & VV_ROOT) != 0) {
2838                         mp = atomic_load_ptr(&vp->v_mount);
2839                         if (mp == NULL) {
2840                                 cache_rev_failed(&reason);
2841                                 goto out_abort;
2842                         }
2843                         tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
2844                         tvp_seqc = vn_seqc_read_any(tvp);
2845                         if (seqc_in_modify(tvp_seqc)) {
2846                                 cache_rev_failed(&reason);
2847                                 goto out_abort;
2848                         }
2849                         if (!vn_seqc_consistent(vp, vp_seqc)) {
2850                                 cache_rev_failed(&reason);
2851                                 goto out_abort;
2852                         }
2853                         vp = tvp;
2854                         vp_seqc = tvp_seqc;
2855                         continue;
2856                 }
2857                 ncp = atomic_load_ptr(&vp->v_cache_dd);
2858                 if (ncp == NULL) {
2859                         cache_rev_failed(&reason);
2860                         goto out_abort;
2861                 }
2862                 nc_flag = atomic_load_char(&ncp->nc_flag);
2863                 if ((nc_flag & NCF_ISDOTDOT) != 0) {
2864                         cache_rev_failed(&reason);
2865                         goto out_abort;
2866                 }
2867                 if (!cache_ncp_canuse(ncp)) {
2868                         cache_rev_failed(&reason);
2869                         goto out_abort;
2870                 }
2871                 if (ncp->nc_nlen >= *buflen) {
2872                         cache_rev_failed(&reason);
2873                         error = ENOMEM;
2874                         goto out_abort;
2875                 }
2876                 *buflen -= ncp->nc_nlen;
2877                 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
2878                 *buflen -= 1;
2879                 buf[*buflen] = '/';
2880                 tvp = ncp->nc_dvp;
2881                 tvp_seqc = vn_seqc_read_any(tvp);
2882                 if (seqc_in_modify(tvp_seqc)) {
2883                         cache_rev_failed(&reason);
2884                         goto out_abort;
2885                 }
2886                 if (!vn_seqc_consistent(vp, vp_seqc)) {
2887                         cache_rev_failed(&reason);
2888                         goto out_abort;
2889                 }
2890                 vp = tvp;
2891                 vp_seqc = tvp_seqc;
2892                 if (vp == rdir || vp == rootvnode)
2893                         break;
2894         }
2895 out_ok:
2896         vfs_smr_exit();
2897         *retbuf = buf + *buflen;
2898         *buflen = orig_buflen - *buflen + addend;
2899         SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
2900         return (0);
2901
2902 out_abort:
2903         *buflen = orig_buflen;
2904         SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
2905         vfs_smr_exit();
2906         return (error);
2907 }
2908
2909 static int
2910 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
2911     size_t *buflen)
2912 {
2913         size_t orig_buflen;
2914         bool slash_prefixed;
2915         int error;
2916
2917         if (*buflen < 2)
2918                 return (EINVAL);
2919
2920         orig_buflen = *buflen;
2921
2922         vref(vp);
2923         slash_prefixed = false;
2924         if (vp->v_type != VDIR) {
2925                 *buflen -= 1;
2926                 buf[*buflen] = '\0';
2927                 error = vn_vptocnp(&vp, curthread->td_ucred, buf, buflen);
2928                 if (error)
2929                         return (error);
2930                 if (*buflen == 0) {
2931                         vrele(vp);
2932                         return (ENOMEM);
2933                 }
2934                 *buflen -= 1;
2935                 buf[*buflen] = '/';
2936                 slash_prefixed = true;
2937         }
2938
2939         return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, slash_prefixed,
2940             orig_buflen - *buflen));
2941 }
2942
2943 /*
2944  * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
2945  *
2946  * Since the namecache does not track handlings, the caller is expected to first
2947  * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
2948  *
2949  * Then we have 2 cases:
2950  * - if the found vnode is a directory, the path can be constructed just by
2951  *   fullowing names up the chain
2952  * - otherwise we populate the buffer with the saved name and start resolving
2953  *   from the parent
2954  */
2955 static int
2956 vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
2957     size_t *buflen)
2958 {
2959         char *buf, *tmpbuf;
2960         struct pwd *pwd;
2961         struct componentname *cnp;
2962         struct vnode *vp;
2963         size_t addend;
2964         int error;
2965         bool slash_prefixed;
2966         enum vtype type;
2967
2968         if (*buflen < 2)
2969                 return (EINVAL);
2970         if (*buflen > MAXPATHLEN)
2971                 *buflen = MAXPATHLEN;
2972
2973         slash_prefixed = false;
2974
2975         buf = malloc(*buflen, M_TEMP, M_WAITOK);
2976
2977         addend = 0;
2978         vp = ndp->ni_vp;
2979         /*
2980          * Check for VBAD to work around the vp_crossmp bug in lookup().
2981          *
2982          * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
2983          * set to mount point's root vnode while ni_dvp will be vp_crossmp.
2984          * If the type is VDIR (like in this very case) we can skip looking
2985          * at ni_dvp in the first place. However, since vnodes get passed here
2986          * unlocked the target may transition to doomed state (type == VBAD)
2987          * before we get to evaluate the condition. If this happens, we will
2988          * populate part of the buffer and descend to vn_fullpath_dir with
2989          * vp == vp_crossmp. Prevent the problem by checking for VBAD.
2990          *
2991          * This should be atomic_load(&vp->v_type) but it is ilegal to take
2992          * an address of a bit field, even if said field is sized to char.
2993          * Work around the problem by reading the value into a full-sized enum
2994          * and then re-reading it with atomic_load which will still prevent
2995          * the compiler from re-reading down the road.
2996          */
2997         type = vp->v_type;
2998         type = atomic_load_int(&type);
2999         if (type == VBAD) {
3000                 error = ENOENT;
3001                 goto out_bad;
3002         }
3003         if (type != VDIR) {
3004                 cnp = &ndp->ni_cnd;
3005                 addend = cnp->cn_namelen + 2;
3006                 if (*buflen < addend) {
3007                         error = ENOMEM;
3008                         goto out_bad;
3009                 }
3010                 *buflen -= addend;
3011                 tmpbuf = buf + *buflen;
3012                 tmpbuf[0] = '/';
3013                 memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
3014                 tmpbuf[addend - 1] = '\0';
3015                 slash_prefixed = true;
3016                 vp = ndp->ni_dvp;
3017         }
3018
3019         vfs_smr_enter();
3020         pwd = pwd_get_smr();
3021         error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3022             slash_prefixed, addend);
3023         VFS_SMR_ASSERT_NOT_ENTERED();
3024         if (error < 0) {
3025                 pwd = pwd_hold(curthread);
3026                 vref(vp);
3027                 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3028                     slash_prefixed, addend);
3029                 pwd_drop(pwd);
3030                 if (error != 0)
3031                         goto out_bad;
3032         }
3033
3034         *freebuf = buf;
3035
3036         return (0);
3037 out_bad:
3038         free(buf, M_TEMP);
3039         return (error);
3040 }
3041
3042 struct vnode *
3043 vn_dir_dd_ino(struct vnode *vp)
3044 {
3045         struct namecache *ncp;
3046         struct vnode *ddvp;
3047         struct mtx *vlp;
3048         enum vgetstate vs;
3049
3050         ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3051         vlp = VP2VNODELOCK(vp);
3052         mtx_lock(vlp);
3053         TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3054                 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3055                         continue;
3056                 ddvp = ncp->nc_dvp;
3057                 vs = vget_prep(ddvp);
3058                 mtx_unlock(vlp);
3059                 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3060                         return (NULL);
3061                 return (ddvp);
3062         }
3063         mtx_unlock(vlp);
3064         return (NULL);
3065 }
3066
3067 int
3068 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3069 {
3070         struct namecache *ncp;
3071         struct mtx *vlp;
3072         int l;
3073
3074         vlp = VP2VNODELOCK(vp);
3075         mtx_lock(vlp);
3076         TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3077                 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3078                         break;
3079         if (ncp == NULL) {
3080                 mtx_unlock(vlp);
3081                 return (ENOENT);
3082         }
3083         l = min(ncp->nc_nlen, buflen - 1);
3084         memcpy(buf, ncp->nc_name, l);
3085         mtx_unlock(vlp);
3086         buf[l] = '\0';
3087         return (0);
3088 }
3089
3090 /*
3091  * This function updates path string to vnode's full global path
3092  * and checks the size of the new path string against the pathlen argument.
3093  *
3094  * Requires a locked, referenced vnode.
3095  * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3096  *
3097  * If vp is a directory, the call to vn_fullpath_global() always succeeds
3098  * because it falls back to the ".." lookup if the namecache lookup fails.
3099  */
3100 int
3101 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3102     u_int pathlen)
3103 {
3104         struct nameidata nd;
3105         struct vnode *vp1;
3106         char *rpath, *fbuf;
3107         int error;
3108
3109         ASSERT_VOP_ELOCKED(vp, __func__);
3110
3111         /* Construct global filesystem path from vp. */
3112         VOP_UNLOCK(vp);
3113         error = vn_fullpath_global(vp, &rpath, &fbuf);
3114
3115         if (error != 0) {
3116                 vrele(vp);
3117                 return (error);
3118         }
3119
3120         if (strlen(rpath) >= pathlen) {
3121                 vrele(vp);
3122                 error = ENAMETOOLONG;
3123                 goto out;
3124         }
3125
3126         /*
3127          * Re-lookup the vnode by path to detect a possible rename.
3128          * As a side effect, the vnode is relocked.
3129          * If vnode was renamed, return ENOENT.
3130          */
3131         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3132             UIO_SYSSPACE, path, td);
3133         error = namei(&nd);
3134         if (error != 0) {
3135                 vrele(vp);
3136                 goto out;
3137         }
3138         NDFREE(&nd, NDF_ONLY_PNBUF);
3139         vp1 = nd.ni_vp;
3140         vrele(vp);
3141         if (vp1 == vp)
3142                 strcpy(path, rpath);
3143         else {
3144                 vput(vp1);
3145                 error = ENOENT;
3146         }
3147
3148 out:
3149         free(fbuf, M_TEMP);
3150         return (error);
3151 }
3152
3153 #ifdef DDB
3154 static void
3155 db_print_vpath(struct vnode *vp)
3156 {
3157
3158         while (vp != NULL) {
3159                 db_printf("%p: ", vp);
3160                 if (vp == rootvnode) {
3161                         db_printf("/");
3162                         vp = NULL;
3163                 } else {
3164                         if (vp->v_vflag & VV_ROOT) {
3165                                 db_printf("<mount point>");
3166                                 vp = vp->v_mount->mnt_vnodecovered;
3167                         } else {
3168                                 struct namecache *ncp;
3169                                 char *ncn;
3170                                 int i;
3171
3172                                 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3173                                 if (ncp != NULL) {
3174                                         ncn = ncp->nc_name;
3175                                         for (i = 0; i < ncp->nc_nlen; i++)
3176                                                 db_printf("%c", *ncn++);
3177                                         vp = ncp->nc_dvp;
3178                                 } else {
3179                                         vp = NULL;
3180                                 }
3181                         }
3182                 }
3183                 db_printf("\n");
3184         }
3185
3186         return;
3187 }
3188
3189 DB_SHOW_COMMAND(vpath, db_show_vpath)
3190 {
3191         struct vnode *vp;
3192
3193         if (!have_addr) {
3194                 db_printf("usage: show vpath <struct vnode *>\n");
3195                 return;
3196         }
3197
3198         vp = (struct vnode *)addr;
3199         db_print_vpath(vp);
3200 }
3201
3202 #endif
3203
3204 static bool __read_frequently cache_fast_lookup = true;
3205 SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_lookup, CTLFLAG_RW,
3206     &cache_fast_lookup, 0, "");
3207
3208 #define CACHE_FPL_FAILED        -2020
3209
3210 static void
3211 cache_fpl_cleanup_cnp(struct componentname *cnp)
3212 {
3213
3214         uma_zfree(namei_zone, cnp->cn_pnbuf);
3215 #ifdef DIAGNOSTIC
3216         cnp->cn_pnbuf = NULL;
3217         cnp->cn_nameptr = NULL;
3218 #endif
3219 }
3220
3221 static void
3222 cache_fpl_handle_root(struct nameidata *ndp, struct vnode **dpp)
3223 {
3224         struct componentname *cnp;
3225
3226         cnp = &ndp->ni_cnd;
3227         while (*(cnp->cn_nameptr) == '/') {
3228                 cnp->cn_nameptr++;
3229                 ndp->ni_pathlen--;
3230         }
3231
3232         *dpp = ndp->ni_rootdir;
3233 }
3234
3235 /*
3236  * Components of nameidata (or objects it can point to) which may
3237  * need restoring in case fast path lookup fails.
3238  */
3239 struct nameidata_saved {
3240         long cn_namelen;
3241         char *cn_nameptr;
3242         size_t ni_pathlen;
3243         int cn_flags;
3244 };
3245
3246 struct cache_fpl {
3247         struct nameidata *ndp;
3248         struct componentname *cnp;
3249         struct pwd *pwd;
3250         struct vnode *dvp;
3251         struct vnode *tvp;
3252         seqc_t dvp_seqc;
3253         seqc_t tvp_seqc;
3254         struct nameidata_saved snd;
3255         int line;
3256         enum cache_fpl_status status:8;
3257         bool in_smr;
3258 };
3259
3260 static void
3261 cache_fpl_checkpoint(struct cache_fpl *fpl, struct nameidata_saved *snd)
3262 {
3263
3264         snd->cn_flags = fpl->ndp->ni_cnd.cn_flags;
3265         snd->cn_namelen = fpl->ndp->ni_cnd.cn_namelen;
3266         snd->cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
3267         snd->ni_pathlen = fpl->ndp->ni_pathlen;
3268 }
3269
3270 static void
3271 cache_fpl_restore(struct cache_fpl *fpl, struct nameidata_saved *snd)
3272 {
3273
3274         fpl->ndp->ni_cnd.cn_flags = snd->cn_flags;
3275         fpl->ndp->ni_cnd.cn_namelen = snd->cn_namelen;
3276         fpl->ndp->ni_cnd.cn_nameptr = snd->cn_nameptr;
3277         fpl->ndp->ni_pathlen = snd->ni_pathlen;
3278 }
3279
3280 #ifdef INVARIANTS
3281 #define cache_fpl_smr_assert_entered(fpl) ({                    \
3282         struct cache_fpl *_fpl = (fpl);                         \
3283         MPASS(_fpl->in_smr == true);                            \
3284         VFS_SMR_ASSERT_ENTERED();                               \
3285 })
3286 #define cache_fpl_smr_assert_not_entered(fpl) ({                \
3287         struct cache_fpl *_fpl = (fpl);                         \
3288         MPASS(_fpl->in_smr == false);                           \
3289         VFS_SMR_ASSERT_NOT_ENTERED();                           \
3290 })
3291 #else
3292 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
3293 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
3294 #endif
3295
3296 #define cache_fpl_smr_enter_initial(fpl) ({                     \
3297         struct cache_fpl *_fpl = (fpl);                         \
3298         vfs_smr_enter();                                        \
3299         _fpl->in_smr = true;                                    \
3300 })
3301
3302 #define cache_fpl_smr_enter(fpl) ({                             \
3303         struct cache_fpl *_fpl = (fpl);                         \
3304         MPASS(_fpl->in_smr == false);                           \
3305         vfs_smr_enter();                                        \
3306         _fpl->in_smr = true;                                    \
3307 })
3308
3309 #define cache_fpl_smr_exit(fpl) ({                              \
3310         struct cache_fpl *_fpl = (fpl);                         \
3311         MPASS(_fpl->in_smr == true);                            \
3312         vfs_smr_exit();                                         \
3313         _fpl->in_smr = false;                                   \
3314 })
3315
3316 static int
3317 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
3318 {
3319
3320         if (fpl->status != CACHE_FPL_STATUS_UNSET) {
3321                 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
3322                     ("%s: converting to abort from %d at %d, set at %d\n",
3323                     __func__, fpl->status, line, fpl->line));
3324         }
3325         fpl->status = CACHE_FPL_STATUS_ABORTED;
3326         fpl->line = line;
3327         return (CACHE_FPL_FAILED);
3328 }
3329
3330 #define cache_fpl_aborted(x)    cache_fpl_aborted_impl((x), __LINE__)
3331
3332 static int
3333 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
3334 {
3335
3336         KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3337             ("%s: setting to partial at %d, but already set to %d at %d\n",
3338             __func__, line, fpl->status, fpl->line));
3339         cache_fpl_smr_assert_entered(fpl);
3340         fpl->status = CACHE_FPL_STATUS_PARTIAL;
3341         fpl->line = line;
3342         return (CACHE_FPL_FAILED);
3343 }
3344
3345 #define cache_fpl_partial(x)    cache_fpl_partial_impl((x), __LINE__)
3346
3347 static int
3348 cache_fpl_handled_impl(struct cache_fpl *fpl, int error, int line)
3349 {
3350
3351         KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
3352             ("%s: setting to handled at %d, but already set to %d at %d\n",
3353             __func__, line, fpl->status, fpl->line));
3354         cache_fpl_smr_assert_not_entered(fpl);
3355         MPASS(error != CACHE_FPL_FAILED);
3356         fpl->status = CACHE_FPL_STATUS_HANDLED;
3357         fpl->line = line;
3358         return (error);
3359 }
3360
3361 #define cache_fpl_handled(x, e) cache_fpl_handled_impl((x), (e), __LINE__)
3362
3363 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
3364         (LOCKLEAF | LOCKPARENT | WANTPARENT | NOCACHE | FOLLOW | LOCKSHARED | SAVENAME | \
3365          SAVESTART | WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)
3366
3367 #define CACHE_FPL_INTERNAL_CN_FLAGS \
3368         (ISDOTDOT | MAKEENTRY | ISLASTCN)
3369
3370 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
3371     "supported and internal flags overlap");
3372
3373 static bool
3374 cache_fpl_islastcn(struct nameidata *ndp)
3375 {
3376
3377         return (*ndp->ni_next == 0);
3378 }
3379
3380 static bool
3381 cache_fpl_isdotdot(struct componentname *cnp)
3382 {
3383
3384         if (cnp->cn_namelen == 2 &&
3385             cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
3386                 return (true);
3387         return (false);
3388 }
3389
3390 static bool
3391 cache_can_fplookup(struct cache_fpl *fpl)
3392 {
3393         struct nameidata *ndp;
3394         struct componentname *cnp;
3395         struct thread *td;
3396
3397         ndp = fpl->ndp;
3398         cnp = fpl->cnp;
3399         td = cnp->cn_thread;
3400
3401         if (!cache_fast_lookup) {
3402                 cache_fpl_aborted(fpl);
3403                 return (false);
3404         }
3405 #ifdef MAC
3406         if (mac_vnode_check_lookup_enabled()) {
3407                 cache_fpl_aborted(fpl);
3408                 return (false);
3409         }
3410 #endif
3411         if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
3412                 cache_fpl_aborted(fpl);
3413                 return (false);
3414         }
3415         if (ndp->ni_dirfd != AT_FDCWD) {
3416                 cache_fpl_aborted(fpl);
3417                 return (false);
3418         }
3419         if (IN_CAPABILITY_MODE(td)) {
3420                 cache_fpl_aborted(fpl);
3421                 return (false);
3422         }
3423         if (AUDITING_TD(td)) {
3424                 cache_fpl_aborted(fpl);
3425                 return (false);
3426         }
3427         if (ndp->ni_startdir != NULL) {
3428                 cache_fpl_aborted(fpl);
3429                 return (false);
3430         }
3431         return (true);
3432 }
3433
3434 static bool
3435 cache_fplookup_vnode_supported(struct vnode *vp)
3436 {
3437
3438         return (vp->v_type != VLNK);
3439 }
3440
3441 /*
3442  * Move a negative entry to the hot list.
3443  *
3444  * We have to take locks, but they may be contended and in the worst
3445  * case we may need to go off CPU. We don't want to spin within the
3446  * smr section and we can't block with it. Instead we are going to
3447  * look up the entry again.
3448  */
3449 static int __noinline
3450 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
3451     uint32_t hash)
3452 {
3453         struct componentname *cnp;
3454         struct namecache *ncp;
3455         struct neglist *neglist;
3456         struct negstate *negstate;
3457         struct vnode *dvp;
3458         u_char nc_flag;
3459
3460         cnp = fpl->cnp;
3461         dvp = fpl->dvp;
3462
3463         if (!vhold_smr(dvp))
3464                 return (cache_fpl_aborted(fpl));
3465
3466         neglist = NCP2NEGLIST(oncp);
3467         cache_fpl_smr_exit(fpl);
3468
3469         mtx_lock(&ncneg_hot.nl_lock);
3470         mtx_lock(&neglist->nl_lock);
3471         /*
3472          * For hash iteration.
3473          */
3474         cache_fpl_smr_enter(fpl);
3475
3476         /*
3477          * Avoid all surprises by only succeeding if we got the same entry and
3478          * bailing completely otherwise.
3479          *
3480          * In particular at this point there can be a new ncp which matches the
3481          * search but hashes to a different neglist.
3482          */
3483         CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3484                 if (ncp == oncp)
3485                         break;
3486         }
3487
3488         /*
3489          * No match to begin with.
3490          */
3491         if (__predict_false(ncp == NULL)) {
3492                 goto out_abort;
3493         }
3494
3495         /*
3496          * The newly found entry may be something different...
3497          */
3498         if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3499             !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
3500                 goto out_abort;
3501         }
3502
3503         /*
3504          * ... and not even negative.
3505          */
3506         nc_flag = atomic_load_char(&ncp->nc_flag);
3507         if ((nc_flag & NCF_NEGATIVE) == 0) {
3508                 goto out_abort;
3509         }
3510
3511         if (__predict_false(!cache_ncp_canuse(ncp))) {
3512                 goto out_abort;
3513         }
3514
3515         negstate = NCP2NEGSTATE(ncp);
3516         if ((negstate->neg_flag & NEG_HOT) == 0) {
3517                 numhotneg++;
3518                 TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
3519                 TAILQ_INSERT_TAIL(&ncneg_hot.nl_list, ncp, nc_dst);
3520                 negstate->neg_flag |= NEG_HOT;
3521         }
3522
3523         SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp, ncp->nc_name);
3524         counter_u64_add(numneghits, 1);
3525         cache_fpl_smr_exit(fpl);
3526         mtx_unlock(&neglist->nl_lock);
3527         mtx_unlock(&ncneg_hot.nl_lock);
3528         vdrop(dvp);
3529         return (cache_fpl_handled(fpl, ENOENT));
3530 out_abort:
3531         cache_fpl_smr_exit(fpl);
3532         mtx_unlock(&neglist->nl_lock);
3533         mtx_unlock(&ncneg_hot.nl_lock);
3534         vdrop(dvp);
3535         return (cache_fpl_aborted(fpl));
3536 }
3537
3538 /*
3539  * The target vnode is not supported, prepare for the slow path to take over.
3540  */
3541 static int __noinline
3542 cache_fplookup_partial_setup(struct cache_fpl *fpl)
3543 {
3544         struct nameidata *ndp;
3545         struct componentname *cnp;
3546         enum vgetstate dvs;
3547         struct vnode *dvp;
3548         struct pwd *pwd;
3549         seqc_t dvp_seqc;
3550
3551         ndp = fpl->ndp;
3552         cnp = fpl->cnp;
3553         dvp = fpl->dvp;
3554         dvp_seqc = fpl->dvp_seqc;
3555
3556         dvs = vget_prep_smr(dvp);
3557         if (__predict_false(dvs == VGET_NONE)) {
3558                 cache_fpl_smr_exit(fpl);
3559                 return (cache_fpl_aborted(fpl));
3560         }
3561
3562         cache_fpl_smr_exit(fpl);
3563
3564         vget_finish_ref(dvp, dvs);
3565         if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3566                 vrele(dvp);
3567                 return (cache_fpl_aborted(fpl));
3568         }
3569
3570         pwd = pwd_hold(curthread);
3571         if (fpl->pwd != pwd) {
3572                 vrele(dvp);
3573                 pwd_drop(pwd);
3574                 return (cache_fpl_aborted(fpl));
3575         }
3576
3577         cache_fpl_restore(fpl, &fpl->snd);
3578
3579         ndp->ni_startdir = dvp;
3580         cnp->cn_flags |= MAKEENTRY;
3581         if (cache_fpl_islastcn(ndp))
3582                 cnp->cn_flags |= ISLASTCN;
3583         if (cache_fpl_isdotdot(cnp))
3584                 cnp->cn_flags |= ISDOTDOT;
3585
3586         return (0);
3587 }
3588
3589 static int
3590 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
3591 {
3592         struct componentname *cnp;
3593         struct vnode *tvp;
3594         seqc_t tvp_seqc;
3595         int error, lkflags;
3596
3597         cnp = fpl->cnp;
3598         tvp = fpl->tvp;
3599         tvp_seqc = fpl->tvp_seqc;
3600
3601         if ((cnp->cn_flags & LOCKLEAF) != 0) {
3602                 lkflags = LK_SHARED;
3603                 if ((cnp->cn_flags & LOCKSHARED) == 0)
3604                         lkflags = LK_EXCLUSIVE;
3605                 error = vget_finish(tvp, lkflags, tvs);
3606                 if (__predict_false(error != 0)) {
3607                         return (cache_fpl_aborted(fpl));
3608                 }
3609         } else {
3610                 vget_finish_ref(tvp, tvs);
3611         }
3612
3613         if (!vn_seqc_consistent(tvp, tvp_seqc)) {
3614                 if ((cnp->cn_flags & LOCKLEAF) != 0)
3615                         vput(tvp);
3616                 else
3617                         vrele(tvp);
3618                 return (cache_fpl_aborted(fpl));
3619         }
3620
3621         return (cache_fpl_handled(fpl, 0));
3622 }
3623
3624 /*
3625  * They want to possibly modify the state of the namecache.
3626  *
3627  * Don't try to match the API contract, just leave.
3628  * TODO: this leaves scalability on the table
3629  */
3630 static int
3631 cache_fplookup_final_modifying(struct cache_fpl *fpl)
3632 {
3633         struct componentname *cnp;
3634
3635         cnp = fpl->cnp;
3636         MPASS(cnp->cn_nameiop != LOOKUP);
3637         return (cache_fpl_partial(fpl));
3638 }
3639
3640 static int __noinline
3641 cache_fplookup_final_withparent(struct cache_fpl *fpl)
3642 {
3643         struct componentname *cnp;
3644         enum vgetstate dvs, tvs;
3645         struct vnode *dvp, *tvp;
3646         seqc_t dvp_seqc;
3647         int error;
3648
3649         cnp = fpl->cnp;
3650         dvp = fpl->dvp;
3651         dvp_seqc = fpl->dvp_seqc;
3652         tvp = fpl->tvp;
3653
3654         MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
3655
3656         /*
3657          * This is less efficient than it can be for simplicity.
3658          */
3659         dvs = vget_prep_smr(dvp);
3660         if (__predict_false(dvs == VGET_NONE)) {
3661                 return (cache_fpl_aborted(fpl));
3662         }
3663         tvs = vget_prep_smr(tvp);
3664         if (__predict_false(tvs == VGET_NONE)) {
3665                 cache_fpl_smr_exit(fpl);
3666                 vget_abort(dvp, dvs);
3667                 return (cache_fpl_aborted(fpl));
3668         }
3669
3670         cache_fpl_smr_exit(fpl);
3671
3672         if ((cnp->cn_flags & LOCKPARENT) != 0) {
3673                 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
3674                 if (__predict_false(error != 0)) {
3675                         vget_abort(tvp, tvs);
3676                         return (cache_fpl_aborted(fpl));
3677                 }
3678         } else {
3679                 vget_finish_ref(dvp, dvs);
3680         }
3681
3682         if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3683                 vget_abort(tvp, tvs);
3684                 if ((cnp->cn_flags & LOCKPARENT) != 0)
3685                         vput(dvp);
3686                 else
3687                         vrele(dvp);
3688                 return (cache_fpl_aborted(fpl));
3689         }
3690
3691         error = cache_fplookup_final_child(fpl, tvs);
3692         if (__predict_false(error != 0)) {
3693                 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
3694                 if ((cnp->cn_flags & LOCKPARENT) != 0)
3695                         vput(dvp);
3696                 else
3697                         vrele(dvp);
3698                 return (error);
3699         }
3700
3701         MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
3702         return (0);
3703 }
3704
3705 static int
3706 cache_fplookup_final(struct cache_fpl *fpl)
3707 {
3708         struct componentname *cnp;
3709         enum vgetstate tvs;
3710         struct vnode *dvp, *tvp;
3711         seqc_t dvp_seqc;
3712
3713         cnp = fpl->cnp;
3714         dvp = fpl->dvp;
3715         dvp_seqc = fpl->dvp_seqc;
3716         tvp = fpl->tvp;
3717
3718         VNPASS(cache_fplookup_vnode_supported(dvp), dvp);
3719
3720         if (cnp->cn_nameiop != LOOKUP) {
3721                 return (cache_fplookup_final_modifying(fpl));
3722         }
3723
3724         if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
3725                 return (cache_fplookup_final_withparent(fpl));
3726
3727         tvs = vget_prep_smr(tvp);
3728         if (__predict_false(tvs == VGET_NONE)) {
3729                 return (cache_fpl_partial(fpl));
3730         }
3731
3732         if (!vn_seqc_consistent(dvp, dvp_seqc)) {
3733                 cache_fpl_smr_exit(fpl);
3734                 vget_abort(tvp, tvs);
3735                 return (cache_fpl_aborted(fpl));
3736         }
3737
3738         cache_fpl_smr_exit(fpl);
3739         return (cache_fplookup_final_child(fpl, tvs));
3740 }
3741
3742 static int __noinline
3743 cache_fplookup_dot(struct cache_fpl *fpl)
3744 {
3745         struct vnode *dvp;
3746
3747         dvp = fpl->dvp;
3748
3749         fpl->tvp = dvp;
3750         fpl->tvp_seqc = vn_seqc_read_any(dvp);
3751         if (seqc_in_modify(fpl->tvp_seqc)) {
3752                 return (cache_fpl_aborted(fpl));
3753         }
3754
3755         counter_u64_add(dothits, 1);
3756         SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", dvp);
3757
3758         return (0);
3759 }
3760
3761 static int __noinline
3762 cache_fplookup_dotdot(struct cache_fpl *fpl)
3763 {
3764         struct nameidata *ndp;
3765         struct componentname *cnp;
3766         struct namecache *ncp;
3767         struct vnode *dvp;
3768         struct prison *pr;
3769         u_char nc_flag;
3770
3771         ndp = fpl->ndp;
3772         cnp = fpl->cnp;
3773         dvp = fpl->dvp;
3774
3775         /*
3776          * XXX this is racy the same way regular lookup is
3777          */
3778         for (pr = cnp->cn_cred->cr_prison; pr != NULL;
3779             pr = pr->pr_parent)
3780                 if (dvp == pr->pr_root)
3781                         break;
3782
3783         if (dvp == ndp->ni_rootdir ||
3784             dvp == ndp->ni_topdir ||
3785             dvp == rootvnode ||
3786             pr != NULL) {
3787                 fpl->tvp = dvp;
3788                 fpl->tvp_seqc = vn_seqc_read_any(dvp);
3789                 if (seqc_in_modify(fpl->tvp_seqc)) {
3790                         return (cache_fpl_aborted(fpl));
3791                 }
3792                 return (0);
3793         }
3794
3795         if ((dvp->v_vflag & VV_ROOT) != 0) {
3796                 /*
3797                  * TODO
3798                  * The opposite of climb mount is needed here.
3799                  */
3800                 return (cache_fpl_aborted(fpl));
3801         }
3802
3803         ncp = atomic_load_ptr(&dvp->v_cache_dd);
3804         if (ncp == NULL) {
3805                 return (cache_fpl_aborted(fpl));
3806         }
3807
3808         nc_flag = atomic_load_char(&ncp->nc_flag);
3809         if ((nc_flag & NCF_ISDOTDOT) != 0) {
3810                 if ((nc_flag & NCF_NEGATIVE) != 0)
3811                         return (cache_fpl_aborted(fpl));
3812                 fpl->tvp = ncp->nc_vp;
3813         } else {
3814                 fpl->tvp = ncp->nc_dvp;
3815         }
3816
3817         if (__predict_false(!cache_ncp_canuse(ncp))) {
3818                 return (cache_fpl_aborted(fpl));
3819         }
3820
3821         fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
3822         if (seqc_in_modify(fpl->tvp_seqc)) {
3823                 return (cache_fpl_partial(fpl));
3824         }
3825
3826         counter_u64_add(dotdothits, 1);
3827         return (0);
3828 }
3829
3830 static int
3831 cache_fplookup_next(struct cache_fpl *fpl)
3832 {
3833         struct componentname *cnp;
3834         struct namecache *ncp;
3835         struct negstate *negstate;
3836         struct vnode *dvp, *tvp;
3837         u_char nc_flag;
3838         uint32_t hash;
3839         bool neg_hot;
3840
3841         cnp = fpl->cnp;
3842         dvp = fpl->dvp;
3843
3844         if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.')) {
3845                 return (cache_fplookup_dot(fpl));
3846         }
3847
3848         hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
3849
3850         CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3851                 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3852                     !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
3853                         break;
3854         }
3855
3856         /*
3857          * If there is no entry we have to punt to the slow path to perform
3858          * actual lookup. Should there be nothing with this name a negative
3859          * entry will be created.
3860          */
3861         if (__predict_false(ncp == NULL)) {
3862                 return (cache_fpl_partial(fpl));
3863         }
3864
3865         tvp = atomic_load_ptr(&ncp->nc_vp);
3866         nc_flag = atomic_load_char(&ncp->nc_flag);
3867         if ((nc_flag & NCF_NEGATIVE) != 0) {
3868                 /*
3869                  * If they want to create an entry we need to replace this one.
3870                  */
3871                 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
3872                         return (cache_fpl_partial(fpl));
3873                 }
3874                 negstate = NCP2NEGSTATE(ncp);
3875                 neg_hot = ((negstate->neg_flag & NEG_HOT) != 0);
3876                 if (__predict_false(!cache_ncp_canuse(ncp))) {
3877                         return (cache_fpl_partial(fpl));
3878                 }
3879                 if (__predict_false((nc_flag & NCF_WHITE) != 0)) {
3880                         return (cache_fpl_partial(fpl));
3881                 }
3882                 if (!neg_hot) {
3883                         return (cache_fplookup_negative_promote(fpl, ncp, hash));
3884                 }
3885                 SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp,
3886                     ncp->nc_name);
3887                 counter_u64_add(numneghits, 1);
3888                 cache_fpl_smr_exit(fpl);
3889                 return (cache_fpl_handled(fpl, ENOENT));
3890         }
3891
3892         if (__predict_false(!cache_ncp_canuse(ncp))) {
3893                 return (cache_fpl_partial(fpl));
3894         }
3895
3896         fpl->tvp = tvp;
3897         fpl->tvp_seqc = vn_seqc_read_any(tvp);
3898         if (seqc_in_modify(fpl->tvp_seqc)) {
3899                 return (cache_fpl_partial(fpl));
3900         }
3901
3902         if (!cache_fplookup_vnode_supported(tvp)) {
3903                 return (cache_fpl_partial(fpl));
3904         }
3905
3906         counter_u64_add(numposhits, 1);
3907         SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
3908         return (0);
3909 }
3910
3911 static bool
3912 cache_fplookup_mp_supported(struct mount *mp)
3913 {
3914
3915         if (mp == NULL)
3916                 return (false);
3917         if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
3918                 return (false);
3919         return (true);
3920 }
3921
3922 /*
3923  * Walk up the mount stack (if any).
3924  *
3925  * Correctness is provided in the following ways:
3926  * - all vnodes are protected from freeing with SMR
3927  * - struct mount objects are type stable making them always safe to access
3928  * - stability of the particular mount is provided by busying it
3929  * - relationship between the vnode which is mounted on and the mount is
3930  *   verified with the vnode sequence counter after busying
3931  * - association between root vnode of the mount and the mount is protected
3932  *   by busy
3933  *
3934  * From that point on we can read the sequence counter of the root vnode
3935  * and get the next mount on the stack (if any) using the same protection.
3936  *
3937  * By the end of successful walk we are guaranteed the reached state was
3938  * indeed present at least at some point which matches the regular lookup.
3939  */
3940 static int __noinline
3941 cache_fplookup_climb_mount(struct cache_fpl *fpl)
3942 {
3943         struct mount *mp, *prev_mp;
3944         struct vnode *vp;
3945         seqc_t vp_seqc;
3946
3947         vp = fpl->tvp;
3948         vp_seqc = fpl->tvp_seqc;
3949
3950         VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
3951         mp = atomic_load_ptr(&vp->v_mountedhere);
3952         if (mp == NULL)
3953                 return (0);
3954
3955         prev_mp = NULL;
3956         for (;;) {
3957                 if (!vfs_op_thread_enter_crit(mp)) {
3958                         if (prev_mp != NULL)
3959                                 vfs_op_thread_exit_crit(prev_mp);
3960                         return (cache_fpl_partial(fpl));
3961                 }
3962                 if (prev_mp != NULL)
3963                         vfs_op_thread_exit_crit(prev_mp);
3964                 if (!vn_seqc_consistent(vp, vp_seqc)) {
3965                         vfs_op_thread_exit_crit(mp);
3966                         return (cache_fpl_partial(fpl));
3967                 }
3968                 if (!cache_fplookup_mp_supported(mp)) {
3969                         vfs_op_thread_exit_crit(mp);
3970                         return (cache_fpl_partial(fpl));
3971                 }
3972                 vp = atomic_load_ptr(&mp->mnt_rootvnode);
3973                 if (vp == NULL || VN_IS_DOOMED(vp)) {
3974                         vfs_op_thread_exit_crit(mp);
3975                         return (cache_fpl_partial(fpl));
3976                 }
3977                 vp_seqc = vn_seqc_read_any(vp);
3978                 if (seqc_in_modify(vp_seqc)) {
3979                         vfs_op_thread_exit_crit(mp);
3980                         return (cache_fpl_partial(fpl));
3981                 }
3982                 prev_mp = mp;
3983                 mp = atomic_load_ptr(&vp->v_mountedhere);
3984                 if (mp == NULL)
3985                         break;
3986         }
3987
3988         vfs_op_thread_exit_crit(prev_mp);
3989         fpl->tvp = vp;
3990         fpl->tvp_seqc = vp_seqc;
3991         return (0);
3992 }
3993
3994 static bool
3995 cache_fplookup_need_climb_mount(struct cache_fpl *fpl)
3996 {
3997         struct mount *mp;
3998         struct vnode *vp;
3999
4000         vp = fpl->tvp;
4001
4002         /*
4003          * Hack: while this is a union, the pointer tends to be NULL so save on
4004          * a branch.
4005          */
4006         mp = atomic_load_ptr(&vp->v_mountedhere);
4007         if (mp == NULL)
4008                 return (false);
4009         if (vp->v_type == VDIR)
4010                 return (true);
4011         return (false);
4012 }
4013
4014 /*
4015  * Parse the path.
4016  *
4017  * The code is mostly copy-pasted from regular lookup, see lookup().
4018  * The structure is maintained along with comments for easier maintenance.
4019  * Deduplicating the code will become feasible after fast path lookup
4020  * becomes more feature-complete.
4021  */
4022 static int
4023 cache_fplookup_parse(struct cache_fpl *fpl)
4024 {
4025         struct nameidata *ndp;
4026         struct componentname *cnp;
4027         char *cp;
4028
4029         ndp = fpl->ndp;
4030         cnp = fpl->cnp;
4031
4032         /*
4033          * Search a new directory.
4034          *
4035          * The last component of the filename is left accessible via
4036          * cnp->cn_nameptr for callers that need the name. Callers needing
4037          * the name set the SAVENAME flag. When done, they assume
4038          * responsibility for freeing the pathname buffer.
4039          */
4040         for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
4041                 continue;
4042         cnp->cn_namelen = cp - cnp->cn_nameptr;
4043         if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4044                 cache_fpl_smr_exit(fpl);
4045                 return (cache_fpl_handled(fpl, ENAMETOOLONG));
4046         }
4047         ndp->ni_pathlen -= cnp->cn_namelen;
4048         KASSERT(ndp->ni_pathlen <= PATH_MAX,
4049             ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
4050         ndp->ni_next = cp;
4051
4052         /*
4053          * Replace multiple slashes by a single slash and trailing slashes
4054          * by a null.  This must be done before VOP_LOOKUP() because some
4055          * fs's don't know about trailing slashes.  Remember if there were
4056          * trailing slashes to handle symlinks, existing non-directories
4057          * and non-existing files that won't be directories specially later.
4058          */
4059         while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
4060                 cp++;
4061                 ndp->ni_pathlen--;
4062                 if (*cp == '\0') {
4063                         /*
4064                          * TODO
4065                          * Regular lookup performs the following:
4066                          * *ndp->ni_next = '\0';
4067                          * cnp->cn_flags |= TRAILINGSLASH;
4068                          *
4069                          * Which is problematic since it modifies data read
4070                          * from userspace. Then if fast path lookup was to
4071                          * abort we would have to either restore it or convey
4072                          * the flag. Since this is a corner case just ignore
4073                          * it for simplicity.
4074                          */
4075                         return (cache_fpl_partial(fpl));
4076                 }
4077         }
4078         ndp->ni_next = cp;
4079
4080         /*
4081          * Check for degenerate name (e.g. / or "")
4082          * which is a way of talking about a directory,
4083          * e.g. like "/." or ".".
4084          *
4085          * TODO
4086          * Another corner case handled by the regular lookup
4087          */
4088         if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
4089                 return (cache_fpl_partial(fpl));
4090         }
4091         return (0);
4092 }
4093
4094 static void
4095 cache_fplookup_parse_advance(struct cache_fpl *fpl)
4096 {
4097         struct nameidata *ndp;
4098         struct componentname *cnp;
4099
4100         ndp = fpl->ndp;
4101         cnp = fpl->cnp;
4102
4103         cnp->cn_nameptr = ndp->ni_next;
4104         while (*cnp->cn_nameptr == '/') {
4105                 cnp->cn_nameptr++;
4106                 ndp->ni_pathlen--;
4107         }
4108 }
4109
4110 static int __noinline
4111 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
4112 {
4113
4114         switch (error) {
4115         case EAGAIN:
4116                 /*
4117                  * Can happen when racing against vgone.
4118                  * */
4119         case EOPNOTSUPP:
4120                 cache_fpl_partial(fpl);
4121                 break;
4122         default:
4123                 /*
4124                  * See the API contract for VOP_FPLOOKUP_VEXEC.
4125                  */
4126                 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
4127                         error = cache_fpl_aborted(fpl);
4128                 } else {
4129                         cache_fpl_smr_exit(fpl);
4130                         cache_fpl_handled(fpl, error);
4131                 }
4132                 break;
4133         }
4134         return (error);
4135 }
4136
4137 static int
4138 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
4139 {
4140         struct nameidata *ndp;
4141         struct componentname *cnp;
4142         struct mount *mp;
4143         int error;
4144
4145         error = CACHE_FPL_FAILED;
4146         ndp = fpl->ndp;
4147         cnp = fpl->cnp;
4148
4149         cache_fpl_checkpoint(fpl, &fpl->snd);
4150
4151         fpl->dvp = dvp;
4152         fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
4153         if (seqc_in_modify(fpl->dvp_seqc)) {
4154                 cache_fpl_aborted(fpl);
4155                 goto out;
4156         }
4157         mp = atomic_load_ptr(&fpl->dvp->v_mount);
4158         if (!cache_fplookup_mp_supported(mp)) {
4159                 cache_fpl_aborted(fpl);
4160                 goto out;
4161         }
4162
4163         VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4164
4165         for (;;) {
4166                 error = cache_fplookup_parse(fpl);
4167                 if (__predict_false(error != 0)) {
4168                         break;
4169                 }
4170
4171                 VNPASS(cache_fplookup_vnode_supported(fpl->dvp), fpl->dvp);
4172
4173                 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
4174                 if (__predict_false(error != 0)) {
4175                         error = cache_fplookup_failed_vexec(fpl, error);
4176                         break;
4177                 }
4178
4179                 if (__predict_false(cache_fpl_isdotdot(cnp))) {
4180                         error = cache_fplookup_dotdot(fpl);
4181                         if (__predict_false(error != 0)) {
4182                                 break;
4183                         }
4184                 } else {
4185                         error = cache_fplookup_next(fpl);
4186                         if (__predict_false(error != 0)) {
4187                                 break;
4188                         }
4189
4190                         VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4191
4192                         if (cache_fplookup_need_climb_mount(fpl)) {
4193                                 error = cache_fplookup_climb_mount(fpl);
4194                                 if (__predict_false(error != 0)) {
4195                                         break;
4196                                 }
4197                         }
4198                 }
4199
4200                 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
4201
4202                 if (cache_fpl_islastcn(ndp)) {
4203                         error = cache_fplookup_final(fpl);
4204                         break;
4205                 }
4206
4207                 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
4208                         error = cache_fpl_aborted(fpl);
4209                         break;
4210                 }
4211
4212                 fpl->dvp = fpl->tvp;
4213                 fpl->dvp_seqc = fpl->tvp_seqc;
4214
4215                 cache_fplookup_parse_advance(fpl);
4216                 cache_fpl_checkpoint(fpl, &fpl->snd);
4217         }
4218 out:
4219         switch (fpl->status) {
4220         case CACHE_FPL_STATUS_UNSET:
4221                 __assert_unreachable();
4222                 break;
4223         case CACHE_FPL_STATUS_PARTIAL:
4224                 cache_fpl_smr_assert_entered(fpl);
4225                 return (cache_fplookup_partial_setup(fpl));
4226         case CACHE_FPL_STATUS_ABORTED:
4227                 if (fpl->in_smr)
4228                         cache_fpl_smr_exit(fpl);
4229                 return (CACHE_FPL_FAILED);
4230         case CACHE_FPL_STATUS_HANDLED:
4231                 MPASS(error != CACHE_FPL_FAILED);
4232                 cache_fpl_smr_assert_not_entered(fpl);
4233                 if (__predict_false(error != 0)) {
4234                         ndp->ni_dvp = NULL;
4235                         ndp->ni_vp = NULL;
4236                         cache_fpl_cleanup_cnp(cnp);
4237                         return (error);
4238                 }
4239                 ndp->ni_dvp = fpl->dvp;
4240                 ndp->ni_vp = fpl->tvp;
4241                 if (cnp->cn_flags & SAVENAME)
4242                         cnp->cn_flags |= HASBUF;
4243                 else
4244                         cache_fpl_cleanup_cnp(cnp);
4245                 return (error);
4246         }
4247 }
4248
4249 /*
4250  * Fast path lookup protected with SMR and sequence counters.
4251  *
4252  * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
4253  *
4254  * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
4255  * outlined below.
4256  *
4257  * Traditional vnode lookup conceptually looks like this:
4258  *
4259  * vn_lock(current);
4260  * for (;;) {
4261  *      next = find();
4262  *      vn_lock(next);
4263  *      vn_unlock(current);
4264  *      current = next;
4265  *      if (last)
4266  *          break;
4267  * }
4268  * return (current);
4269  *
4270  * Each jump to the next vnode is safe memory-wise and atomic with respect to
4271  * any modifications thanks to holding respective locks.
4272  *
4273  * The same guarantee can be provided with a combination of safe memory
4274  * reclamation and sequence counters instead. If all operations which affect
4275  * the relationship between the current vnode and the one we are looking for
4276  * also modify the counter, we can verify whether all the conditions held as
4277  * we made the jump. This includes things like permissions, mount points etc.
4278  * Counter modification is provided by enclosing relevant places in
4279  * vn_seqc_write_begin()/end() calls.
4280  *
4281  * Thus this translates to:
4282  *
4283  * vfs_smr_enter();
4284  * dvp_seqc = seqc_read_any(dvp);
4285  * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
4286  *     abort();
4287  * for (;;) {
4288  *      tvp = find();
4289  *      tvp_seqc = seqc_read_any(tvp);
4290  *      if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
4291  *          abort();
4292  *      if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
4293  *          abort();
4294  *      dvp = tvp; // we know nothing of importance has changed
4295  *      dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
4296  *      if (last)
4297  *          break;
4298  * }
4299  * vget(); // secure the vnode
4300  * if (!seqc_consistent(tvp, tvp_seqc) // final check
4301  *          abort();
4302  * // at this point we know nothing has changed for any parent<->child pair
4303  * // as they were crossed during the lookup, meaning we matched the guarantee
4304  * // of the locked variant
4305  * return (tvp);
4306  *
4307  * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
4308  * - they are called while within vfs_smr protection which they must never exit
4309  * - EAGAIN can be returned to denote checking could not be performed, it is
4310  *   always valid to return it
4311  * - if the sequence counter has not changed the result must be valid
4312  * - if the sequence counter has changed both false positives and false negatives
4313  *   are permitted (since the result will be rejected later)
4314  * - for simple cases of unix permission checks vaccess_vexec_smr can be used
4315  *
4316  * Caveats to watch out for:
4317  * - vnodes are passed unlocked and unreferenced with nothing stopping
4318  *   VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
4319  *   to use atomic_load_ptr to fetch it.
4320  * - the aforementioned object can also get freed, meaning absent other means it
4321  *   should be protected with vfs_smr
4322  * - either safely checking permissions as they are modified or guaranteeing
4323  *   their stability is left to the routine
4324  */
4325 int
4326 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
4327     struct pwd **pwdp)
4328 {
4329         struct cache_fpl fpl;
4330         struct pwd *pwd;
4331         struct vnode *dvp;
4332         struct componentname *cnp;
4333         struct nameidata_saved orig;
4334         int error;
4335
4336         MPASS(ndp->ni_lcf == 0);
4337
4338         fpl.status = CACHE_FPL_STATUS_UNSET;
4339         fpl.ndp = ndp;
4340         fpl.cnp = &ndp->ni_cnd;
4341         MPASS(curthread == fpl.cnp->cn_thread);
4342
4343         if ((fpl.cnp->cn_flags & SAVESTART) != 0)
4344                 MPASS(fpl.cnp->cn_nameiop != LOOKUP);
4345
4346         if (!cache_can_fplookup(&fpl)) {
4347                 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4348                 *status = fpl.status;
4349                 return (EOPNOTSUPP);
4350         }
4351
4352         cache_fpl_checkpoint(&fpl, &orig);
4353
4354         cache_fpl_smr_enter_initial(&fpl);
4355         pwd = pwd_get_smr();
4356         fpl.pwd = pwd;
4357         ndp->ni_rootdir = pwd->pwd_rdir;
4358         ndp->ni_topdir = pwd->pwd_jdir;
4359
4360         cnp = fpl.cnp;
4361         cnp->cn_nameptr = cnp->cn_pnbuf;
4362         if (cnp->cn_pnbuf[0] == '/') {
4363                 cache_fpl_handle_root(ndp, &dvp);
4364         } else {
4365                 MPASS(ndp->ni_dirfd == AT_FDCWD);
4366                 dvp = pwd->pwd_cdir;
4367         }
4368
4369         SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
4370
4371         error = cache_fplookup_impl(dvp, &fpl);
4372         cache_fpl_smr_assert_not_entered(&fpl);
4373         SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
4374
4375         *status = fpl.status;
4376         switch (fpl.status) {
4377         case CACHE_FPL_STATUS_UNSET:
4378                 __assert_unreachable();
4379                 break;
4380         case CACHE_FPL_STATUS_HANDLED:
4381                 SDT_PROBE3(vfs, namei, lookup, return, error,
4382                     (error == 0 ? ndp->ni_vp : NULL), true);
4383                 break;
4384         case CACHE_FPL_STATUS_PARTIAL:
4385                 *pwdp = fpl.pwd;
4386                 /*
4387                  * Status restored by cache_fplookup_partial_setup.
4388                  */
4389                 break;
4390         case CACHE_FPL_STATUS_ABORTED:
4391                 cache_fpl_restore(&fpl, &orig);
4392                 break;
4393         }
4394         return (error);
4395 }