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