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