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