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