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