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